/** @license
twilio-ip-messaging.js v0.9 (0.9.2)
The following license applies to all parts of this software except as
documented below.
Copyright (c) 2015, Twilio, inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of Twilio nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software includes javascript-state-machine under the following license.
Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
This software includes durational under the following license.
Copyright (c) 2014 Micheil Smith
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This software includes loglevel under the following license.
Copyright (c) 2013 Tim Perry
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
This software includes q under the following license.
Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
This software includes platform.js under the following license.
Copyright 2014 Benjamin Tan
Copyright 2011-2015 John-David Dalton
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(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
*/
DataSyncClient.prototype.openStream = function (uri) {
var _this5 = this;
return this._network.get(uri).then(function (response) {
if (response.body.type !== 'stream') {
throw new Error('Unexpected data type: ' + response.body.type);
}
log.debug('DSS I: data stream opened: ', response);
return new DataStream(_this5._getDependencies(), response.body);
});
};
/**
* Creates an instance of Map
* @return Promise
*/
DataSyncClient.prototype.createMap = function (purpose, context) {
var _this6 = this;
var payload = {};
if (typeof purpose !== 'undefined') {
payload.purpose = purpose;
}
if (typeof context !== 'undefined') {
payload.context = context;
}
return this._network.post(this._config.mapsUri, payload).then(function (response) {
return new DataMap(_this6._getDependencies(), response.body);
});
};
/**
* Open an existing Map
* @param {string} uri
* @return Promise
*/
DataSyncClient.prototype.openMap = function (uri) {
var _this7 = this;
return this._network.get(uri).then(function (response) {
if (response.body.type !== 'map') {
throw new Error('Unexpected data type: ' + response.body.type);
}
return new DataMap(_this7._getDependencies(), response.body);
});
};
/**
* Set authentication token
* If token is already set, it will be replaced with the new one
*
* @param {String} Authentication token
*/
DataSyncClient.prototype.setAuthToken = function (token) {
log.info('DSS I: authTokenUpdated');
this._config.updateToken(token);
};
Object.freeze(DataSyncClient);
module.exports = DataSyncClient;
},{"./configuration.js":4,"./dataentity.js":5,"./datamap.js":6,"./datastream.js":7,"./network.js":8,"./router.js":9,"./subscriptions.js":10,"loglevel":265}],3:[function(require,module,exports){
'use strict';
/**
* @class
* @classdesc Entity of event stream collection
*/
function CollectionEntity(data) {
var _this = this;
Object.defineProperties(this, {
_id: { value: data.id, writable: false },
_uri: { value: data.uri, writable: false },
_value: { value: data.value, writable: true },
id: { enumerable: true,
get: function get() {
return _this._id;
} },
uri: { enumerable: true,
get: function get() {
return _this._uri;
} },
value: { enumerable: true,
get: function get() {
return _this._value;
} }
});
}
CollectionEntity.prototype._update = function (value) {
this._value = value;
};
Object.freeze(CollectionEntity);
module.exports = CollectionEntity;
},{}],4:[function(require,module,exports){
'use strict';
var CDS_URI = 'https://cds.twilio.com';
var SUBSCRIPTIONS_PATH = '/v1/subscriptions';
var MAPS_PATH = '/v2/Maps';
var STREAMS_PATH = '/v2/Streams';
var ENTITIES_PATH = '/v2/Entities';
/**
* @param {String} token - authentication token
*
* @class DataSyncConfig
* @classdesc Settings container for the DataSync library
*/
function DataSyncConfig(token, options) {
var _this = this;
options = (options || {}).DataSync || {};
var baseUri = options.cdsUri || CDS_URI;
var settings = {
subscriptionsUri: baseUri + SUBSCRIPTIONS_PATH,
entitiesUri: baseUri + MAPS_PATH,
streamsUri: baseUri + STREAMS_PATH,
mapsUri: baseUri + ENTITIES_PATH
};
Object.defineProperties(this, {
_token: { value: token, writable: true },
token: { enumerable: true, get: function get() {
return _this._token;
} },
subscriptionsUri: { enumerable: true, get: function get() {
return settings.subscriptionsUri;
} },
entitiesUri: { enumerable: true, get: function get() {
return settings.entitiesUri;
} },
streamsUri: { enumerable: true, get: function get() {
return settings.streamsUri;
} },
mapsUri: { enumerable: true, get: function get() {
return settings.mapsUri;
} }
});
}
DataSyncConfig.prototype.updateToken = function (token) {
this._token = token;
};
module.exports = DataSyncConfig;
},{}],5:[function(require,module,exports){
'use strict';
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var JsonDiff = require('../../util/jsondiff');
var log = require('loglevel');
/**
* @class DataEntity
* @classdesc Represents a DSS object
*
* @constructor
*/
function DataEntity(params, descriptor) {
var _this = this;
Object.defineProperties(this, {
_config: { value: params.config },
_datasync: { value: params.datasync },
_network: { value: params.network },
_router: { value: params.router },
_pendingListeners: { value: {} },
_isSynced: { value: true, writable: true },
_links: { value: descriptor.links },
_entityId: { value: descriptor.entity_id },
_revision: { value: descriptor.entity_revision, writable: true },
_data: { value: descriptor.data, writable: true },
uri: { enumerable: true, get: function get() {
return _this._links.entity;
} },
id: { enumerable: true, get: function get() {
return _this._entityId;
} },
revision: { enumerable: true, get: function get() {
return _this._revision;
} }
});
EventEmitter.call(this);
this._initialize();
}
inherits(DataEntity, EventEmitter);
/**
* @private
*/
DataEntity.prototype._initialize = function () {
var _this2 = this;
['keyAdded', 'keyRemoved', 'keyUpdated'].forEach(function (eventName) {
_this2._pendingListeners[eventName] = {};
_this2.on(eventName, function (path, data) {
var handlers = _this2._pendingListeners[eventName][path] || [];
handlers.forEach(function (handler) {
handler(data);
});
_this2._pendingListeners[eventName][path] = [];
});
});
};
/**
* Update data entity with new data
* @private
*/
DataEntity.prototype._update = function (update) {
switch (update.type) {
case 'entity_update':
var originalData = this._data;
this._revision = update.entity_revision;
this._data = update.data;
this._traverse(originalData, update.data);
this.emit('updated', update.data);
break;
case 'entity_delete':
this.emit('deleted');
}
};
/**
* Calculate diff between old and new data
* @private
*/
DataEntity.prototype._traverse = function (originalData, updatedData) {
var _this3 = this;
var diff = JsonDiff.diff(originalData, updatedData);
diff.forEach(function (row) {
if (row.op === 'add') {
_this3.emit('keyAdded', row.path, row.value);
} else if (row.op === 'replace') {
_this3.emit('keyUpdated', row.path, row.value);
} else if (row.op === 'remove') {
_this3.emit('keyRemoved', row.path);
}
});
};
/**
* Notifies user that he should resolve the conflict
* If user hasn't setup any conflict event handlers, it fails immediately
* @private
*/
DataEntity.prototype._resolveConflict = function (conflictResolver) {
var _this4 = this;
if (!(conflictResolver && typeof conflictResolver === 'function')) {
return Promise.reject(new Error('Can\'t resolve conflict'));
}
return new Promise(function (resolve, reject) {
var revision = _this4._revision;
var localData = _this4._data;
var rollback = (function rollback(err) {
this._revision = revision;
this._data = localData;
reject(err);
}).bind(_this4);
_this4.forceSync().then(function () {
conflictResolver({
localData: localData,
remoteData: _this4._data,
resolve: resolve,
reject: rollback
});
});
});
};
/**
* Subscribe to changes of data entity
*/
DataEntity.prototype.subscribe = function () {
return this._router.subscribe(this.uri, this);
};
/**
* Unsubscribe from changes of current data entity
*/
DataEntity.prototype.unsubscribe = function () {
return this._router.unsubscribe(this.uri, this);
};
/**
* @returns {Object} Internal data of entity
*/
DataEntity.prototype.getData = function () {
return this._data;
};
DataEntity.prototype.setData = function (data) {
this._data = data;
this._isSynced = false;
};
/**
* @private
*/
DataEntity.prototype._pushChangesInternal = function (resolve, reject) {
var _this5 = this;
return this._network.put(this.uri, { data: this._data }, this._revision).then(function (response) {
var revision = response.body.entity_revision;
log.debug('DSS: entity updated: ', response, ' new revision is: ', revision);
resolve(response);
_this5._router.emulateUpdate(_this5, _this5.uri, { revision: revision, data: _this5._data });
}).catch(reject);
};
/**
* Push changes to the server
* @public
*/
DataEntity.prototype.pushChanges = function (conflictResolver) {
var _this6 = this;
return new Promise(function (resolve, reject) {
var handleError = (function handleError(err) {
if (err.status === 412) {
log.info('DSS I: version conflict detected!');
this._resolveConflict(conflictResolver).then(handleMerge).catch(reject);
} else {
log.error('DSS E: failed to push local changes to server: ', err);
reject(err);
}
}).bind(_this6);
var handleMerge = (function handleMerge(mergedData) {
this.setData(mergedData);
setTimeout((function () {
this._pushChangesInternal(resolve, handleError);
}).bind(this), 0);
}).bind(_this6);
_this6._pushChangesInternal(resolve, handleError);
});
};
/**
* Get new data from server
*/
DataEntity.prototype.softSync = function () {
var _this7 = this;
/* eslint-disable camelcase */
return this._network.get(this.uri).then(function (response) {
var revision = response.body.entity_revision;
var data = response.body.data;
_this7._update({ entity_revision: revision, type: 'entity_update', data: data });
return _this7;
});
/* eslint-enable camelcase */
};
/**
* Download new data from service and overwrite local changes
* Won't fire any events and callbacks about changes
*/
DataEntity.prototype.forceSync = function () {
var _this8 = this;
return this._network.get(this.uri).then(function (response) {
_this8._revision = response.body.entity_revision;
_this8._data = response.body.data;
return _this8;
}).catch(function (reason) {
log.error('DSS E: failed to get entity: ', reason);
});
};
DataEntity.prototype.addEventHandler = function (eventName, path, handler) {
var handlers = this._pendingListeners[eventName][path] || [];
handlers.push(handler);
this._pendingListeners[eventName][path] = handlers;
};
/**
* Get value by given path
* @param {string} path JSON path
*/
DataEntity.prototype.value = function (path) {
var result = undefined;
try {
var pathArr = path.replace(/^\/|\/$/gm, '').split('/');
var obj = this.getData();
pathArr.forEach(function (el) {
obj = obj[el];
});
result = obj;
} finally {
return result;
}
};
/**
* Updates the value by given path
*
* Value should be the same type - you can't update
* the object or array with the string type
*
* To replace node with the value of another type, see {@see replace}
*
* @param path - JSON Pointer path to the node
* @param value - The value to update.
*/
DataEntity.prototype.update = function (path, value) {
var pathArr = path.replace(/^\/|\/$/gm, '').split('/').filter(function (el) {
return el !== '';
});
var found = true;
var obj = this.getData();
for (var idx = 0; idx < pathArr.length; ++idx) {
obj = obj[pathArr[idx]];
if (typeof obj === 'undefined') {
found = false;
break;
}
}
if (found) {
if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== (typeof value === 'undefined' ? 'undefined' : _typeof(value))) {
log.error('Can\'t have different type when updating the value!');
return false;
}
switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) {
case 'object':
for (var key in value) {
obj[key] = value[key];
}
break;
default:
obj = value;
}
this._isSynced = false;
return true;
}
return false;
};
Object.freeze(DataEntity);
module.exports = DataEntity;
},{"../../util/jsondiff":34,"events":232,"loglevel":265,"util":261}],6:[function(require,module,exports){
'use strict';
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var util = require('../../util');
var Entity = require('./collectionentity');
/**
* @class DataMap
* @classdec Map collection
*/
function DataMap(deps, descriptor) {
var _this = this;
var cacheState = {
ensured: false
};
Object.defineProperties(this, {
_deps: { value: deps },
_descriptor: { value: descriptor },
_cacheState: { value: cacheState },
_links: { get: function get() {
return _this._descriptor.links;
} },
_revision: { value: descriptor.revision, writable: true },
_context: { writable: true },
_entities: { value: new Map() },
uri: { enumerable: true,
get: function get() {
return _this._descriptor.links.collection;
} },
entitiesUri: { enumerable: true,
get: function get() {
return _this._descriptor.links.entities;
} },
revision: { enumerable: true,
get: function get() {
return _this._revision;
} }
});
EventEmitter.call(this);
}
inherits(DataMap, EventEmitter);
DataMap.prototype._uriForKey = function (key) {
return this._links.entities + '?id=' + key;
};
DataMap.prototype._tryPostOrUpdate = function (uri, data) {
var _this2 = this;
return new Promise(function (resolve, reject) {
_this2._deps.network.post(uri, data).then(function (response) {
return resolve({ uri: response.body.links.entity });
}).catch(function (err) {
if (err.status === 409) {
var _ret = (function () {
var location = undefined;
try {
var body = JSON.parse(err.body);
location = body.links.entity;
} catch (e) {
reject(e);
}
return {
v: _this2._deps.network.put(location, data).then(function () {
return resolve({ uri: location });
}).catch(reject)
};
})();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
reject(err);
});
});
};
/**
* Query events from servie and apply changes to the collection
* @private
*/
DataMap.prototype._queryEvents = function () {
var _this3 = this;
var uri = this._links.events + '?from=' + this._revision + '&limit=100';
return this._deps.network.get(uri).then(function (response) {
response.body.results.forEach(function (event) {
return _this3._update(event);
});
});
};
/**
* @return Promise Context of collection
*/
DataMap.prototype.getContext = function () {
var _this4 = this;
if (typeof this._context !== 'undefined') {
return Promise.resolve(this._context);
}
return this._deps.network.get(this._links.context).then(function (response) {
_this4._context = response.body.data;
return _this4._context;
});
};
DataMap.prototype.updateContext = function (context) {
var _this5 = this;
return this._deps.network.put(this._links.context, { data: context }).then(function () {
_this5._context = context;
_this5.emit('contextUpdated', context);
});
};
DataMap.prototype.subscribe = function () {
return this._deps.router.subscribe(this._links.collection, this);
};
DataMap.prototype.unsubscribe = function () {
return this._deps.router.unsubscribe(this._links.collection, this);
};
DataMap.prototype.set = function (key, value) {
var _this6 = this;
var entity = this._entities.get(key);
if (typeof entity !== 'undefined') {
var _uri = entity.uri;
return this._deps.network.put(_uri, { data: value }).then(function () {
entity._update(value);
});
}
var uri = this._uriForKey(key);
return this._tryPostOrUpdate(uri, { data: value }).then(function (result) {
entity = new Entity({ id: key,
uri: result.uri,
value: value });
_this6._entities.set(key, entity);
});
};
/**
* @param String key String identifier of entity in a map
* @return Promise
*/
DataMap.prototype.get = function (key) {
var _this7 = this;
return new Promise(function (resolve, reject) {
if (_this7._entities.has(key)) {
resolve(_this7._entities.get(key));
} else {
var uri = _this7._uriForKey(key);
_this7._deps.network.get(uri).then(function (response) {
var entityData = response.body.results.find(function (el) {
return el.entity_id === key;
});
if (entityData) {
var entity = new Entity({ id: entityData.entity_id,
uri: entityData.links.entity,
value: entityData.data });
_this7._entities.set(key, entity);
resolve(entity);
} else {
reject(new Error('Entity not found'));
}
});
}
});
};
/**
* Delete an entity by given key
* @return Promise
*/
DataMap.prototype.remove = function (key) {
var _this8 = this;
return this.get(key).then(function (entity) {
return _this8._deps.network.delete(entity.uri);
}).then(function () {
_this8._entities.delete(key);
});
};
DataMap.prototype.query = function (from, limit, direction) {
var _this9 = this;
limit = limit || 50;
direction = direction || 'forward';
var uri = new util.UriBuilder(this._links.entities).arg('from', from).arg('limit', limit).arg('direction', direction).build();
return this._deps.network.get(uri).then(function (result) {
var queryResult = result.body.results.map(function (el) {
return new Entity({ id: el.entity_id,
uri: el.links.entity,
value: el.data });
});
queryResult.forEach(function (entity) {
return _this9._entities.set(entity.id, entity);
});
return queryResult;
});
};
/**
* Synchronizes object with state on a server
* Fires events about all changes
*
* DataMap#entityAdded
* DataMap#entityRemoved
* DataMap#entityUpdated
* DataMap#contextUpdated
*
* @public
*/
DataMap.prototype.softSync = function () {
this._queryEvents();
};
/**
* Enumerate through all of maps entities
* It always triggers server interaction when being called for the first time for an object, so could be slow
* @param Function handler Function to handle each argument
*/
DataMap.prototype.forEach = function (handler) {
var _this10 = this;
var pageSize = 50;
return new Promise(function (resolve, reject) {
if (_this10._cacheState.ensured) {
_this10._entities.forEach(handler);
resolve();
} else {
(function () {
var processChunk = function processChunk(from, handleElement, handleEnd) {
var _pageSize = pageSize;
var _shouldStrip = false;
if (typeof from !== 'undefined') {
_pageSize += 1;
_shouldStrip = true;
}
_this10.query(from, _pageSize, 'forward').then(function (result) {
if (_shouldStrip) {
result.shift();
}return result;
}) // always strip first element
.then(function (result) {
result.forEach(function (el) {
handler(el);
});return result;
}).then(function (result) {
if (result.length === pageSize) {
(function () {
var anchor = result[result.length - 1].id;
setTimeout(function () {
return processChunk(anchor, handleElement, handleEnd);
});
})();
} else {
handleEnd();
}
}).catch(reject);
};
var _undefined = undefined;
processChunk(_undefined, handler, function () {
_this10._cacheState.ensured = true;resolve();
});
})();
}
});
};
/**
* Handle update, which came from the server
*/
DataMap.prototype._update = function (update) {
switch (update.type) {
case 'entity_create':
{
this._handleEntityAdded(update.entity_id, update.links.entity, update.data);
}
break;
case 'entity_update':
{
this._handleEntityUpdated(update.entity_id, update.links.entity, update.data);
}
break;
case 'entity_delete':
{
this._handleEntityRemoved(update.entity_id, update.links.entity, update.data);
}
break;
case 'context_update':
{
this._handleContextUpdate(update.data);
}
break;
case 'collection_delete':
{
this.emit('deleted');
}
break;
}
if (this._revision === update.event_id - 1) {
this._revision = update.event_id;
}
};
/**
* Handle entity insertion event, coming from server
* @private
*/
DataMap.prototype._handleEntityAdded = function (entityId, uri, data) {
if (!this._entities.has(entityId)) {
var streamEntity = new Entity({ id: entityId,
uri: uri,
value: data });
this._entities.set(entityId, streamEntity);
this.emit('entityAdded', streamEntity);
}
};
/**
* Handle new value of entity, coming from server
* @private
*/
DataMap.prototype._handleEntityUpdated = function (entityId, uri, data) {
var streamEntity = new Entity({ id: entityId,
uri: uri,
value: data });
this._entities.set(entityId, streamEntity);
this.emit('entityUpdated', streamEntity);
};
/**
* @private
*/
DataMap.prototype._handleEntityRemoved = function (entityId) {
if (this._entities.has(entityId)) {
this._entities.delete(entityId);
this.emit('entityRemoved', entityId);
}
};
DataMap.prototype._handleContextUpdate = function (data) {
this._context = data;
this.emit('contextUpdated', data);
};
Object.freeze(DataMap);
module.exports = DataMap;
},{"../../util":33,"./collectionentity":3,"events":232,"util":261}],7:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var util = require('../../util');
var log = require('loglevel');
var Entity = require('./collectionentity');
/**
* @class EventStream
* @classdesc
*/
function EventStream(deps, descriptor) {
var _this = this;
Object.defineProperties(this, {
_config: { value: deps.config, writable: false },
_deps: { value: deps, writable: false },
_descriptor: { value: descriptor },
_links: { get: function get() {
return _this._descriptor.links;
} },
_context: { writable: true },
_revision: { value: descriptor.revision, writable: true },
_entities: { value: new Map(), writable: false },
uri: { enumerable: true,
get: function get() {
return _this._descriptor.links.collection;
} },
entitiesUri: { get: function get() {
return _this._descriptor.links.entities;
} },
revision: { enumerable: true,
get: function get() {
return _this._revision;
} }
});
EventEmitter.call(this);
}
inherits(EventStream, EventEmitter);
/**
* @private
*/
EventStream.prototype._uriForKey = function (id) {
return this._links.entities + '/' + id;
};
/**
* Subscribe on event stream events
* Should be called to receive entityAdded, entityUpdated, entityRemoved events
*/
EventStream.prototype.subscribe = function () {
return this._deps.router.subscribe(this._links.collection, this);
};
/**
* Unsubscribe from event stream event
* Events will no longer be fired
*/
EventStream.prototype.unsubscribe = function () {
return this._deps.router.unsubscribe(this._links.collection, this);
};
/**
* Add element to the collection
* @param {Object} value - value to add
* @returns {Promise} Id of a new element
*/
EventStream.prototype.add = function (value) {
var _this2 = this;
return this._deps.network.post(this._links.entities, { data: value }).then(function (response) {
var streamEntity = new Entity({ id: Number(response.body.entity_id),
uri: response.body.links.entity,
value: value });
_this2._entities.set(streamEntity.id, streamEntity);
return streamEntity.id;
});
};
/**
* Remove event stream entity by id
* @returns Promise to remove, which may fail
*/
EventStream.prototype.remove = function (id) {
var uri = this._uriForKey(id);
return this._deps.network.delete(uri).then(function () {
return;
});
};
EventStream.prototype.update = function (id, value) {
var uri = this._uriForKey(id);
return this._deps.network.put(uri, { data: value }).then(function () {
return;
});
};
/**
* Retrieve event stream element by id
* @param {Number} id - entity id
*/
EventStream.prototype.get = function (entityId) {
var _this3 = this;
if (this._entities.has(entityId)) {
return Promise.resolve(this._entities.get(entityId));
}
var uri = this._uriForKey(entityId);
return this._deps.network.get(uri).then(function (response) {
var streamEntity = new Entity({ id: Number(response.body.entity_id),
uri: uri,
value: response.body.data });
_this3._entities.set(streamEntity.id, streamEntity);
return streamEntity;
});
};
/**
* Query events from servie and apply changes to the collection
* @private
*/
EventStream.prototype._queryEvents = function () {
var _this4 = this;
var uri = this._links.events + '?from=' + this._revision + '&limit=100';
return this._deps.network.get(uri).then(function (response) {
response.body.results.forEach(function (event) {
return _this4._update(event);
});
});
};
/**
* Query entities from the stream
*
* @param {String} direction Direction for querying, can be 'forward' or 'backwards'
* @param {String} from Entity, which should be used as an anchor, or "end" if it should be got from end
* @param {Number} limit - amount of entities to get
* @param {String} order - order of entities, should be 'asc' or 'desc'
*/
EventStream.prototype.queryEntities = function (direction, from, limit, order) {
var _this5 = this;
direction = direction || 'forward';
order = order || 'asc';
var uri = new util.UriBuilder(this._links.entities).arg('direction', direction).arg('from', from).arg('limit', limit).arg('order', order).build();
return this._deps.network.get(uri).then(function (result) {
var queryResult = result.body.results.map(function (el) {
return new Entity({ id: Number(el.entity_id),
uri: el.links.entity,
value: el.data });
});
queryResult.forEach(function (entity) {
return _this5._entities.set(entity.id, entity);
});
return queryResult;
});
};
/**
* Query entities from the stream
*
* @param {String} from Entity, which should be used as an anchor, or "end" if it should be got from end
* @param {Number} count - amount of entities to get
* @param {String} order - order of entities, should be 'asc' or 'desc'
*/
EventStream.prototype.queryEntitiesBefore = function (from, count, order) {
return this.queryEntities('backwards', from, count, order);
};
/**
* Query last entities from event stream
* @param {Integer} count Number of entities to fetch
* @param {String} order Order of entites. Could be 'asc' or 'desc'
*/
EventStream.prototype.queryLastEntities = function (count, order) {
return this.queryEntitiesBefore('end', count, order);
};
/**
* @return Promise Context of collection
*/
EventStream.prototype.getContext = function () {
var _this6 = this;
if (typeof this._context !== 'undefined') {
return Promise.resolve(this._context);
}
return this._deps.network.get(this._links.context).then(function (response) {
_this6._context = response.body.data;
return _this6._context;
});
};
EventStream.prototype.updateContext = function (context) {
var _this7 = this;
return this._deps.network.put(this._links.context, { data: context }).then(function () {
_this7._context = context;
_this7.emit('contextUpdated', context);
}).catch(function (err) {
log.error('Failed to update context', err);
throw err;
});
};
/**
* Force to check for modifications on server
* If there are any modifications, object will fire all appropriate callbacks
*/
EventStream.prototype.softSync = function () {
return this._queryEvents();
};
/**
* Handle update, which came from the server
*/
EventStream.prototype._update = function (update) {
var entityId = Number(update.entity_id);
switch (update.type) {
case 'entity_create':
{
this._handleEntityAdded(entityId, update.links.entity, update.data);
}
break;
case 'entity_update':
{
this._handleEntityUpdated(entityId, update.links.entity, update.data);
}
break;
case 'entity_delete':
{
this._handleEntityRemoved(entityId, update);
}
break;
case 'context_update':
{
this._handleContextUpdate(update.data);
}
break;
case 'collection_delete':
{
this.emit('deleted');
}
break;
}
if (this._revision === update.event_id - 1) {
this._revision = update.event_id;
}
};
/**
* Handle entity insertion event, coming from server
* @private
*/
EventStream.prototype._handleEntityAdded = function (entityId, uri, data) {
if (!this._entities.has(entityId)) {
var streamEntity = new Entity({ id: Number(entityId),
uri: uri,
value: data });
this._entities.set(entityId, streamEntity);
this.emit('entityAdded', streamEntity);
}
};
/**
* Handle new value of entity, coming from server
* @private
*/
EventStream.prototype._handleEntityUpdated = function (entityId, uri, data) {
var streamEntity = new Entity({ id: entityId,
uri: uri,
value: data });
this._entities.set(entityId, streamEntity);
this.emit('entityUpdated', streamEntity);
};
/**
* @private
*/
EventStream.prototype._handleEntityRemoved = function (entityId) {
if (this._entities.has(entityId)) {
this._entities.delete(entityId);
this.emit('entityRemoved', entityId);
}
};
EventStream.prototype._handleContextUpdate = function (data) {
this._context = data;
this.emit('contextUpdated', data);
};
Object.freeze(EventStream);
module.exports = EventStream;
},{"../../util":33,"./collectionentity":3,"events":232,"loglevel":265,"util":261}],8:[function(require,module,exports){
'use strict';
/**
* @class Network
* @classdesc Separates network operations to make it possible to add some optimization/caching strategies
*/
function Network(config, transport) {
var _this = this;
Object.defineProperties(this, {
_config: { value: config },
_transport: { value: transport },
_headers: { get: function get() {
return _this._getHeaders();
} }
});
}
Network.prototype._getHeaders = function () {
return {
'Content-Type': 'application/json',
'X-Twilio-Token': this._config.token
};
};
/**
* Make a GET request by given URI
* @Returns Promise Result of successful get request
*/
Network.prototype.get = function (uri) {
return this._transport.get(uri, this._headers);
};
Network.prototype.post = function (uri, body) {
return this._transport.post(uri, this._headers, body);
};
Network.prototype.put = function (uri, body, revision) {
/*
Temporary disable this check.
Need to understand first, do we have such scenarios
if (typeof revision === 'undefined') {
throw new Error('Can\'t make a PUT operation with undefined revision');
}
*/
var headers = {
'Content-Type': 'application/json',
'X-Twilio-Token': this._config.token
};
if (typeof revision !== 'undefined') {
headers['If-Match'] = revision;
}
return this._transport.put(uri, headers, body);
};
Network.prototype.delete = function (uri) {
return this._transport.delete(uri, this._headers);
};
Object.freeze(Network);
module.exports = Network;
},{}],9:[function(require,module,exports){
'use strict';
var util = require('../../util');
var log = require('loglevel');
var COREDATA_ENTITY_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.entity';
var COREDATA_STREAM_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.stream';
var COREDATA_MAP_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.map';
/**
* @class Router
* @classdesc Routes all incoming messages to the consumers
*/
function Router(params) {
Object.defineProperties(this, {
_config: { value: params.config },
_subscriptions: { value: params.subscriptions }
});
}
/**
* Entry point for all incoming messages
* @param {String} type - Type of incoming message
* @param {Object} message - Message to route
*/
Router.prototype.onMessage = function (type, message) {
log.trace('DSS I: message ', type, ': ', message);
if (type === COREDATA_ENTITY_NOTIFICATION_TYPE) {
var uri = message.event.links.entity;
this._subscriptions.getSubscribers(uri).forEach(function (entity) {
var copiedMessage = util.deepClone(message);
entity._update(copiedMessage.event);
});
} else if (type === COREDATA_STREAM_NOTIFICATION_TYPE || type === COREDATA_MAP_NOTIFICATION_TYPE) {
var uri = message.collection.links.collection;
this._subscriptions.getSubscribers(uri).forEach(function (eventStream) {
var copiedMessage = util.deepClone(message);
eventStream._update(copiedMessage.event);
});
}
};
/**
* Notifiy all other local instances of entity about changes
*/
Router.prototype.emulateUpdate = function (source, uri, data) {
this._subscriptions.getSubscribers(uri).forEach(function (subscriber) {
if (subscriber !== source) {
var copiedData = util.deepClone(data);
subscriber._update(copiedData);
}
});
};
/**
* Subscribe for events
*/
Router.prototype.subscribe = function (entityUrl, entity) {
return this._subscriptions.add(entityUrl, entity).then(function (isNewSubscription) {
if (isNewSubscription) {
entity.softSync();
}
});
};
/**
* Unsubscribe from events
*/
Router.prototype.unsubscribe = function (entityUrl, entity) {
return this._subscriptions.remove(entityUrl, entity).then(function () {});
};
/**
* Handle transport establishing event
* If we have any subscriptions - we should check object for modifications
*/
Router.prototype.onConnected = function () {
// Endpoint could be an entity or event stream,
// probably need to make some superclass for them
this._subscriptions.forEach(function (uri, endpoint) {
endpoint.softSync();
});
};
Object.freeze(Router);
module.exports = Router;
},{"../../util":33,"loglevel":265}],10:[function(require,module,exports){
'use strict';
var log = require('loglevel');
/**
* @class Subscriptions
* @classdesc Subscriptions container for CDS objects
*
* @constructor
*/
function Subscriptions(config, network) {
Object.defineProperties(this, {
_config: { value: config },
_network: { value: network },
_subscriptions: { value: new Map() },
_serverSubscriptions: { value: new Map() }
});
}
/**
* @private
*/
Subscriptions.prototype._subscribeOnServer = function (entityUri) {
var _this = this;
var uri = this._config.subscriptionsUri;
return this._network.post(uri, {
subscription: {
objectUrl: entityUri,
channelType: 'twilsock'
}
}).then(function (res) {
log.debug('DSS I: subscribed: ', res.headers.Location);
if (!res.headers.Location) {
throw new Error('Location header is absent or inaccessible');
}
_this._serverSubscriptions.set(entityUri, res.headers.Location);
return true;
}).catch(function (err) {
log.error('DSS E: subscription failed: ', err);
throw err;
});
};
/**
* @private
*/
Subscriptions.prototype._unsubscribeOnServer = function (entityUri) {
var _this2 = this;
var subscriptionUri = this._serverSubscriptions.get(entityUri);
if (!subscriptionUri) {
throw new Error('No such subscription');
}
return this._network.delete(subscriptionUri).then(function (res) {
log.debug('DSS I: subscription deleted: ', res);
_this2._serverSubscriptions.delete(entityUri);
return true;
}).catch(function (err) {
if (err.status === 404) {
log.debug('DSS I: subscription is already deleted');
return true;
}
log.error('DSS E: delete subscription failed: ', err);
throw err;
});
};
/**
* Add subscription
* @param {string} uri URI to the server object
* @param {object} endpoint Endpoint object
*/
Subscriptions.prototype.add = function (entityUri, entity) {
var _this3 = this;
if (this._subscriptions.has(entityUri)) {
var _subscribers = this._subscriptions.get(entityUri);
_subscribers.add(entity);
return Promise.resolve(false);
}
var subscribers = new Set();
subscribers.add(entity);
return this._subscribeOnServer(entityUri).then(function () {
_this3._subscriptions.set(entityUri, subscribers);
return true;
});
};
/**
* Remove subscription for the entity
* @param {string} entityUri URI
* @param {object} endpoint Endpoint object
*/
Subscriptions.prototype.remove = function (entityUri, entity) {
if (!this._subscriptions.has(entityUri)) {
return Promise.resolve(true);
}
if (!this._subscriptions.get(entityUri).has(entity)) {
return Promise.resolve(false);
}
var subscribers = this._subscriptions.get(entityUri);
subscribers.delete(entity);
if (subscribers.size > 0) {
this._subscriptions.set(entityUri, subscribers);
return Promise.resolve(false);
}
this._subscriptions.delete(entityUri);
return this._unsubscribeOnServer(entityUri);
};
/**
* Query subscribers for given URI
* @return {set}
*/
Subscriptions.prototype.getSubscribers = function (entityUri) {
var subscribers = this._subscriptions.get(entityUri);
if (subscribers) {
return subscribers;
}
return new Set();
};
/**
* Iterates through all subscriptions
* @param {function} hanlder function to call for each subscription
*/
Subscriptions.prototype.forEach = function (handler) {
this._subscriptions.forEach(function (subscribers, uri) {
subscribers.forEach(function (subscriber) {
return handler(uri, subscriber);
});
});
};
Object.freeze(Subscriptions);
module.exports = Subscriptions;
},{"loglevel":265}],11:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var MembersEntity = require('./data/members');
var Member = require('./member');
var MessagesEntity = require('./data/messages');
var JsonDiff = require('../../util/jsondiff');
var log = require('loglevel');
var fieldMappings = {
attributes: 'attributes',
createdBy: 'createdBy',
dateCreated: 'dateCreated',
dateUpdated: 'dateUpdated',
friendlyName: 'friendlyName',
lastConsumedMessageIndex: 'lastConsumedMessageIndex',
name: 'friendlyName',
sid: 'sid',
status: 'status',
type: 'type',
uniqueName: 'uniqueName'
};
/**
* @class
* @classdesc A Channel represents a remote channel of communication between
* multiple IP Messaging Clients.
* @property {Object} attributes - The Channel's custom attributes.
* @property {String} createdBy - The identity of the User that created this Channel.
* @property {Date} dateCreated - The Date this Channel was created.
* @property {Date} dateUpdated - The Date this Channel was last updated.
* @property {String} friendlyName - The Channel's name.
* @property {Boolean} isPrivate - Whether the channel is private (as opposed to public).
* @property {Number} lastConsumedMessageIndex - Index of the last Message the User has consumed in this Channel.
* @property {Map} members - A map of Members in the Channel.
* @property {Array} messages - An sorted array of Messages in the Channel.
* @property {String} sid - The Channel's unique system identifier.
* @property {Enumeration} status - Whether the Channel is 'known' to local Client, Client is 'invited' to or
* is 'joined' to this Channel.
* @property {Enumeration} type - The Channel's type as a String: ['private', 'public']
* @property {String} uniqueName - The Channel's unique name (tag).
* @fires Channel#memberJoined
* @fires Channel#memberLeft
* @fires Channel#memberUpdated
* @fires Channel#messageAdded
* @fires Channel#messageRemoved
* @fires Channel#messageUpdated
* @fires Channel#typingEnded
* @fires Channel#typingStarted
* @fires Channel#updated
*/
function Channel(session, data, sid) {
var _this = this;
if (!(this instanceof Channel)) {
return new Channel(session, data, sid);
}
var attributes = data.attributes || {};
var createdBy = data.createdBy;
var dateCreated = data.dateCreated;
var dateUpdated = data.dateUpdated;
var friendlyName = data.name || data.friendlyName;
var lastConsumedMessageIndex = data.lastConsumedMessageIndex || null;
var status = 'known';
var type = data.type || Channel.type.PUBLIC;
var uniqueName = data.uniqueName || null;
var uri = data.channelUrl;
if (data.isPrivate) {
type = Channel.type.PRIVATE;
}
try {
JSON.stringify(attributes);
} catch (e) {
throw new Error('Attributes must be a valid JSON object.');
}
var members = new Map();
var membersEntity = new MembersEntity(this, session, members);
membersEntity.on('memberJoined', this.emit.bind(this, 'memberJoined'));
membersEntity.on('memberLeft', this.emit.bind(this, 'memberLeft'));
membersEntity.on('memberUpdated', this.emit.bind(this, 'memberUpdated'));
var messages = [];
var messagesEntity = new MessagesEntity(this, session, messages);
messagesEntity.on('messageAdded', this.emit.bind(this, 'messageAdded'));
messagesEntity.on('messageUpdated', this.emit.bind(this, 'messageUpdated'));
messagesEntity.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
Object.defineProperties(this, {
_attributes: {
get: function get() {
return attributes;
},
set: function set(_attributes) {
return attributes = _attributes;
}
},
_createdBy: {
get: function get() {
return createdBy;
},
set: function set(_createdBy) {
return createdBy = _createdBy;
}
},
_dateCreated: {
get: function get() {
return dateCreated;
},
set: function set(_dateCreated) {
return dateCreated = _dateCreated;
}
},
_dateUpdated: {
get: function get() {
return dateUpdated;
},
set: function set(_dateUpdated) {
return dateUpdated = _dateUpdated;
}
},
_friendlyName: {
get: function get() {
return friendlyName;
},
set: function set(_friendlyName) {
return friendlyName = _friendlyName;
}
},
_lastConsumedMessageIndex: {
get: function get() {
return lastConsumedMessageIndex;
},
set: function set(_lastConsumedMessageIndex) {
return lastConsumedMessageIndex = _lastConsumedMessageIndex;
}
},
_type: {
get: function get() {
return type;
},
set: function set(_type) {
return type = _type;
}
},
_sid: {
get: function get() {
return sid;
},
set: function set(_sid) {
return sid = _sid;
}
},
_status: {
get: function get() {
return status;
},
set: function set(_status) {
return status = _status;
}
},
_uniqueName: {
get: function get() {
return uniqueName;
},
set: function set(_uniqueName) {
return uniqueName = _uniqueName;
}
},
_entityPromise: { value: null, writable: true },
_subscribePromise: { value: null, writable: true },
_lastTypingUpdate: { value: 0, writable: true },
_membersEntity: { value: membersEntity },
_messagesEntity: { value: messagesEntity },
_session: { value: session },
_uri: { value: uri, writable: true },
attributes: {
enumerable: true,
get: function get() {
return attributes;
}
},
createdBy: {
enumerable: true,
get: function get() {
return createdBy;
}
},
dateCreated: {
enumerable: true,
get: function get() {
return dateCreated;
}
},
dateUpdated: {
enumerable: true,
get: function get() {
return dateUpdated;
}
},
friendlyName: {
enumerable: true,
get: function get() {
return friendlyName;
}
},
isPrivate: {
enumerable: true,
get: function get() {
return _this._type === Channel.type.PRIVATE;
}
},
lastConsumedMessageIndex: {
enumerable: true,
get: function get() {
return lastConsumedMessageIndex;
}
},
members: {
enumerable: true,
value: members
},
messages: {
enumerable: true,
value: messages
},
sid: {
enumerable: true,
get: function get() {
return sid;
}
},
status: {
enumerable: true,
get: function get() {
return status;
}
},
type: {
enumerable: true,
get: function get() {
return type;
}
},
uniqueName: {
enumerable: true,
get: function get() {
return uniqueName;
}
}
});
EventEmitter.call(this);
}
inherits(Channel, EventEmitter);
/**
* The type of Channel (Public or private).
* @readonly
* @enum {String}
*/
Channel.type = {
/** 'public' | This channel is Public. */
PUBLIC: 'public',
/** 'private' | This channel is Private. */
PRIVATE: 'private'
};
/**
* The status of the Channel, relative to the Client.
* @readonly
* @enum {String}
*/
Channel.status = {
/** 'known' | This Client knows about the Channel, but the User is neither joined nor invited to it. */
KNOWN: 'known',
/** 'invited' | This Client's User is invited to the Channel. */
INVITED: 'invited',
/** 'joined' | This Client's User is joined to the Channel. */
JOINED: 'joined',
/** 'failed' | This Channel is malformed, or has failed to load. */
FAILED: 'failed'
};
Object.freeze(Channel.type);
Object.freeze(Channel.status);
/**
* Load and Subscribe to this Channel and do not subscribe to its Members and Messages.
* This or _subscribeStreams will need to be called before any events on Channel will fire.
* @returns {Promise}
* @private
*/
Channel.prototype._subscribe = function _subscribe() {
var _this2 = this;
if (this._entityPromise) {
return this._entityPromise;
}
this._entityPromise = this._session.datasync.openEntity(this._uri).then(function (entity) {
_this2._entity = entity;
entity.subscribe();
entity.on('updated', function (data) {
return _this2._update(data);
});
_this2._update(entity.getData());
return _this2._entity;
});
return this._entityPromise;
};
/**
* Load the attributes of this Channel and instantiate its Members and Messages.
* This or _subscribe will need to be called before any events on Channel will fire.
* This will need to be called before any events on Members or Messages will fire
* @returns {Promise}
* @private
*/
Channel.prototype._subscribeStreams = function _subscribeStreams() {
var _this3 = this;
this._subscribePromise = this._subscribePromise || this._subscribe().then(function (entity) {
var messagesUri = entity.value('/messagesUrl');
var rosterUri = entity.value('/rosterUrl');
return Promise.all([_this3._messagesEntity.subscribe(messagesUri).then(function () {
return _this3._messagesEntity.getMessages();
}), _this3._membersEntity.subscribe(rosterUri)]);
}).then(function () {
return _this3._entity;
});
return this._subscribePromise;
};
/**
* Load the Channel state.
* @returns {Promise}
* @private
*/
Channel.prototype._fetch = function _fetch() {
return this._session.datasync.openEntity(this._uri).then(function (entity) {
return entity.getData();
});
};
/**
* Stop listening for and firing events on this Channel.
* @returns {Promise}
* @private
*/
Channel.prototype._unsubscribe = function () {
var promises = [];
if (this._entityPromise) {
promises.push(this._entity.unsubscribe());
}
promises.push(this._membersEntity.unsubscribe());
promises.push(this._messagesEntity.unsubscribe());
this._entityPromise = null;
this._subscribePromise = null;
return Promise.all(promises);
};
/**
* Set channel status
* @private
*/
Channel.prototype._setStatus = function (status) {
if (this._status === status) {
return;
}
this._status = status;
if (status === 'joined') {
this._subscribeStreams();
} else if (status === 'invited') {
this._subscribe();
} else if (this._entityPromise) {
this._unsubscribe();
}
};
/**
* Updates local channel object with new values
* @private
*/
Channel.prototype._update = function (update) {
try {
if (typeof update.attributes === 'string') {
update.attributes = JSON.parse(update.attributes);
} else if (update.attributes) {
JSON.stringify(update.attributes);
}
} catch (e) {
log.warn('Retrieved malformed attributes from the server for channel: ' + this._sid);
update.attributes = {};
}
var updated = false;
for (var key in update) {
var localKey = fieldMappings[key];
if (localKey && localKey === fieldMappings.attributes) {
if (!JsonDiff.isDeepEqual(this._attributes, update.attributes)) {
this._attributes = update.attributes;
updated = true;
}
} else if (localKey && this[localKey] !== update[key]) {
this['_' + localKey] = update[key];
updated = true;
}
}
// if uniqueName is not present in the update - then we should set it to undefined on the client object
if (!update.status && !update.uniqueName) {
if (this._uniqueName) {
this._uniqueName = null;
updated = true;
}
}
if (this._dateCreated && !(this._dateCreated instanceof Date)) {
this._dateCreated = new Date(this._dateCreated);
}
if (this._dateUpdated && !(this._dateUpdated instanceof Date)) {
this._dateUpdated = new Date(this._dateUpdated);
}
if (updated) {
this.emit('updated', this);
}
};
/**
* Add a Client to the Channel by its Identity.
* @param {String} identity - Identity of the Client to add.
* @returns {Promise}
*/
Channel.prototype.add = function addByIdentity(identity) {
if (!identity || typeof identity !== 'string') {
throw new Error('Channel.add requires an identity parameter');
}
return this._membersEntity.add(identity);
};
/**
* Decline an invitation to the Channel.
* @returns {Promise}
*/
Channel.prototype.decline = function declineChannel() {
var _this4 = this;
return this._session.addCommand('declineInvitation', {
channelSid: this._sid
}).then(function () {
return _this4;
});
};
/**
* Delete the Channel.
* @returns {Promise}
*/
Channel.prototype.delete = function deleteChannel() {
var _this5 = this;
return this._session.addCommand('destroyChannel', {
channelSid: this._sid
}).then(function () {
return _this5;
});
};
/**
* Invite a user to the Channel by their Identity.
* @param {String} identity - Identity of the user to invite.
* @returns {Promise}
*/
Channel.prototype.invite = function inviteByIdentity(identity) {
if (typeof identity !== 'string' || !identity.length) {
throw new Error('Channel.invite requires an identity parameter');
}
return this._membersEntity.invite(identity);
};
/**
* Set last consumed Channel's Message index to current consumption horizon.
* @param {Number} index - Message index to set as last read.
* @returns {Promise}
*/
Channel.prototype.updateLastConsumedMessageIndex = function updateLastConsumedMessageIndex(index) {
var _this6 = this;
if (parseInt(index) !== index) {
var err = 'Channel.updateLastConsumedMessageIndex requires an integral index parameter';
throw new Error(err);
}
return this._subscribeStreams().then(function () {
return _this6._session.sendLastConsumedMessageIndexForChannel(_this6._sid, index);
}).then(function () {
return _this6;
});
};
/**
* Get the custom attributes of this channel.
* NOTE: Attributes will be empty in public channels until this is called.
* However, private channels will already have this due to back-end limitation.
* @returns {Promise}
*/
Channel.prototype.getAttributes = function getAttributes() {
var _this7 = this;
if (this._entityPromise) {
return this._subscribe().then(function () {
return _this7.attributes;
});
}
return this._fetch().then(function (data) {
_this7._update(data);
return _this7.attributes;
});
};
/**
* Get a sorted list of Messages.
* @param {Number} [count] - Amount of Messages to fetch
* @param {String} [anchor='end'] - Newest Message to fetch
* @returns {Promise>}
*/
Channel.prototype.getMessages = function getMessages(count, anchor) {
var _this8 = this;
return this._subscribeStreams().then(function () {
return _this8._messagesEntity.getMessages(count, anchor);
});
};
/**
* Get a list of all Members joined to this Channel.
* @returns {Promise>}
*/
Channel.prototype.getMembers = function getMembers() {
var _this9 = this;
return this._subscribeStreams().then(function () {
return _this9._membersEntity.getMembers();
});
};
/**
* Join the Channel.
* @returns {Promise}
*/
Channel.prototype.join = function joinChannel() {
var _this10 = this;
return this._session.addCommand('joinChannel', {
channelSid: this._sid
}).then(function () {
return _this10;
});
};
/**
* Leave the Channel.
* @returns {Promise}
*/
Channel.prototype.leave = function leaveChannel() {
var _this11 = this;
if (this._status !== Channel.status.JOINED) {
return Promise.resolve(this);
}
return this._session.addCommand('leaveChannel', {
channelSid: this._sid
}).then(function () {
return _this11;
});
};
/**
* Remove a Member from the Channel.
* @param {Member|String} member - The Member (Or identity) to remove.
* @returns {Promise}
*/
Channel.prototype.removeMember = function removeMember(member) {
if (!member || typeof member !== 'string' && !(member instanceof Member)) {
throw new Error('Channel.removeMember requires a member parameter.');
}
return this._membersEntity.remove(typeof member === 'string' ? member : member.identity);
};
/**
* Send a Message on the Channel.
* @param {String} messageBody - The message body.
* @returns {Promise} A Promise for the message ID
*/
Channel.prototype.sendMessage = function sendMessage(messageBody) {
return this._messagesEntity.send(messageBody);
};
/**
* Send a notification to the server indicating that this Client is currently typing in this Channel.
* @returns {Promise}
*/
Channel.prototype.typing = function typing() {
if (this._lastTypingUpdate > Date.now() - this._session.typingTimeout) {
return Promise.resolve();
}
this._lastTypingUpdate = Date.now();
return this._session.sendTypingIndicator(this._sid);
};
/**
* Update the Channel's attributes.
* @param {Object} attributes - The new attributes object.
* @returns {Promise} A Promise for the Channel
*/
Channel.prototype.updateAttributes = function updateAttributes(attributes) {
var _this12 = this;
if (typeof attributes === 'undefined') {
throw new Error('Attributes is a required parameter for updateAttributes');
} else if (attributes.constructor !== Object) {
throw new Error('Attributes must be a valid JSON object.');
}
return this._session.addCommand('editAttributes', {
channelSid: this._sid,
attributes: JSON.stringify(attributes)
}).then(function () {
return _this12;
});
};
/**
* Update the Channel's friendlyName.
* @param {String} name - The new Channel friendlyName.
* @returns {Promise} A Promise for the Channel
*/
Channel.prototype.updateFriendlyName = function updateFriendlyName(name) {
var _this13 = this;
if (this._friendlyName === name) {
return Promise.resolve(this);
}
return this._session.addCommand('editFriendlyName', {
channelSid: this._sid,
friendlyName: name
}).then(function () {
return _this13;
});
};
/**
* Update the Channel's unique name (tag).
* @param {String} uniqueName - The new Channel uniqueName.
* @returns {Promise} A Promise for the Channel
*/
Channel.prototype.updateUniqueName = function updateUniqueName(uniqueName) {
var _this14 = this;
if (this._uniqueName === uniqueName) {
return Promise.resolve(this);
}
return this._session.addCommand('editUniqueName', {
channelSid: this._sid,
uniqueName: uniqueName
}).then(function () {
return _this14;
});
};
/**
* Update the Channel's type (public or private). Currently not implemented.
* @param {String} type
* @private
* @returns {Promise} A Promise for the Channel
*/
Channel.prototype.updateType = function (type) {
if (type !== Channel.type.PRIVATE && type !== Channel.type.PUBLIC) {
throw new Error('Can\'t set unknown channel type ' + type);
}
if (this._type !== type) {
throw new Error('Changing of channel type isn\'t supported');
}
return Promise.resolve(this);
};
Object.freeze(Channel);
/**
* Fired when a Member has joined the Channel.
* @param {Member} member
* @event Channel#memberJoined
*/
/**
* Fired when a Member has left the Channel.
* @param {Member} member
* @event Channel#memberLeft
*/
/**
* Fired when a Member's fields has been updated.
* @param {Member} member
* @event Channel#memberUpdated
*/
/**
* Fired when a new Message has been added to the Channel on the server.
* @param {Message} message
* @event Channel#messageAdded
*/
/**
* Fired when Message is removed from Channel's message list.
* @param {Message} message
* @event Channel#messageRemoved
*/
/**
* Fired when an existing Message's fields are updated with new values.
* @param {Message} message
* @event Channel#messageUpdated
*/
/**
* Fired when a member has begun typing.
* @event Channel#typingStarted
* @type {Member}
*/
/**
* Fired when a member has stopped typing.
* @event Channel#typingEnded
* @type {Member}
*/
/**
* Fired when the Channel's fields have been updated.
* @param {Channel} channel
* @event Channel#updated
*/
module.exports = Channel;
},{"../../util/jsondiff":34,"./data/members":15,"./data/messages":16,"./member":17,"events":232,"loglevel":265,"util":261}],12:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var log = require('loglevel');
var Configuration = require('./configuration');
var Session = require('./session.js');
var Channel = require('./channel.js');
var ChannelsEntity = require('./data/channels.js');
var DataSyncClient = require('../datasync/client');
var NotificationClient = require('../notification/client');
var TwilsockClient = require('../twilsock/client');
var Transport = require('../transport');
var AccessManager = require('twilio-common').AccessManager;
var SDK_VERSION = require('../../../package.json').version;
/**
* @class
* @classdesc A Client provides an interface for the local
* User to interact with Channels. The Client constructor will
* synchronously return an instance of Client, and will hold
* any outgoing methods until it has asynchronously finished
* syncing with the server.
* @param {AccessManager|String} accessManager - The Client's AccessManager, or a Capability
* token JWT string.
* @param {Client#ClientOptions} options - Options to customize the Client
* @property {AccessManager} accessManager - The Client's AccessManager
* @property {Map} channels - A Map containing all Channels known locally on
* the Client. To ensure the Channels have loaded before getting a response, use
* {@link Client#getChannels}.
* @property {String} identity - The unique identifier for the User of this Client.
* @fires Client#channelAdded
* @fires Client#channelInvited
* @fires Client#channelJoined
* @fires Client#channelLeft
* @fires Client#channelRemoved
* @fires Client#channelUpdated
* @fires Client#tokenExpired
*/
function Client(accessManager, options) {
var _this = this;
options = options || {};
options.logLevel = options.logLevel || 'error';
log.setDefaultLevel(options.logLevel);
log.setLevel(options.logLevel);
var config = new Configuration(options);
if (typeof accessManager === 'string') {
accessManager = new AccessManager(accessManager);
}
if (!accessManager || !accessManager.token) {
throw new Error('A valid Twilio AccessManager or Capability Token must be passed to IPMessaging Client');
}
var token = accessManager.token;
var twilsock = options.twilsockClient || new TwilsockClient(token, options);
var transport = options.transportClient || new Transport(twilsock, options);
var notification = options.notificationClient || new NotificationClient('ip_messaging', token, transport, twilsock, options);
var datasync = options.dataSyncClient || new DataSyncClient(token, notification, transport, options);
var session = new Session(datasync, transport, token, config);
var sessionPromise = session.initialize();
var channels = new Map();
var channelsEntity = new ChannelsEntity(session, channels);
var channelsPromise = sessionPromise.then(function () {
channelsEntity.on('channelAdded', _this.emit.bind(_this, 'channelAdded'));
channelsEntity.on('channelRemoved', _this.emit.bind(_this, 'channelRemoved'));
channelsEntity.on('channelInvited', _this.emit.bind(_this, 'channelInvited'));
channelsEntity.on('channelJoined', _this.emit.bind(_this, 'channelJoined'));
channelsEntity.on('channelLeft', _this.emit.bind(_this, 'channelLeft'));
channelsEntity.on('channelUpdated', _this.emit.bind(_this, 'channelUpdated'));
return channelsEntity.fetchChannels(session);
});
accessManager.on('tokenExpired', function () {
return _this.emit('tokenExpired', accessManager);
});
accessManager.on('tokenUpdated', function () {
return _this._updateToken(accessManager.token);
});
Object.defineProperties(this, {
_channelsPromise: { value: channelsPromise },
_datasync: { value: datasync },
_notification: { value: notification },
_session: { value: session },
_sessionPromise: { value: sessionPromise },
_token: { value: token, writable: true },
_twilsock: { value: twilsock },
accessManager: {
enumerable: true,
value: accessManager
},
channels: {
enumerable: true,
value: channels
},
identity: {
enumerable: true,
get: function get() {
return accessManager.identity;
}
}
});
this._initialize(options.typingTimeout || 5000);
EventEmitter.call(this);
}
/**
* Current version of this IP Messaging Client.
* @name Client#version
* @type String
* @readonly
*/
Object.defineProperties(Client, {
version: {
enumerable: true,
value: SDK_VERSION
}
});
inherits(Client, EventEmitter);
/**
* @param typingTimeout
* @returns {*|Promise.|Request}
* @private
*/
Client.prototype._initialize = function _initialize(typingTimeout) {
var _this2 = this;
return this._sessionPromise.then(function () {
_this2._notification.subscribe('twilio.ipmsg.typing_indicator', 'twilsock');
_this2._notification.subscribe('twilio.channel.new_message', 'gcm');
_this2._notification.subscribe('twilio.channel.added_to_channel', 'gcm');
_this2._notification.on('message', function (type, message) {
if (type === 'twilio.ipmsg.typing_indicator') {
log.trace('Got new typing indicator push!');
log.trace(message);
_this2._channelsPromise.then(function (channels) {
return channels.channels.get(message.channel_sid);
}).then(function (channel) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = channel.members.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var member = _step.value;
if (member.identity === message.identity) {
member._startTyping(typingTimeout);
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}).catch(function (err) {
log.error('IMPSG E: ', err);
throw err;
});
}
});
});
};
/**
* Update the token used by the Client and re-register with IP Messaging services.
* @param {String} token - The JWT string of the new token.
* @private
* @returns {Promise}
*/
Client.prototype._updateToken = function _updateToken(token) {
var _this3 = this;
if (!token || token.split('.').length !== 3) {
return log.error('Received a malformed token from AccessManager. \
Token not updated in IP MessagingClient.');
}
if (token === this._token) {
return Promise.resolve(this);
}
this._token = token;
log.info('IPMSG I: authTokenUpdated');
return Promise.all([this._twilsock.setAuthToken(token), this._notification.setAuthToken(token), this._datasync.setAuthToken(token), this._sessionPromise.then(function () {
return _this3._session.updateToken(token);
})]).then(function () {
return _this3;
});
};
/**
* Get a Channel by its SID.
* @param {String} channelSid - The sid of the Channel to get.
* @returns {Promise}
*/
Client.prototype.getChannelBySid = function getChannelBySid(channelSid) {
var _this4 = this;
if (!channelSid || typeof channelSid !== 'string') {
throw new Error('Client.getChannelBySid requires a channelSid parameter');
}
return this._channelsPromise.then(function () {
return _this4.channels.get(channelSid);
});
};
/**
* Get a Channel by its unique identifier name.
* @param {String} uniqueName - The unique identifier name of the Channel to get.
* @returns {Promise}
*/
Client.prototype.getChannelByUniqueName = function getChannelByUniqueName(uniqueName) {
var _this5 = this;
if (!uniqueName || typeof uniqueName !== 'string') {
throw new Error('Client.getChannelByUniqueName requires a uniqueName parameter');
}
return this._channelsPromise.then(function () {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = _this5.channels.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var channel = _step2.value;
if (channel.uniqueName === uniqueName) {
return channel;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
});
};
/**
* Get the current list of all Channels the Client knows about.
* @returns {Promise>}
*/
Client.prototype.getChannels = function getChannels() {
var _this6 = this;
return this._channelsPromise.then(function () {
var channels = [];
_this6.channels.forEach(function (channel) {
return channels.push(channel);
});
return channels;
});
};
/**
* Create a channel on the server.
* @param {Client#CreateChannelOptions} [options] - Options for the Channel
* @returns {Promise}
*/
Client.prototype.createChannel = function createChannel(options) {
options = options || {};
var channel = new Channel(this._session, options, null);
return this._channelsPromise.then(function (channelsEntity) {
return channelsEntity.addChannel(channel);
});
};
Object.freeze(Client);
/**
* These options can be passed to Client.createChannel
* @typedef {Object} Client#CreateChannelOptions
* @property {Object} [attributes] - Any custom attributes to attach to the Channel.
* @property {Boolean} [isPrivate] - Whether or not this Channel should be visible
* to uninvited Clients.
* @property {String} [friendlyName] - The non-unique display name of the Channel.
* @property {String} [uniqueName] - The unique identity name of the Channel.
*/
/**
* These options can be passed to Client constructor
* @typedef {Object} Client#ClientOptions
* @property {String} [logLevel='error'] - The level of logging to enable. Valid options
* (from strictest to broadest): ['silent', 'error', 'warn', 'info', 'debug', 'trace']
* @property {String} [wsServer] - A custom websocket server to connect to.
*/
/**
* Fired when a Channel becomes visible to the Client.
* @param {Channel} channel
* @event Client#channelAdded
*/
/**
* Fired when the Client is invited to a Channel.
* @param {Channel} channel
* @event Client#channelInvited
*/
/**
* Fired when the Client joins a Channel.
* @param {Channel} channel
* @event Client#channelJoined
*/
/**
* Fired when the Client leaves a Channel.
* @param {Channel} channel
* @event Client#channelLeft
*/
/**
* Fired when a Channel is no longer visible to the Client.
* @param {Channel} channel
* @event Client#channelRemoved
*/
/**
* Fired when a Channel's attributes or metadata have been updated.
* @param {Channel} channel
* @event Client#channelUpdated
*/
/**
* Fired when the supplied token expires.
* @event Client#tokenExpired
*/
module.exports = Client;
},{"../../../package.json":272,"../datasync/client":2,"../notification/client":20,"../transport":24,"../twilsock/client":26,"./channel.js":11,"./configuration":13,"./data/channels.js":14,"./session.js":19,"events":232,"loglevel":265,"twilio-common":269,"util":261}],13:[function(require,module,exports){
'use strict';
var TYPING_URI = 'https://aim.twilio.com';
var TYPING_PATH = '/v1/typing';
var TYPING_TIMEOUT = 5;
var CONSUMPTION_HORIZON_SENDING_INTERVAL = 'PT5S';
function IPMessagingConfig(options) {
options = options || {};
var _options = options.IPMessaging || {};
var baseUri = _options.typingUri || TYPING_URI;
Object.defineProperties(this, {
typingIndicatorUri: { enumerable: true,
value: baseUri + TYPING_PATH },
typingIndicatorTimeout: { enumerable: true,
value: TYPING_TIMEOUT * 1000 },
consumptionReportInterval: { enumerable: true,
value: CONSUMPTION_HORIZON_SENDING_INTERVAL }
});
}
module.exports = IPMessagingConfig;
},{}],14:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var Channel = require('../channel');
/**
* Creates an instance of channels collection {@see Channel}
*
* @class ChannelsEntity
* @classdesc Provides an access to the channels collection
*/
function ChannelsEntity(session, channels) {
Object.defineProperties(this, {
_session: { value: session },
channels: {
enumerable: true,
value: channels
}
});
EventEmitter.call(this);
}
inherits(ChannelsEntity, EventEmitter);
/**
* Add channel to server
* @private
* @returns {Promise} Channel
*/
ChannelsEntity.prototype.addChannel = function addChannel(channel) {
var _this = this;
return this._session.addCommand('createChannel', {
friendlyName: channel.friendlyName,
uniqueName: channel.uniqueName,
type: channel.isPrivate ? 'private' : 'public',
attributes: JSON.stringify(channel.attributes)
}).then(function (response) {
var existingChannel = _this.channels.get(channel.sid);
if (existingChannel) {
existingChannel._update(channel);
return existingChannel;
}
channel._sid = response.channelSid;
channel._uri = response.channelUrl;
_this.channels.set(channel.sid, channel);
channel.on('updated', function () {
return _this.emit('channelUpdated', channel);
});
return channel._subscribe().then(function () {
_this.emit('channelAdded', channel);
return channel;
});
});
};
ChannelsEntity.prototype.fetchChannels = function fetchChannels(session) {
var self = this;
return new Promise(function (resolve, reject) {
var myUrl = session.getMyChannelsUrl();
var publicUrl = session.getChannelsUrl();
var called = false;
function setChannels() {
called = true;
self._fetchPublicChannels(publicUrl).then(function () {
return self._fetchMyChannels(myUrl);
}).then(function () {
resolve(self);
}, function (reason) {
reject(reason);
});
}
session.onKeyUpdated('/channelsUrl', function (url) {
publicUrl = url;
if (myUrl && !called) {
setChannels();
}
});
session.onKeyUpdated('/myChannelsUrl', function (url) {
myUrl = url;
if (publicUrl && !called) {
setChannels();
}
});
});
};
/**
* Fetch private channel list from service and create all needed objects
* @private
*/
ChannelsEntity.prototype._fetchMyChannels = function (url) {
var _this2 = this;
return this._session.datasync.openMap(url).then(function (map) {
map.subscribe();
map.on('entityAdded', function (entity) {
var sid = entity.id;
_this2._upsertChannel(sid, entity.value);
});
map.on('entityRemoved', function (sid) {
var channel = _this2.channels.get(sid);
if (channel) {
if (channel.status === 'joined' || channel.status === 'invited') {
channel._setStatus('known');
_this2.emit('channelLeft', channel);
}
if (channel.isPrivate) {
_this2.channels.delete(sid);
_this2.emit('channelRemoved', channel);
}
}
});
map.on('entityUpdated', function (entity) {
var sid = entity.id;
_this2._upsertChannel(sid, entity.value);
});
var upserts = [];
return map.forEach(function (entity) {
var channelData = entity.value;
var sid = entity.id;
upserts.push(_this2._upsertChannel(sid, channelData));
}).then(function () {
return Promise.all(upserts);
}).then(function () {
return _this2;
});
});
};
/**
* Fetch public channel list from service and create all needed objects
* @private
*/
ChannelsEntity.prototype._fetchPublicChannels = function (url) {
var _this3 = this;
return this._session.datasync.openMap(url).then(function (map) {
map.subscribe();
map.on('entityAdded', function (entity) {
var sid = entity.id;
var channel = _this3.channels.get(sid);
if (!channel) {
channel = new Channel(_this3._session, entity.value, sid);
channel.on('updated', function () {
return _this3.emit('channelUpdated', channel);
});
_this3.channels.set(sid, channel);
_this3.emit('channelAdded', channel);
}
});
map.on('entityRemoved', function (sid) {
var channel = _this3.channels.get(sid);
if (channel) {
if (channel.status === 'joined' || channel.status === 'invited') {
channel._unsubscribe();
_this3.emit('channelLeft', channel);
}
_this3.channels.delete(sid);
_this3.emit('channelRemoved', channel);
}
});
map.on('entityUpdated', function (entity) {
var sid = entity.id;
_this3._upsertChannel(sid, entity.value);
});
return map.forEach(function (entity) {
var channelData = entity.value;
var sid = entity.id;
var channel = new Channel(_this3._session, channelData, sid);
channel.on('updated', function () {
return _this3.emit('channelUpdated', channel);
});
_this3.channels.set(sid, channel);
}).then(function () {
return _this3;
});
});
};
ChannelsEntity.prototype._upsertChannel = function (sid, data) {
var _this4 = this;
var channel = this.channels.get(sid);
// Update the Channel's status if we know about it
if (channel) {
if (data.status === 'joined' && channel.status !== 'joined') {
channel._setStatus('joined');
// TODO: Do this better.
if (data.lastConsumedMessageIndex) {
channel._lastConsumedMessageIndex = data.lastConsumedMessageIndex;
}
this.emit('channelJoined', channel);
} else if (data.status === 'invited' && channel.status !== 'invited') {
channel._setStatus('invited');
this.emit('channelInvited', channel);
} else if (data.status === 'known' && (channel.status === 'invited' || channel.status === 'joined')) {
channel._setStatus('known');
channel._update(data);
this.emit('channelLeft', channel);
} else if (data.status === 'notParticipating' && data.type === 'private') {
channel._subscribe();
} else {
channel._update(data);
}
return Promise.resolve(channel);
}
// Fetch the Channel if we don't know about it
channel = new Channel(this._session, data, sid);
channel.on('updated', function () {
return _this4.emit('channelUpdated', channel);
});
this.channels.set(sid, channel);
return channel._subscribe().then(function () {
if (data.status === 'joined') {
channel._setStatus('joined');
_this4.emit('channelJoined', channel);
} else if (data.status === 'invited') {
channel._setStatus('invited');
_this4.emit('channelInvited', channel);
}
_this4.emit('channelAdded', channel);
return channel;
});
};
module.exports = ChannelsEntity;
},{"../channel":11,"events":232,"util":261}],15:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var Member = require('../member');
/**
* Creates members collection
*
* @class Members
* @classdesc Represents the collection of members for the channel
*/
function Members(channel, session, members) {
Object.defineProperties(this, {
_datasync: { value: session.datasync },
_session: { value: session },
_rosterStreamPromise: {
writable: true,
value: null
},
channel: {
enumerable: true,
value: channel
},
members: {
enumerable: true,
value: members
}
});
EventEmitter.call(this);
}
inherits(Members, EventEmitter);
Members.prototype.unsubscribe = function unsubscribe() {
return this._rosterStreamPromise ? this._rosterStreamPromise.then(function (entity) {
return entity.unsubscribe();
}) : Promise.resolve();
};
Members.prototype.subscribe = function (rosterUri) {
var _this = this;
this._rosterStreamPromise = this._datasync.openMap(rosterUri).then(function (rosterMap) {
rosterMap.subscribe();
rosterMap.on('entityAdded', function (entity) {
var memberSid = entity.id;
if (_this.members.has(memberSid)) {
return;
}
var member = _this.upsertMember(memberSid, entity.value);
_this.emit('memberJoined', member);
});
rosterMap.on('entityRemoved', function (memberSid) {
if (!_this.members.has(memberSid)) {
return;
}
var leftMember = _this.members.get(memberSid);
_this.members.delete(memberSid);
_this.emit('memberLeft', leftMember);
});
rosterMap.on('entityUpdated', function (entity) {
var memberSid = entity.id;
if (!_this.members.has(memberSid)) {
return;
}
_this.upsertMember(memberSid, entity.value);
});
return rosterMap.forEach(function (entity) {
var memberSid = entity.id;
if (!_this.members.has(memberSid)) {
_this.upsertMember(memberSid, entity.value);
}
}).then(function () {
return rosterMap;
});
});
return this._rosterStreamPromise;
};
Members.prototype.upsertMember = function upsertMember(memberSid, data) {
var _this2 = this;
var member = this.members.get(memberSid);
if (!member) {
member = new Member(this.channel, data, memberSid);
this.members.set(memberSid, member);
member.on('updated', function () {
return _this2.emit('memberUpdated', member);
});
} else {
member._update(data);
}
return member;
};
/**
* @returns Synchronously returns the list of members {@see Member}
*/
Members.prototype.getMembersList = function () {
var members = [];
this.members.forEach(function (member) {
return members.push(member);
});
return members;
};
/**
* @returns {Promise>} returns list of members {@see Member}
*/
Members.prototype.getMembers = function () {
var _this3 = this;
return this._rosterStreamPromise.then(function () {
var members = [];
_this3.members.forEach(function (member) {
return members.push(member);
});
return members;
});
};
/**
* Add user to the channel
*/
Members.prototype.add = function (username) {
return this._session.addCommand('addMember', {
channelSid: this.channel.sid,
username: username
});
};
/**
* Invites user to the channel
* User can choose either to join or not
*/
Members.prototype.invite = function (username) {
return this._session.addCommand('inviteMember', {
channelSid: this.channel.sid,
username: username
});
};
/**
* Remove user from channel
*/
Members.prototype.remove = function (username) {
return this._session.addCommand('removeMember', {
channelSid: this.channel.sid,
username: username
});
};
module.exports = Members;
/**
* Fired when member joined channel
* @event Members#memberJoined
* @type {Member}
*/
/**
* Fired when member left channel
* @event Members#memberLeft
* @type {string}
*/
/**
* Fired when member info updated
* Note that event won't be fired if user haven't requested any member data
*
* @event Members#memberUpdated
* @type {Member}
*/
},{"../member":17,"events":232,"util":261}],16:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var Message = require('../message');
var Q = require('q');
/*
* Creates an instance of messages collection
*
* @class Messages
* @classdesc Represents the collection of messages in a channel
*/
function Messages(channel, session, messages) {
var deferred = Q.defer();
Object.defineProperties(this, {
_datasync: { value: session.datasync },
_deferred: { value: deferred },
_eventStreamPromise: { value: null, writable: true },
_sortedMessages: { value: messages },
_messagesByIndex: { value: new Map() },
_session: { value: session },
_waitForURI: { value: deferred.promise },
channel: {
enumerable: true,
value: channel
}
});
EventEmitter.call(this);
}
inherits(Messages, EventEmitter);
/**
* Subscribe to the Messages Event Stream
* @param {String} uri - The URI of the Messages resource.
* @returns {Promise}
*/
Messages.prototype.subscribe = function subscribe(uri) {
var _this = this;
this._eventStreamPromise = this._eventStreamPromise || this._datasync.openStream(uri).then(function (eventStream) {
eventStream.on('entityAdded', function (entity) {
var message = new Message(_this.channel, entity.id, entity.value);
_this._sortedMessages.push(message);
_this._messagesByIndex.set(message.index, message);
message.on('updated', function () {
return _this.emit('messageUpdated', message);
});
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _this.channel.members.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var member = _step.value;
if (member.identity === message.author) {
member._endTyping();
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
_this.emit('messageAdded', message);
});
eventStream.on('entityRemoved', function (index) {
var message = _this._removeMessageById(index);
if (message) {
_this._messagesByIndex.delete(message.index);
message.removeAllListeners('updated');
_this.emit('messageRemoved', message);
}
});
eventStream.on('entityUpdated', function (entity) {
var message = _this._messagesByIndex.get(entity.id);
if (message) {
message._update(entity.value);
}
});
_this._deferred.resolve(eventStream);
return eventStream;
});
return this._eventStreamPromise.then(function (eventStream) {
eventStream.subscribe();
return eventStream;
});
};
Messages.prototype.unsubscribe = function unsubscribe() {
return this._eventStreamPromise ? this._eventStreamPromise.then(function (entity) {
return entity.unsubscribe();
}) : Promise.resolve();
};
/**
* @param {Number} entityId Entity ID of Message to remove.
* @returns {Message} removedMessage The message that was removed (or undefined).
* @private
*/
Messages.prototype._removeMessageById = function (entityId) {
var removedMessage = undefined;
for (var i = 0; i < this._sortedMessages.length; i++) {
var message = this._sortedMessages[i];
if (message.index === entityId) {
removedMessage = this._sortedMessages.splice(i, 1)[0];
break;
}
}
return removedMessage;
};
/**
* Send Message to the channel
* @param {String} message - Message to post
* @returns Returns promise which can fail
*/
Messages.prototype.send = function (message) {
return this._session.addCommand('sendMessage', {
channelSid: this.channel.sid,
text: message
});
};
/**
* Returns last messages from channel
*
* @returns last page of messages by default
*
* @param {Number} messagesCount number of messages to return
* @param {String} anchor Most early message id which is already known, or 'end'
*/
Messages.prototype.getMessages = function getMessages(count, anchor) {
var _this2 = this;
count = count || 100;
if (typeof anchor !== 'undefined') {
count++;
var isKnown = this._sortedMessages.some(function (message) {
if (message.sid !== anchor) {
return false;
}
anchor = message.index;
return true;
});
if (!isKnown) {
return Promise.reject(new Error('Unknown anchor'));
}
}
return this._waitForURI.then(function (messagesStream) {
return messagesStream.queryEntitiesBefore(anchor, count);
}).then(function (messageEntities) {
var messages = [];
messageEntities.forEach(function (messageEntity) {
var messageData = messageEntity.value;
var message = new Message(_this2.channel, messageEntity.id, messageData);
messages.push(message);
_this2._messagesByIndex.set(message.index, message);
message.on('updated', function () {
return _this2.emit('messageUpdated', message);
});
});
// Remove the matched anchor
if (typeof anchor !== 'undefined' && anchor !== 'end') {
var removedMessage = messages.pop();
if (removedMessage) {
_this2._messagesByIndex.delete(removedMessage.index);
removedMessage.removeAllListeners('messageUpdated');
}
}
_this2._updateSortedMessages();
return messages;
});
};
Messages.prototype._updateSortedMessages = function _updateSortedMessages() {
var uniqueValues = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this._messagesByIndex.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var message = _step2.value;
uniqueValues.push(message);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
uniqueValues.sort(function (message1, message2) {
return message1.index - message2.index;
});
Array.prototype.splice.apply(this._sortedMessages, [0, this._sortedMessages.length].concat(uniqueValues));
};
module.exports = Messages;
},{"../message":18,"events":232,"q":267,"util":261}],17:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
/**
* @class
* @classdesc A Member represents a remote Client in a Channel.
* @property {Channel} channel - The Channel the remote Client is a Member of.
* @property {String} identity - The identity of the remote Client.
* @property {Boolean} isTyping - Whether or not this Member is currently typing.
* @property {Number} lastConsumedMessageIndex - Latest consumed Message index by this Member.
* @property {Date} lastConsumptionTimestamp - Date when Member has updated his consumption horizon.
* @property {String} sid - The server-assigned unique identifier for the Member.
* @fires Member#typingEnded
* @fires Member#typingStarted
* @fires Member#updated
*/
function Member(channel, data, sid) {
if (!(this instanceof Member)) {
return new Member(channel, data, sid);
}
var isTyping = false;
var typingTimeout = null;
var identity = data.identity;
var roleSid = data.roleSid || null;
var lastConsumedMessageIndex = data.lastConsumedMessageIndex || null;
var lastConsumptionTimestamp = data.lastConsumptionTimestamp ? new Date(data.lastConsumptionTimestamp) : null;
if (!data.identity) {
throw new Error('Received invalid Member object from server: Missing identity.');
}
Object.defineProperties(this, {
_identity: {
get: function get() {
return identity;
},
set: function set(_identity) {
return identity = _identity;
}
},
_isTyping: {
get: function get() {
return isTyping;
},
set: function set(_isTyping) {
return isTyping = _isTyping;
}
},
_lastConsumedMessageIndex: {
get: function get() {
return lastConsumedMessageIndex;
},
set: function set(_lastConsumedMessageIndex) {
return lastConsumedMessageIndex = _lastConsumedMessageIndex;
}
},
_lastConsumptionTimestamp: {
get: function get() {
return lastConsumptionTimestamp;
},
set: function set(_lastConsumptionTimestamp) {
return lastConsumptionTimestamp = _lastConsumptionTimestamp;
}
},
_roleSid: {
get: function get() {
return roleSid;
},
set: function set(_roleSid) {
return roleSid = _roleSid;
}
},
_typingTimeout: {
writable: true,
value: typingTimeout
},
channel: {
enumerable: true,
value: channel
},
identity: {
enumerable: true,
get: function get() {
return identity;
}
},
isTyping: {
enumerable: true,
get: function get() {
return isTyping;
}
},
lastConsumedMessageIndex: {
enumerable: true,
get: function get() {
return lastConsumedMessageIndex;
}
},
lastConsumptionTimestamp: {
enumerable: true,
get: function get() {
return lastConsumptionTimestamp;
}
},
roleSid: {
enumerable: true,
get: function get() {
return roleSid;
}
},
sid: {
enumerable: true,
value: sid
}
});
EventEmitter.call(this);
}
inherits(Member, EventEmitter);
Object.freeze(Member);
/**
* Private method used to start or reset the typing indicator timeout (with event emitting)
* @private
*/
Member.prototype._startTyping = function (timeout) {
var _this = this;
if (this._typingTimeout) {
clearTimeout(this._typingTimeout);
}
this.emit('typingStarted', this);
this.channel.emit('typingStarted', this);
this._typingTimeout = setTimeout(function () {
return _this._endTyping();
}, timeout);
return this;
};
/**
* Private method function used to stop typing indicator (with event emitting)
* @private
*/
Member.prototype._endTyping = function () {
if (!this._typingTimeout) {
return;
}
this.emit('typingEnded', this);
this.channel.emit('typingEnded', this);
clearInterval(this._typingTimeout);
this._typingTimeout = null;
};
/**
* Remove this Member from the Channel.
* @returns Promise
*/
Member.prototype.remove = function removeMember() {
return this.channel.removeMember(this);
};
/**
* Private method function used update local object's property roleSid with new value
* @private
*/
Member.prototype._update = function (data) {
var updated = false;
if (data.roleSid && this._roleSid !== data.roleSid) {
this._roleSid = data.roleSid;
updated = true;
}
if (data.lastConsumedMessageIndex && this._lastConsumedMessageIndex !== data.lastConsumedMessageIndex) {
this._lastConsumedMessageIndex = data.lastConsumedMessageIndex;
updated = true;
}
if (data.lastConsumptionTimestamp) {
var lastConsumptionTimestamp = new Date(data.lastConsumptionTimestamp);
if (!this._lastConsumptionTimestamp || this._lastConsumptionTimestamp.getTime() !== lastConsumptionTimestamp.getTime()) {
this._lastConsumptionTimestamp = lastConsumptionTimestamp;
updated = true;
}
}
if (updated) {
this.emit('updated', this);
}
};
module.exports = Member;
/**
* Fired when member started to type
* @event Member#typingStarted
* @type {Member}
*/
/**
* Fired when member ended to type
* @event Member#typingEnded
* @type {Member}
*/
/**
* Fired when member is updated
* @event Member#updated
* @type {Member}
*/
},{"events":232,"util":261}],18:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
/**
* @class
* @classdesc A Message represents a Message in a Channel.
* @property {String} author - The name of the user that authored this Message.
* @property {String} body - The body of the Message.
* @property {Channel} channel - The Channel the Message belongs to.
* @property {Date} dateUpdated - When the Message was updated.
* @property {Number} index - Index of Message in the Channel's messages stream.
* @property {String} lastUpdatedBy - The name of the last user updated this Message.
* @property {String} sid - The server-assigned unique identifier for
* the Message.
* @property {Date} timestamp - When the Message was sent.
* @fires Message#updated
*/
function Message(channel, entityId, data) {
if (!(this instanceof Message)) {
return new Message(channel, entityId, data);
}
var body = data.text;
var dateUpdated = data.dateUpdated ? new Date(data.dateUpdated) : null;
var lastUpdatedBy = data.lastUpdatedBy ? data.lastUpdatedBy : null;
Object.defineProperties(this, {
_body: {
get: function get() {
return body;
},
set: function set(_body) {
return body = _body;
}
},
_dateUpdated: {
get: function get() {
return dateUpdated;
},
set: function set(_dateUpdated) {
return dateUpdated = _dateUpdated;
}
},
_lastUpdatedBy: {
get: function get() {
return lastUpdatedBy;
},
set: function set(_lastUpdatedBy) {
return lastUpdatedBy = _lastUpdatedBy;
}
},
author: {
enumerable: true,
value: data.author
},
body: {
enumerable: true,
get: function get() {
return body;
}
},
channel: {
enumerable: true,
value: channel
},
dateUpdated: {
enumerable: true,
get: function get() {
return dateUpdated;
}
},
index: {
enumerable: true,
value: parseInt(entityId)
},
lastUpdatedBy: {
enumerable: true,
get: function get() {
return lastUpdatedBy;
}
},
sid: {
enumerable: true,
value: data.sid
},
timestamp: {
enumerable: true,
value: new Date(data.timestamp)
}
});
EventEmitter.call(this);
}
inherits(Message, EventEmitter);
Message.prototype._update = function (data) {
var updated = false;
if ((data.text || typeof data.text === 'string') && data.text !== this._body) {
this._body = data.text;
updated = true;
}
if (data.lastUpdatedBy && data.lastUpdatedBy !== this._lastUpdatedBy) {
this._lastUpdatedBy = data.lastUpdatedBy;
updated = true;
}
if (data.dateUpdated && new Date(data.dateUpdated).getTime() !== this._dateUpdated.getTime()) {
this._dateUpdated = new Date(data.dateUpdated);
updated = true;
}
if (updated) {
this.emit('updated', this);
}
};
/**
* Remove the Message.
* @returns {Promise}
*/
Message.prototype.remove = function removeMessage() {
var _this = this;
return this.channel._session.addCommand('deleteMessage', {
channelSid: this.channel.sid,
messageIdx: this.index.toString()
}).then(function () {
return _this;
});
};
/**
* Edit message body.
* @param {String} body - new body of Message.
* @returns {Promise}
*/
Message.prototype.updateBody = function updateMessageBody(body) {
var _this2 = this;
if (typeof body !== 'string') {
throw new Error('Body is a required parameter for updateBody');
}
return this.channel._session.addCommand('editMessage', {
channelSid: this.channel.sid,
messageIdx: this.index.toString(),
text: body
}).then(function () {
return _this2;
});
};
/**
* Fired when the Message's fields have been updated.
* @param {Message} message
* @event Message#updated
*/
module.exports = Message;
},{"events":232,"util":261}],19:[function(require,module,exports){
'use strict';
var guid = require('../../util/guid');
var platform = require('platform');
var log = require('loglevel');
var ChangeTracker = require('../../util/changetracker');
var Durational = require('durational');
var SDK_VERSION = require('../../../package.json').version;
/**
* Constructs the instance of Session
*
* @class Session
*
* @classdesc Provides the interface to send the command to the server
* It is reliable, which means that it tracks the command object state
* and waits the answer from the server.
*/
function Session(datasync, transport, token, config) {
var platformInfo = typeof navigator !== 'undefined' ? platform.parse(navigator.userAgent) : platform;
Object.defineProperties(this, {
_commandQueue: { value: [] },
_lastConsumptionHorizonUpdate: { value: 0, writable: true },
_consumptionHorizonReports: { value: new Map() },
_purpose: { value: 'com.twilio.rtd.ipmsg' },
_endpointPlatform: {
value: ['js', SDK_VERSION, platformInfo.os, platformInfo.name, platformInfo.version].join('|')
},
_pendingCommands: { value: new Map() },
_sessionContextChangeTracker: { value: new ChangeTracker() },
_sessionStreamPromise: { value: null, writable: true },
_config: { value: config },
datasync: { enumerable: true, value: datasync },
transport: { value: transport },
token: { enumerable: true, value: token, writable: true },
typingTimeout: { value: config.typingIndicatorTimeout, writable: true }
});
}
Session.prototype.initialize = function () {
var _this = this;
var context = {
type: 'IpMsgSession',
version: 'v2',
endpointPlatform: this._endpointPlatform,
token: this.token
};
this._sessionStreamPromise = this.datasync.createStream(this._purpose, context).then(function (stream) {
log.trace('IPMSG: session created');
stream.on('entityAdded', function (entity) {
return _this._processCommandResponse(entity);
});
stream.on('entityUpdated', function (entity) {
return _this._processCommandResponse(entity);
});
stream.on('contextUpdated', function (updatedContext) {
return _this._sessionContextChangeTracker.update(updatedContext);
});
stream.subscribe();
return stream;
}).catch(function (err) {
log.error('IPMSG: failed to create session', err);
throw err;
});
return this._sessionStreamPromise;
};
/**
* Sends the command to the server
* @returns Promise the promise, which is being fulfilled only when service will reply
*/
Session.prototype.addCommand = function (action, params) {
var _this2 = this;
return new Promise(function (resolve, reject) {
_this2._commandQueue.push({ action: action,
params: params,
resolve: resolve,
reject: reject
});
_this2._wakeupQueue();
});
};
/**
* @private
*/
Session.prototype._wakeupQueue = function () {
if (!this._commandQueueIsActive && this._commandQueue.length > 0) {
this._commandQueueIsActive = true;
this._executeQueue();
}
};
/**
* @private
*/
Session.prototype._executeQueue = function () {
var _this3 = this;
if (this._commandQueue.length === 0) {
this._commandQueueIsActive = false;
return;
}
setTimeout(function () {
var command = _this3._commandQueue.shift();
_this3._processCommand(command).then(function (value) {
command.resolve(value);
_this3._executeQueue();
}).catch(function (err) {
command.reject(err);
_this3._executeQueue();
});
}, 0);
};
/**
* @private
*/
Session.prototype._processCommand = function (args) {
var _this4 = this;
var command = { request: args.params };
command.request.action = args.action;
command.commandId = guid();
return new Promise(function (resolve, reject) {
_this4._sessionStreamPromise.then(function (stream) {
_this4._pendingCommands.set(command.commandId, {
resolve: resolve,
reject: reject
});
stream.add(command);
}).catch(function (err) {
reject(new Error('Can\'t add command: ' + err.message));
});
});
};
/**
* @private
*/
Session.prototype._processCommandResponse = function (entity) {
if (entity.value.hasOwnProperty('response') && entity.value.hasOwnProperty('commandId') && this._pendingCommands.has(entity.value.commandId)) {
var value = entity.value;
var commandId = entity.value.commandId;
if (value.response.status === 200) {
log.trace('Command succeeded: ', value);
var resolve = this._pendingCommands.get(commandId).resolve;
this._pendingCommands.delete(commandId);
resolve(value.response);
} else {
log.trace('Command failed: ', value);
var reject = this._pendingCommands.get(commandId).reject;
this._pendingCommands.delete(commandId);
reject(new Error(JSON.stringify(value)));
}
}
};
Session.prototype.updateToken = function (token) {
return this._sessionStreamPromise.then(function (stream) {
return stream.getContext().then(function (context) {
context.token = token;
return stream.updateContext(context);
});
}).catch(function (err) {
log.error('Couldn\'t update the token in session context', err);
throw new Error(err);
});
};
Session.prototype.onKeyUpdated = function (path, handler) {
this._sessionContextChangeTracker.addEventHandler('keyAdded', path, handler);
this._sessionContextChangeTracker.addEventHandler('keyUpdated', path, handler);
};
Session.prototype.getChannelsUrl = function () {
var _this5 = this;
return new Promise(function (resolve) {
_this5._sessionStreamPromise.then(function (stream) {
return stream.getContext();
}).then(function (context) {
if (context.hasOwnProperty('channelsUrl')) {
resolve(context.channelsUrl);
} else {
_this5.onKeyUpdated('/channelsUrl', resolve);
}
});
});
};
Session.prototype.getMyChannelsUrl = function () {
var _this6 = this;
return new Promise(function (resolve) {
_this6._sessionStreamPromise.then(function (stream) {
return stream.getContext();
}).then(function (context) {
if (context.hasOwnProperty('myChannelsUrl')) {
resolve(context.myChannelsUrl);
} else {
_this6.onKeyUpdated('/myChannelsUrl', resolve);
}
});
});
};
Session.prototype._getConsumptionReportInterval = function () {
var _this7 = this;
return this._sessionStreamPromise.then(function (stream) {
return stream.getContext();
}).then(function (context) {
return Durational.fromString(context.consumptionReportInterval || _this7._config.consumptionReportInterval);
});
};
Session.prototype._upsertLastConsumedMessageIndexForChannel = function (channelSid, index) {
var currentHorizon = this._consumptionHorizonReports.get(channelSid);
if (!currentHorizon || currentHorizon.messageIdx < index) {
this._consumptionHorizonReports.set(channelSid, {
channelSid: channelSid,
messageIdx: index
});
}
};
Session.prototype.sendLastConsumedMessageIndexForChannel = function (channelSid, index) {
var _this8 = this;
return this._getConsumptionReportInterval().then(function (duration) {
_this8._upsertLastConsumedMessageIndexForChannel(channelSid, index);
if (_this8._lastConsumptionHorizonUpdate > Date.now() - duration.seconds * 1000) {
return Promise.resolve();
}
_this8._lastConsumptionHorizonUpdate = Date.now();
var reports = [];
_this8._consumptionHorizonReports.forEach(function (entry) {
return reports.push(entry);
});
_this8._consumptionHorizonReports.clear();
return reports.length ? _this8.addCommand('consumptionReport', { report: reports }) : Promise.resolve();
});
};
Session.prototype.sendTypingIndicator = function (channelSid) {
var _this9 = this;
log.trace('IPMSG I: sending typing indicator');
var url = this._config.typingIndicatorUri;
var headers = {
'X-Twilio-Token': this.token,
'Content-Type': 'application/x-www-form-urlencoded'
};
var body = 'ChannelSid=' + channelSid;
return this.transport.post(url, headers, body).then(function (res) {
if (body.hasOwnProperty('typing_timeout')) {
_this9.typingTimeout = body.typing_timeout * 1000;
}
return res;
}).then(null, function (reason) {
log.error('IPMSG E: failed to send typing indicator: ', reason);
throw reason;
});
};
module.exports = Session;
},{"../../../package.json":272,"../../util/changetracker":31,"../../util/guid":32,"durational":262,"loglevel":265,"platform":266}],20:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var log = require('loglevel');
var NotificationConfig = require('./configuration');
var Registrar = require('./registrar');
/**
* Creates the instance of Notification helper library
* @param {string} productId id of a product, which uses notification library
* @param {string} token - Twilio token
* @param {config} options Object with config values to override defaults
*
* @class NotificationClient
* @classdesc The helper library for the notification service.
* Provides high level api for creating and managing notification subscriptions and receiving messages
*/
function NotificationClient(productId, token, transport, twilsock, options) {
var _this = this;
if (!token) {
throw new Error('Token is required for Notification client');
}
var reliableTransportState = {
overall: false,
transport: false,
registration: false
};
var config = new NotificationConfig(token, options);
Object.defineProperties(this, {
_config: { value: config },
_registrar: { value: new Registrar(productId, transport, config) },
_twilsock: { value: twilsock },
_reliableTransportState: { value: reliableTransportState }
});
EventEmitter.call(this);
this._registrar.on('stateChanged', function (state) {
_this._onRegistrationStateChange(state);
});
this._registrar.on('needReliableTransport', this._onNeedReliableTransport.bind(this));
this._twilsock.on('message', function (type, message) {
return _this._routeMessage(type, message);
});
this._twilsock.on('connected', function (notificationId) {
_this._onTransportStateChange(true);
_this._registrar.setNotificationId('twilsock', notificationId);
});
this._twilsock.on('disconnected', function () {
_this._onTransportStateChange(false);
});
}
inherits(NotificationClient, EventEmitter);
/**
* Routes messages to the external subscribers
*/
NotificationClient.prototype._routeMessage = function (type, message) {
log.trace('Message arrived: ', type, message);
this.emit('message', type, message);
};
NotificationClient.prototype._onNeedReliableTransport = function (isNeeded) {
if (isNeeded) {
this._twilsock.connect();
} else {
this._twilsock.disconnect();
}
};
NotificationClient.prototype._onRegistrationStateChange = function (state) {
this._reliableTransportState.registration = state === 'registered';
this._updateTransportState();
};
NotificationClient.prototype._onTransportStateChange = function (connected) {
this._reliableTransportState.transport = connected;
this._updateTransportState();
};
NotificationClient.prototype._updateTransportState = function () {
var overallState = this._reliableTransportState.transport && this._reliableTransportState.registration;
if (this._reliableTransportState.overall !== overallState) {
this._reliableTransportState.overall = overallState;
log.info('NTFCN I: Transport ready ' + overallState);
this.emit('transportReady', overallState);
}
};
/**
* Adds the subscription for the given message type
* @param {string} messageType The type of message that you want to receive
* @param {string} channelType. Supported are 'twilsock' and 'gcm'
*/
NotificationClient.prototype.subscribe = function (messageType, channelType) {
log.trace('Add subscriptions for event type: ', messageType);
channelType = channelType || 'twilsock';
return this._registrar.subscribe(messageType, channelType);
};
/**
* Remove the subscription for the particular message type
* @param {string} messageType The type of message that you don't want to receive anymore
* @param {string} Channel type. Supported are 'twilsock' and 'gcm'
*/
NotificationClient.prototype.unsubscribe = function (messageType, channelType) {
return this._registrar.unsubscribe(messageType, channelType);
};
/**
* Handle incoming push notification.
* Client application should call this method when it receives push notifications and pass the received data
*/
NotificationClient.prototype.handlePushNotification = function (msg) {
log.warn('Push message passed, but no functionality implemented yet: ' + msg);
};
/**
* Set GCM token to enable application register for a push messages
* @param {string} gcmToken Token received from GCM system
*/
NotificationClient.prototype.setGCMToken = function (gcmToken) {
this._registrar.setNotificationId('gcm', gcmToken);
};
/**
* Set authentication token
* If token is already set, it will be replaced with the new one
*
* @param {String} Authentication token
*/
NotificationClient.prototype.setAuthToken = function (authToken) {
log.info('NTFCN I: authTokenUpdated');
this._config.updateToken(authToken);
this._registrar._updateGcmRegistration();
this._twilsock.disconnect().then(this._twilsock.connect.bind(this._twilsock));
// Reconnection of twilsock automatically triggers re-registration
};
Object.freeze(NotificationClient);
/**
* Fired when new message arrived.
* @param {Object} message`
* @event NotificationClient#message
*/
/**
* Fired when a Channel's attributes or metadata have been updated.
* @param {boolean} transport state
* @event NotificationClient#transportReady
*/
module.exports = NotificationClient;
},{"./configuration":21,"./registrar":23,"events":232,"loglevel":265,"util":261}],21:[function(require,module,exports){
'use strict';
var ERS_URI = 'https://ers.twilio.com';
var ERS_PATH = '/v1/registrations';
/**
* Notification library configuration provider
*/
function NotificationConfig(token, options) {
var _this = this;
options = (options || {}).Notification || {};
var uri = options.ersUri || ERS_URI;
Object.defineProperties(this, {
_registrarUri: { value: uri + ERS_PATH },
_token: { value: token, writable: true },
registrarUri: { get: function get() {
return _this._registrarUri;
} },
token: { get: function get() {
return _this._token;
} }
});
}
NotificationConfig.prototype.updateToken = function (token) {
this._token = token;
};
module.exports = NotificationConfig;
},{}],22:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var StateMachine = require('javascript-state-machine');
var log = require('loglevel');
/**
* Creates new instance of the ERS registrar
*
* @class RegistrarClient
* @classdesc Manages the registrations on ERS service.
* It deduplicates registrations and manages them automatically
*
* @param Object configuration
* @param string notificationId
* @param string channelType
* @param Array messageTypes
*/
function RegistrarClient(productId, transport, config, channelType) {
var _this = this;
var fsm = StateMachine.create({
initial: 'unregistered',
events: [{ name: 'userUpdate', from: ['unregistered'], to: 'registering' }, { name: 'userUpdate', from: ['registered'], to: 'unregistering' }, { name: 'registered', from: ['registering', 'retry'], to: 'registered' }, { name: 'unregistered', from: ['unregistering'], to: 'unregistered' }, { name: 'failure', from: ['registering', 'retry'], to: 'retry' }, { name: 'failure', from: ['unregistering'], to: 'unregistered' }],
callbacks: {
onregistering: function onregistering(event, from, to, arg) {
return _this._register(arg);
},
onunregistering: function onunregistering() {
return _this._unregister();
},
onregistered: function onregistered() {
_this.emit('stateChanged', 'registered');
_this._checkPendingUpdate();
},
onunregistered: function onunregistered() {
_this.emit('stateChanged', 'unregistered');
_this._checkPendingUpdate();
},
onretry: function onretry(event, from, to, arg) {
return _this._retry(arg);
}
}
});
var platform = (typeof navigator !== 'undefined' ? navigator.userAgent : 'web').substring(0, 128);
Object.defineProperties(this, {
_transport: { value: transport },
_url: { value: config.registrarUri, writable: false },
_config: { value: config },
_productId: { value: productId },
_platform: { value: platform },
_fsm: { value: fsm },
_channelType: { value: channelType },
_registrationId: { value: false, writable: true },
_notificationId: { value: false },
_messageTypes: { value: [], writable: true },
_pendingUpdate: { value: false, writable: true }
});
EventEmitter.call(this);
}
inherits(RegistrarClient, EventEmitter);
/**
* Update service registration
* @param Array messageTypes Array of message type names
* @public
*/
RegistrarClient.prototype.update = function (notificationId, messageTypes) {
var regData = { notificationId: notificationId, messageTypes: messageTypes };
if (this._fsm.is('unregistered')) {
if (regData.notificationId && regData.messageTypes.length > 0) {
this._fsm.userUpdate(regData);
}
} else if (this._fsm.is('registered')) {
this._fsm.userUpdate(regData);
this._setPendingUpdate(regData);
} else {
this._setPendingUpdate(regData);
}
};
RegistrarClient.prototype._setPendingUpdate = function (regData) {
this._pendingUpdate = regData;
};
RegistrarClient.prototype._checkPendingUpdate = function () {
if (!this._pendingUpdate) {
return;
}
var pendingUpdate = this._pendingUpdate;
this._pendingUpdate = false;
this.update(pendingUpdate.notificationId, pendingUpdate.messageTypes);
};
RegistrarClient.prototype._retry = function (regData) {
if (!this._pendingUpdate) {
this._register(regData);
} else {
this._checkPendingUpdate();
}
};
RegistrarClient.prototype._register = function (regData) {
var _this2 = this;
/* eslint-disable camelcase */
var registrarRequest = {
endpoint_platform: this._platform,
channel_type: this._channelType,
version: '2',
message_types: regData.messageTypes,
data: {},
ttl: 'PT24H'
};
if (this._channelType === 'twilsock') {
registrarRequest.data.url = regData.notificationId;
} else {
registrarRequest.data.registration_id = regData.notificationId;
}
var uri = this._url + '?productId=' + this._productId;
var headers = {
'Content-Type': 'application/json',
'X-Twilio-Token': this._config.token
};
/* eslint-enable camelcase */
log.trace('NTFCN I: Creating registration for channel ', this._channelType);
return this._transport.post(uri, headers, registrarRequest).then(function (response) {
_this2._registrationId = response.body.id;
_this2._registrationData = regData;
log.debug('NTFCN I: Registration created: ', response);
_this2._fsm.registered();
}).catch(function (error) {
log.error('NTFCN E: Registration failed: ', error);
_this2._fsm.failure(regData);
return error;
});
};
RegistrarClient.prototype._unregister = function () {
var _this3 = this;
if (!this._registrationId) {
return Promise.resolve();
}
var uri = this._url + '/' + this._registrationId;
var headers = {
'Content-Type': 'application/json',
'X-Twilio-Token': this._config.token
};
log.trace('NTFCN I: removing registration for ', this._channelType);
this._transport.delete(uri, headers).then(function () {
log.debug('NTFCN I: registration removed for ', _this3._channelType);
_this3._registrationId = false;
_this3._fsm.unregistered();
}).catch(function (reason) {
// failure to remove registration since being treated as "unregistered" state
// because it is indicates that something wrong with server/connection
log.error('NTFCN E: failed to remove of registration ', _this3.channelType, reason);
_this3._fsm.failure();
return reason;
});
};
module.exports = RegistrarClient;
},{"events":232,"javascript-state-machine":264,"loglevel":265,"util":261}],23:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var log = require('loglevel');
var RegistrarClient = require('./registrar.connector');
/**
* Creates the new instance of ERS registrar client
*
* @class Registrar
* @classdesc Provides an interface to the ERS registrar
*/
function Registrar(productId, transport, config) {
var _this = this;
var subscriptions = {
twilsock: new Set(),
gcm: new Set()
};
var notificationIds = {
twilsock: null,
gcm: null
};
var twilsockRegistrarClient = new RegistrarClient(productId, transport, config, 'twilsock');
var gcmRegistrarClient = new RegistrarClient(productId, transport, config, 'gcm');
Object.defineProperties(this, {
_conf: { value: config },
_subscriptions: { value: subscriptions },
_notificationIds: { value: notificationIds },
_twilsockRegistrar: { value: twilsockRegistrarClient },
_gcmRegistrar: { value: gcmRegistrarClient }
});
EventEmitter.call(this);
twilsockRegistrarClient.on('stateChanged', function (value) {
return _this.emit('stateChanged', value);
});
}
inherits(Registrar, EventEmitter);
/**
* Sets notification ID.
* If new URI is different from previous, it triggers updating of registration for given channel
*
* @param {string} uri The notification ID
*/
Registrar.prototype.setNotificationId = function (channelType, notificationId) {
log.trace('NTFCN I: Notification id for channel ', channelType, notificationId);
if (this._notificationIds[channelType] !== notificationId) {
this._notificationIds[channelType] = notificationId;
this._updateRegistration(channelType);
}
};
/**
* Updates the subscriptions list
* Should be called after reliable transport reconnect
*/
Registrar.prototype.refreshSubscriptions = function () {
log.info('NTFCN: Refresh registrations');
this._updateTwilsockRegistration();
};
/**
* Checks if subscription for given message and channel already exists
*/
Registrar.prototype.hasSubscription = function (messageType, channelType) {
if (channelType === 'twilsock') {
return this._subscriptions.twilsock.has(messageType);
}
if (channelType === 'gcm') {
return this._subscriptions.gcm.has(messageType);
}
throw new Error('Unknown channel type: ' + channelType);
};
/**
* Subscribe for given type of message
*
* @param {String} messageType Message type identifier
* @param {String} channelType Channel type, can be 'twilsock' or 'gcm'
*/
Registrar.prototype.subscribe = function (messageType, channelType) {
if (this.hasSubscription(messageType, channelType)) {
return;
}
if (channelType === 'twilsock') {
if (this._subscriptions.twilsock.size === 0) {
this.emit('needReliableTransport', true);
}
this._subscriptions.twilsock.add(messageType);
this._updateTwilsockRegistration();
} else if (channelType === 'gcm') {
this._subscriptions.gcm.add(messageType);
this._updateGcmRegistration();
} else {
throw new Error('Can\'t subscribe to the channel type ' + channelType);
}
};
/**
* Remove subscription
* @param {String} messageType Message type
* @param {String} channelType Channel type (twilsock or gcm)
*/
Registrar.prototype.unsubscribe = function (messageType, channelType) {
if (!this.hasSubscription(messageType, channelType)) {
return;
}
if (channelType === 'twilsock') {
this._subscriptions.twilsock.delete(messageType);
this._updateTwilsockRegistration();
if (this._subscriptions.twilsock.size === 0) {
this.emit('needReliableTransport', false);
}
} else if (channelType === 'gcm') {
this._subscriptions.gcm.delete(messageType);
this._updateGcmRegistration();
}
};
/**
* Update all registrations for channel type
*/
Registrar.prototype._updateRegistration = function (channelType) {
if (channelType === 'twilsock') {
return this._updateTwilsockRegistration();
} else if (channelType === 'gcm') {
return this._updateGcmRegistration();
}
};
/**
* Updates registration for the GCM channel
* @private
*/
Registrar.prototype._updateTwilsockRegistration = function () {
if (!this._notificationIds.twilsock) {
log.trace('Ignoring twilsock registration update request: no twilsock id in place');
return; // Can't make twilsock registration without transport url
}
var notificationId = this._notificationIds.twilsock;
var activeSubscriptions = [];
this._subscriptions.twilsock.forEach(function (messageType) {
return activeSubscriptions.push(messageType);
});
log.debug('Subscribing to the twilsock notifications');
this._twilsockRegistrar.update(notificationId, activeSubscriptions);
};
/**
* Updates registration for the GCM channel
* @private
*/
Registrar.prototype._updateGcmRegistration = function () {
if (!this._notificationIds.gcm) {
log.trace('Ignoring twilsock registration update request: no twilsock id in place');
return; // Can't make gcm registration without transport url
}
var notificationId = this._notificationIds.gcm;
var activeSubscriptions = [];
this._subscriptions.gcm.forEach(function (messageType) {
return activeSubscriptions.push(messageType);
});
this._gcmRegistrar.update(notificationId, activeSubscriptions);
};
Object.freeze(Registrar);
module.exports = Registrar;
},{"./registrar.connector":22,"events":232,"loglevel":265,"util":261}],24:[function(require,module,exports){
'use strict';
var request = require('./request');
function parseUri(uri) {
var match = uri.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
if (match) {
var uriStruct = {
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
};
if (uriStruct.search.length > 0) {
var paramsString = uriStruct.search.substring(1);
uriStruct.params = paramsString.split('&').map(function (el) {
return el.split('=');
}).reduce(function (prev, curr) {
prev[curr[0]] = curr[1];return prev;
}, {});
}
return uriStruct;
}
throw new Error('Incorrect URI: ' + uri);
}
function twilsockAddress(method, uri) {
var parsedUri = parseUri(uri);
var to = {
method: method,
host: parsedUri.host,
path: parsedUri.pathname
};
if (parsedUri.params) {
to.params = parsedUri.params;
}
return to;
}
function twilsockParams(type, uri, headers, body) {
return {
to: twilsockAddress(type, uri),
headers: headers,
body: body
};
}
function adaptTwilsockResponse(response) {
return { status: response.status,
headers: response.header.http_headers,
body: response.body };
}
function httpParams(uri, headers, body) {
return {
url: uri,
headers: headers,
body: body
};
}
function adaptHttpResponse(response) {
try {
response.body = JSON.parse(response.body);
} finally {
return response;
}
}
/**
* @class Transport
* @classdesc Provides network interface
*/
function Transport(twilsock) {
Object.defineProperties(this, {
_activeGetRequests: { value: new Map() },
_twilsock: { value: twilsock },
_http: { value: request }
});
if (twilsock) {
twilsock.connect();
}
}
Transport.prototype._shouldUseTwilsock = function () {
return this._twilsock && this._twilsock.isConnected;
};
/**
* @private
*/
Transport.prototype._get = function (uri, headers) {
if (this._shouldUseTwilsock()) {
return this._twilsock.send(twilsockParams('GET', uri, headers)).then(adaptTwilsockResponse);
}
return this._http.get(httpParams(uri, headers)).then(adaptHttpResponse);
};
/**
* Make a GET request by given URI
*
* This function applies "multiplexing" optimization.
* If several requests for the same URI happen on the same time,
* only one will really happen, but all clients will see th result.
*
* @Returns Promise Result of successful get request
*/
Transport.prototype.get = function (uri, headers) {
var _this = this;
if (this._activeGetRequests.has(uri)) {
return this._activeGetRequests.get(uri);
}
var promise = this._get(uri, headers).then(function (response) {
_this._activeGetRequests.delete(uri);
return response;
}).catch(function (error) {
_this._activeGetRequests.delete(uri);
throw error;
});
this._activeGetRequests.set(uri, promise);
return promise;
};
/**
* Make a POST request by given URI
* @Returns Promise Result of successful request
*/
Transport.prototype.post = function (uri, headers, body) {
if (this._shouldUseTwilsock()) {
return this._twilsock.send(twilsockParams('POST', uri, headers, body)).then(adaptTwilsockResponse);
}
return this._http.post(httpParams(uri, headers, body)).then(adaptHttpResponse);
};
/**
* Make a PUT request by given URI
* @Returns Promise Result of successful request
*/
Transport.prototype.put = function (uri, headers, body) {
if (this._shouldUseTwilsock()) {
return this._twilsock.send(twilsockParams('PUT', uri, headers, body)).then(adaptTwilsockResponse);
}
return this._http.put(httpParams(uri, headers, body)).then(adaptHttpResponse);
};
/**
* Make a DELETE request by given URI
* @Returns Promise Result of successful request
*/
Transport.prototype.delete = function (uri, headers) {
if (this._shouldUseTwilsock()) {
return this._twilsock.send(twilsockParams('DELETE', uri, headers)).then(adaptHttpResponse);
}
return this._http.delete(httpParams(uri, headers)).then(adaptHttpResponse);
};
Object.freeze(Transport);
module.exports = Transport;
},{"./request":25}],25:[function(require,module,exports){
'use strict';
var XHR = typeof XMLHttpRequest === 'undefined' ? require('xmlhttprequest').XMLHttpRequest : XMLHttpRequest;
function parseResponseHeaders(headerString) {
return headerString.split('\r\n').map(function (el) {
return el.split(': ');
}).filter(function (el) {
return el.length === 2 && el[1].length > 0;
}).reduce(function (prev, curr) {
prev[curr[0]] = curr[1];return prev;
}, {});
}
function request(method, params) {
var promise = new Promise(function (resolve, reject) {
var xhr = new XHR();
xhr.open(method, params.url, true);
xhr.onreadystatechange = function onreadystatechange() {
if (xhr.readyState !== 4) {
return;
}
if (200 <= xhr.status && xhr.status < 300) {
var headers = parseResponseHeaders(xhr.getAllResponseHeaders());
resolve({ status: xhr.status, headers: headers, body: xhr.responseText });
} else {
reject({ status: xhr.status, description: xhr.statusText, body: xhr.responseText });
}
};
for (var headerName in params.headers) {
xhr.setRequestHeader(headerName, params.headers[headerName]);
if (headerName === 'Content-Type' && params.headers[headerName] === 'application/json') {
params.body = JSON.stringify(params.body);
}
}
xhr.send(params.body);
});
return promise;
}
/**
* Use XMLHttpRequest to get a network resource.
* @param {String} method - HTTP Method
* @param {Object} params - Request parameters
* @param {String} params.url - URL of the resource
* @param {Array} params.headers - An array of headers to pass [{ headerName : headerBody }]
* @param {Object} params.body - A JSON body to send to the resource
* @returns {Promise}
**/
var Request = request;
/**
* Sugar function for request('GET', params);
* @param {Object} params - Request parameters
* @returns {Promise}
*/
Request.get = function (params) {
return request('GET', params);
};
/**
* Sugar function for request('POST', params);
* @param {Object} params - Request parameters
* @returns {Promise}
*/
Request.post = function (params) {
return request('POST', params);
};
/**
* Sugar function for request('PUT', params);
* @param {Object} params - Request parameters
* @returns {Promise}
*/
Request.put = function (params) {
return request('PUT', params);
};
/**
* Sugar function for request('DELETE', params);
* @param {Object} params - Request parameters
* @returns {Promise}
*/
Request.delete = function (params) {
return request('DELETE', params);
};
module.exports = Request;
},{"xmlhttprequest":271}],26:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var log = require('loglevel');
var Configuration = require('./configuration.js');
var TwilsockChannel = require('./twilsock.js');
var PacketInterface = require('./packetinterface.js');
/**
* Client library for the Twilsock protocol
*/
function TwilsockClient(token, options) {
var _this = this;
var config = new Configuration(token, options);
var twilsock = new TwilsockChannel(config);
var packetInterface = new PacketInterface(twilsock);
Object.defineProperties(this, {
_config: { value: config },
_socket: { value: twilsock },
_network: { value: packetInterface },
isConnected: { get: function get() {
return _this._socket.isConnected();
} }
});
EventEmitter.call(this);
this._socket.on('message', function (type, message) {
return _this.emit('message', type, message);
});
this._socket.on('connected', function (uri) {
return _this.emit('connected', uri);
});
this._socket.on('disconnected', function () {
return _this.emit('disconnected');
});
}
inherits(TwilsockClient, EventEmitter);
/**
* Send a message
* @param {Object} message Message structure with header, body and remote address
* @public
* @returns {Promise} Result from remote side
*/
TwilsockClient.prototype.send = function (message) {
return this._network.send(message.to, message.headers, message.body);
};
/**
* @param {String} token authentification token
* @public
*/
TwilsockClient.prototype.setAuthToken = function (token) {
var _this2 = this;
log.info('DSS I: authTokenUpdated');
this._config.updateToken(token);
this._socket.disconnect().then(function () {
return _this2._socket.connect();
});
};
/**
* Connect to the server
* @fires TwilsockClient#connected
* @public
*/
TwilsockClient.prototype.connect = function () {
return this._socket.connect();
};
/**
* Connect to the server
* @fires TwilsockClient#disconnected
* @public
*/
TwilsockClient.prototype.disconnect = function () {
return this._socket.disconnect();
};
Object.freeze(TwilsockClient);
/**
* Fired when new message received
* @param {Object} message
* @event TwilsockClient#message
*/
/**
* Fired when socket connected
* @param {String} URI of endpoint
* @event TwilsockClient#connected
*/
/**
* Fired when socket disconnected
* @event TwilsockClient#disconnected
*/
module.exports = TwilsockClient;
},{"./configuration.js":27,"./packetinterface.js":28,"./twilsock.js":29,"events":232,"loglevel":265,"util":261}],27:[function(require,module,exports){
'use strict';
var TWILSOCK_URI = 'wss://tsock.twilio.com';
var TWILSOCK_PATH = '/v2/wsconnect';
/**
* @param {String} token - authentication token
* @param {Object} options - options to override defaults
*
* @class TwilsockConfig
* @classdesc Settings container for the Twilsock client library
*/
function TwilsockConfig(token, options) {
var _this = this;
options = options || {};
var _options = options.Twilsock || {};
var twilsockUri = _options.uri || options.wsServer || TWILSOCK_URI;
Object.defineProperties(this, {
_twilsockWsHost: { value: twilsockUri + TWILSOCK_PATH },
_token: { value: token, writable: true },
token: { get: function get() {
return _this._token;
} },
twilsockUri: { get: function get() {
return _this._twilsockWsHost;
} }
});
}
TwilsockConfig.prototype.updateToken = function (token) {
this._token = token;
};
module.exports = TwilsockConfig;
},{}],28:[function(require,module,exports){
'use strict';
var log = require('loglevel');
function PacketInterface(socket) {
Object.defineProperties(this, {
_activeRequests: { value: new Map() },
_socket: { value: socket }
});
this._socket.on('reply', this._processReply.bind(this));
}
function isHttpSuccess(code) {
return [200, 201, 204].indexOf(code) !== -1;
}
PacketInterface.prototype._processReply = function (reply) {
var request = this._activeRequests.get(reply.id);
if (request) {
this._activeRequests.delete(reply.id);
if (!isHttpSuccess(reply.status.code)) {
request.reject(new Error('Transport failure: ' + reply.status.status));
} else if (!isHttpSuccess(reply.header.http_status.code)) {
request.reject({ status: reply.header.http_status.code,
description: reply.header.http_status.status,
body: reply.body });
} else {
request.resolve(reply);
}
}
};
PacketInterface.prototype.send = function (address, headers, body) {
var _this = this;
return new Promise(function (resolve, reject) {
var id = _this._socket.send(address, headers, body);
log.trace('Twilsock: message sent: ', { id: id, address: address, headers: headers, body: body });
_this._activeRequests.set(id, { resolve: resolve, reject: reject });
});
};
module.exports = PacketInterface;
},{"loglevel":265}],29:[function(require,module,exports){
(function (Buffer){
'use strict';
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
var EventEmitter = require('events').EventEmitter;
var util = require('../../util');
var inherits = require('util').inherits;
var log = require('loglevel');
var WebSocket = require('ws');
var StateMachine = require('javascript-state-machine');
/**
* @class TwilsockChannel
* @classdesc Twilsock connection
*
* @param config
*/
function TwilsockChannel(config) {
var _this = this,
_arguments = arguments;
var fsm = StateMachine.create({
initial: 'disconnected',
events: [{ name: 'userConnect', from: ['disconnected'], to: 'connecting' }, { name: 'userDisconnect', from: ['connecting', 'connected', 'retrying'], to: 'disconnecting' }, { name: 'userRetry', from: ['retrying'], to: 'connecting' }, { name: 'socketConnected', from: ['connecting'], to: 'connected' }, { name: 'socketClosed', from: ['connecting', 'connected'], to: 'retrying' }, { name: 'socketClosed', from: ['disconnecting'], to: 'disconnected' }, { name: 'socketRejected', from: ['connecting', 'connected'], to: 'disconnecting' }],
callbacks: {
onconnecting: this._setupSocket.bind(this),
onretrying: this._retry.bind(this),
onenterconnected: this._onTransportReady.bind(this, true),
onleaveconnected: this._onTransportReady.bind(this, false),
onuserDisconnect: this._closeSocket.bind(this),
ondisconnected: function ondisconnected() {
if (_this._disconnectedPromiseResolve) {
var resolve = _this._disconnectedPromiseResolve;
_this._disconnectedPromiseResolve = null;
resolve();
}
},
onsocketRejected: function onsocketRejected() {
var args = Array.prototype.slice.call(_arguments, 3, _arguments.length);
_this._onSocketRejected(args);
}
},
error: function error() {
log.trace('Twilsock FSM: unexpected transition', arguments);
}
});
Object.defineProperties(this, {
_config: { value: config },
_transportReady: { value: false, writable: true },
_disconnectedPromiseResolve: { value: null, writable: true },
_fsm: { value: fsm }
});
EventEmitter.call(this);
}
inherits(TwilsockChannel, EventEmitter);
TwilsockChannel.prototype._retry = function () {
var _this2 = this;
delete this._socket;
this._retryTimeout = setTimeout(function () {
_this2._fsm.userRetry();
}, 1000);
};
TwilsockChannel.prototype._onConnected = function () {
this._onTransportReady(true);
};
TwilsockChannel.prototype._onDisconnected = function () {
this._onTransportReady(false);
};
function getMagic(buffer) {
var strMagic = '';
var idx = 0;
for (; idx < buffer.length; ++idx) {
var chr = String.fromCharCode(buffer[idx]);
strMagic += chr;
if (chr === '\r') {
idx += 2;
break;
}
}
var magics = strMagic.split(' ');
return {
size: idx,
protocol: magics[0],
version: magics[1],
headerSize: Number(magics[2])
};
}
/**
* @param {Uint8Array} array
* @returns {Object}
*/
function getJsonObject(array) {
return JSON.parse(new Buffer(array).toString());
}
TwilsockChannel.prototype._setupSocket = function () {
var self = this;
var uri = this._config.twilsockUri + '?token=' + this._config.token;
var socket = new WebSocket(uri);
socket.binaryType = 'arraybuffer';
socket.onopen = function () {
log.info('NTFCN I: Twilsock socket opened');
};
socket.onclose = function () {
log.info('NTFCN I: socket closed');
self._fsm.socketClosed();
};
socket.onerror = function (error) {
log.error('NTFCN E: ', error);
// self._fsm.socketError();
};
// Log messages from the server
socket.onmessage = function (message) {
log.trace('NTFCN: twilsock: ', message.data);
var fieldMargin = 2;
var dataView = new Uint8Array(message.data);
var magic = getMagic(dataView);
if (magic.protocol !== 'TWILSOCK' || magic.version !== 'V1.0') {
throw new Error('Unsupported protocol: ' + magic.protocol + ' ver ' + magic.version);
}
var header = getJsonObject(dataView.subarray(magic.size, magic.size + magic.headerSize));
log.trace('Twilsock: message received: ', header);
var payload = null;
if (header.payload_size > 0) {
var payloadOffset = fieldMargin + magic.size + magic.headerSize;
if (!header.hasOwnProperty('payload_type') || header.payload_type.startsWith('application/json')) {
payload = getJsonObject(dataView.subarray(payloadOffset));
} else if (header.payload_type.startsWith('text/plain')) {
payload = new Buffer(dataView.subarray(payloadOffset)).toString();
}
}
if (header.method === 'ready') {
log.trace('Twilsock ready', payload);
self._wschannelUrl = payload.wschannel_url;
self._fsm.socketConnected();
self._confirmReceiving(header);
} else if (header.method === 'notification') {
self._confirmReceiving(header);
self.emit('message', header.message_type, payload);
} else if (header.method === 'reply') {
self.emit('reply', { id: header.id,
status: header.status,
header: header,
body: payload });
} else if (header.method === 'close') {
log.trace('Twilsock connection close initated by server');
self._confirmReceiving(header);
self._fsm.socketRejected(payload);
}
};
this._socket = socket;
};
/**
* Should be called for each message to confirm it received
*/
TwilsockChannel.prototype._confirmReceiving = function (messageHeader) {
/* eslint-disable camelcase */
var header = {
method: 'reply',
id: messageHeader.id,
payload_type: 'application/json',
status: { code: 200, status: 'OK' }
};
/* eslint-enable camelcase */
this._sendPacket(header);
};
/**
* Makes sure that body is properly stringified
*/
function preparePayload(payload) {
switch (typeof payload === 'undefined' ? 'undefined' : _typeof(payload)) {
case 'undefined':
return '';
case 'object':
return JSON.stringify(payload);
default:
return payload;
}
}
/**
* Prepare binary packet and send it over the network
*/
TwilsockChannel.prototype._sendPacket = function (header, payload) {
/* eslint-disable camelcase */
var payloadString = preparePayload(payload);
header.payload_size = Buffer.byteLength(payloadString);
var headerString = JSON.stringify(header) + '\r\n';
var magicString = 'TWILSOCK V1.0 ' + (Buffer.byteLength(headerString) - 2) + '\r\n';
var message = new Uint8Array(new Buffer(magicString + headerString + payloadString));
this._socket.send(message.buffer);
/* eslint-enable camelcase */
};
/**
* Cancels pending retry attempt if it exists
* @private
*/
TwilsockChannel.prototype._cancelRetryAttempt = function () {
if (this._retryTimeout) {
clearTimeout(this._retryTimeout);
delete this._retryTimeout;
}
};
/**
* Shutdown connection
* @private
*/
TwilsockChannel.prototype._closeSocket = function () {
this._cancelRetryAttempt();
if (this._socket) {
this._socket.close();
}
};
/**
* Initiate the twilsock connection
* If already connected, it does nothing
*/
TwilsockChannel.prototype.connect = function () {
this._fsm.userConnect();
};
/**
* Close twilsock connection
* If already disconnected, it does nothing
*/
TwilsockChannel.prototype.disconnect = function () {
var _this3 = this;
if (this._fsm.is('disconnected')) {
return Promise.resolve();
}
return new Promise(function (resolve) {
_this3._fsm.userDisconnect();
_this3._disconnectedPromiseResolve = resolve;
});
};
/**
* Checks if connection established
*/
TwilsockChannel.prototype.isConnected = function () {
return this._socket && this._socket.readyState === 1;
};
/**
* Send upstream message
* @returns {String} id of sent message
*/
TwilsockChannel.prototype.send = function (address, headers, body) {
/* eslint-disable camelcase */
var id = util.makeUUID();
var httpHeader = {
host: address.host,
path: address.path,
method: address.method
};
if (address.hasOwnProperty('params')) {
httpHeader.params = address.params;
}
var twilsockHeader = {
method: 'message',
id: id,
http_header: httpHeader
};
if (headers) {
twilsockHeader.http_header.headers = headers;
}
if (headers && headers.hasOwnProperty('Content-Type')) {
twilsockHeader.payload_type = headers['Content-Type'];
}
this._sendPacket(twilsockHeader, body);
return id;
/* eslint-enable camelcase */
};
/**
* Notify client that transport is ready
*/
TwilsockChannel.prototype._onTransportReady = function (state) {
if (this._transportReady !== state) {
this._transportReady = state;
if (this._transportReady === true) {
log.trace('Twilsock connected: ', this._wschannelUrl);
this._state = 'connected';
this.emit('connected', this._wschannelUrl);
} else {
log.trace('Twilsock disconnected');
this._wschannelUrl = null;
this._state = 'disconnected';
this.emit('disconnected');
}
}
};
/**
* @private
*/
TwilsockChannel.prototype._onSocketRejected = function socketRejected(reason) {
log.error('Twilsock connection denied', reason);
this.emit('remoteClose', reason);
this._closeSocket();
};
Object.freeze(TwilsockChannel);
module.exports = TwilsockChannel;
}).call(this,require("buffer").Buffer)
},{"../../util":33,"buffer":228,"events":232,"javascript-state-machine":264,"loglevel":265,"util":261,"ws":270}],30:[function(require,module,exports){
'use strict';
function IPMessaging(token, options) {
return new IPMessaging.Client(token, options);
}
IPMessaging.Client = require('./clients/ipmessaging/client');
IPMessaging.DataSyncClient = require('./clients/datasync/client');
IPMessaging.NotificationClient = require('./clients/notification/client');
IPMessaging.Transport = require('./clients/transport');
IPMessaging.TwilsockClient = require('./clients/twilsock/client');
module.exports = IPMessaging;
},{"./clients/datasync/client":2,"./clients/ipmessaging/client":12,"./clients/notification/client":20,"./clients/transport":24,"./clients/twilsock/client":26}],31:[function(require,module,exports){
'use strict';
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var JsonDiff = require('./jsondiff');
/**
* Tracks changes for JS objects and emits appropriate callbacks
*/
function ChangeTracker(data) {
var _this = this;
Object.defineProperties(this, {
_pendingListeners: { value: {} },
_data: { value: data || {}, writable: true }
});
EventEmitter.call(this);
['keyAdded', 'keyRemoved', 'keyUpdated'].forEach(function (eventName) {
_this._pendingListeners[eventName] = {};
_this.on(eventName, function (path, value) {
var handlers = _this._pendingListeners[eventName][path] || [];
handlers.forEach(function (handler) {
return handler(value);
});
_this._pendingListeners[eventName][path] = [];
});
});
}
inherits(ChangeTracker, EventEmitter);
/**
* Compare old and new data and fire events if difference found
* @private
*/
ChangeTracker.prototype._traverse = function (originalData, updatedData) {
var _this2 = this;
var diff = JsonDiff.diff(originalData, updatedData);
diff.forEach(function (row) {
if (row.op === 'add') {
_this2.emit('keyAdded', row.path, row.value);
} else if (row.op === 'replace') {
_this2.emit('keyUpdated', row.path, row.value);
} else if (row.op === 'remove') {
_this2.emit('keyRemoved', row.path);
}
});
};
/**
* Set new data to process
* @param Object updatedData new data set
* @public
*/
ChangeTracker.prototype.update = function (updatedData) {
var originalData = this._data;
this._data = updatedData;
this._traverse(originalData, updatedData);
};
ChangeTracker.prototype.addEventHandler = function (eventName, path, handler) {
var handlers = this._pendingListeners[eventName][path] || [];
handlers.push(handler);
this._pendingListeners[eventName][path] = handlers;
};
module.exports = ChangeTracker;
},{"./jsondiff":34,"events":232,"util":261}],32:[function(require,module,exports){
'use strict';
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + s4() + s4() + s4() + s4() + s4() + s4();
}
module.exports = guid;
},{}],33:[function(require,module,exports){
(function (Buffer){
'use strict';
/**
* Decode a base64-encoded string.
* @param {string} encoded - the base64-encoded string
* @returns {string}
*/
var decodeBase64 = typeof atob === 'function' ? atob : function (encoded) {
return new Buffer(encoded, 'base64').toString('ascii');
};
/**
* Base64-encode a string.
* @param {string} plaintext - the string to base64-encode
* @returns {string}
*/
var encodeBase64 = typeof btoa === 'function' ? btoa : function (message) {
return new Buffer(message).toString('base64');
};
var base64 = {
decode: decodeBase64,
encode: encodeBase64
};
/**
* Decode a base64url-encoded string.
* @param {string} encoded - the base64url-encoded string
* @returns {string}
*/
function decodeBase64URL(encoded) {
var remainder = encoded.length % 4;
if (remainder > 0) {
var padlen = 4 - remainder;
encoded += new Array(padlen + 1).join('=');
}
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
return decodeBase64(encoded);
}
/**
* Memoize a function. Be careful with this.
* @param {function} fn - the function to memoize
* @returns {function}
*/
function memoize(fn) {
var memo = {};
return function () {
var args = Array.prototype.slice.call(arguments, 0);
return memo[args] ? memo[args] : memo[args] = fn.apply(null, args);
};
}
var base64URL = {
decode: memoize(decodeBase64URL)
};
/**
* Deep-clone an object. Note that this does not work on object containing
* functions.
* @param {object} obj - the object to deep-clone
* @returns {object}
*/
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* Decode an x-www-form-urlencoded string into an array of key-value pairs.
* @param {string} encoded - the x-www-form-urlencoded string
* @returns {Array}
*/
// FIXME: Currently returns an object.
function fromURLFormEncoded(params) {
if (!params) {
return {};
}
var result = {};
var pairs = params.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
var key = decodeURIComponent(pair[0]);
var val = pair[1] ? decodeURIComponent(pair[1]) : null;
result[key] = val;
}
return result;
}
function makeSystemInfo() {
var nav = typeof navigator === 'undefined' ? {} : navigator;
return {
p: 'browser',
browser: {
userAgent: nav.userAgent || 'unknown',
platform: nav.platform || 'unknown'
},
plugin: 'rtc'
};
}
/**
* Encode an array of key-value pairs as an x-www-form-urlencoded string.
* @param {Array} pairs - the array of key-value pairs
* @returns {string}
*/
// FIXME: Currently this uses objects.
function toURLFormEncoded(dict) {
var str = '';
for (var key in dict) {
str += encodeURIComponent(key) + '=' + encodeURIComponent(dict[key]);
}
return str;
}
/**
* Require a given module without Browserify attempting to package it for us.
* @param {string} module - the module to require
* @returns {Object}
*/
function requireNoBrowserify(module) {
return eval('require(\'' + module + '\')');
}
function getKeys(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
}
function getValues(obj) {
var values = [];
for (var key in obj) {
values.push(obj[key]);
}
return values;
}
function makeUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
}
function _withDefaults(destination, source) {
for (var key in source) {
if (!(key in destination)) {
destination[key] = source[key];
}
}
return destination;
}
function withDefaults(destination, sources) {
destination = destination || {};
sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
_withDefaults(destination, source);
});
return destination;
}
function _extend(destination, source) {
for (var key in source) {
destination[key] = source[key];
}
return destination;
}
function extend(destination, sources) {
destination = destination || {};
sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
_extend(destination, source);
});
return destination;
}
function tails(xs) {
if (xs.length === 0) {
return [[]];
} else {
return [xs].concat(tails(xs.slice(1)));
}
}
function _return(value) {
return function () {
return value;
};
}
function faultTolerantWait(promises) {
return new Promise(function (resolve) {
var totalCount = promises.length;
var failuresCount = 0;
if (totalCount === 0) {
resolve();
}
function handle() {
if (--totalCount <= 0) {
resolve(failuresCount);
}
}
promises.forEach(function (promise) {
promise.then(handle).catch(function () {
failuresCount++;handle();
});
});
});
}
function emitNext() {
var args = [].slice.call(arguments);
var eventEmitter = args[0];
args = args.slice(1);
setTimeout(function () {
eventEmitter.emit.call(eventEmitter, args);
});
return eventEmitter;
}
/**
* Traverse down multiple nodes on an object and return null if
* any link in the path is unavailable.
* @param {Object} obj - Object to traverse
* @param {String} path - Path to traverse. Period-separated.
* @returns {Any|null}
*/
function getOrNull(obj, path) {
return path.split('.').reduce(function (output, step) {
if (!output) {
return null;
}
return output[step];
}, obj);
}
/**
* Parse the passed userAgent string down into a simple object.
* Example browser object: { name: 'Chrome', version: '42.0' }
* @returns {Object} Object containing a name and version.
*/
function parseUserAgent(ua) {
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)\.(\d+)/i) || [];
var specs = { name: M[1], version: M[2] + '.' + M[3] };
var parts;
if (/trident/i.test(specs.name)) {
parts = /\brv[ :]+(\d+)\.(\d+)/g.exec(ua) || [];
return { name: 'IE', version: parts[1] ? parts[1] + '.' + parts[2] : '' };
}
if (specs.name === 'Chrome') {
parts = ua.match(/\b(OPR|Edge)\/(\d+)\.(\d+)/);
if (parts !== null) {
return { name: 'Opera', version: parts[2] + '.' + parts[3] };
}
}
if (specs.name === 'MSIE') {
specs.name = 'IE';
}
return specs;
}
/**
* Overwrite an existing Array with a new one. This is useful when the existing
* Array is an immutable property of another object.
* @param {Array} oldArray - the existing Array to overwrite
* @param {Array} newArray - the new Array to overwrite with
*/
function overwriteArray(oldArray, newArray) {
oldArray.splice(0, oldArray.length);
newArray.forEach(function (item) {
oldArray.push(item);
});
}
/**
* Construct URI with query parameters
*/
function UriBuilder(base) {
Object.defineProperties(this, {
base: { value: base },
args: { value: [] }
});
this.arg = function (name, value) {
if (typeof value !== 'undefined') {
this.args.push(name + '=' + value);
}
return this;
};
this.build = function () {
return this.base + '?' + this.args.join('&');
};
}
module.exports.base64 = base64;
module.exports.base64URL = base64URL;
module.exports.deepClone = deepClone;
module.exports.fromURLFormEncoded = fromURLFormEncoded;
module.exports.requireNoBrowserify = requireNoBrowserify;
module.exports.getKeys = getKeys;
module.exports.getValues = getValues;
module.exports.makeUUID = makeUUID;
module.exports.withDefaults = withDefaults;
module.exports.extend = extend;
module.exports.tails = tails;
module.exports.return = _return;
module.exports.emitNext = emitNext;
module.exports.getOrNull = getOrNull;
module.exports.parseUserAgent = parseUserAgent;
module.exports.overwriteArray = overwriteArray;
module.exports.faultTolerantWait = faultTolerantWait;
module.exports.UriBuilder = UriBuilder;
}).call(this,require("buffer").Buffer)
},{"buffer":228}],34:[function(require,module,exports){
'use strict';
/**
* We're using that wersion of JSONdiff instead of vanilla one
* since vanilla has the bug in path calculation and maintaner doesn't accept the patch.
*
* Should return to the using of original module when situation will change
*/
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
function JsonDiff() {}
JsonDiff.prototype.toString = Object.prototype.toString;
JsonDiff.prototype.hasOwnProperty = Object.prototype.hasOwnProperty;
JsonDiff.prototype.isArray = function (obj) {
return this.toString.call(obj) === '[object Array]';
};
JsonDiff.prototype.isObject = function (obj) {
return this.toString.call(obj) === '[object Object]';
};
JsonDiff.prototype.isString = function (obj) {
return this.toString.call(obj) === '[object String]';
};
JsonDiff.prototype.isFunction = function (obj) {
return this.toString.call(obj) === '[object Function]';
};
JsonDiff.prototype.has = function (obj, key) {
return hasOwnProperty.call(obj, key);
};
JsonDiff.prototype.isEqual = function (a, b) {
return this.eq(a, b, [], []);
};
JsonDiff.prototype.isContainer = function (obj) {
return this.isArray(obj) || isObject(obj);
};
JsonDiff.prototype.isSameContainer = function (obj1, obj2) {
return this.isArray(obj1) && this.isArray(obj2) || this.isObject(obj1) && this.isObject(obj2);
};
JsonDiff.prototype.eq = function (a, b, aStack, bStack) {
var aCtor, bCtor, className, key, length, result, size;
if (a === b) {
return a !== 0 || 1 / a === 1 / b;
}
if (!(a != null) || !(b != null)) {
return a === b;
}
className = this.toString.call(a);
if (className !== this.toString.call(b)) {
return false;
}
switch (className) {
case '[object String]':
return a === String(b);
case '[object Number]':
return a !== +a ? b !== +b : a === 0 ? 1 / a === 1 / b : a === +b;
case '[object Date]':
case '[object Boolean]':
return +a === +b;
case '[object RegExp]':
return a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase;
}
if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) !== 'object' || (typeof b === 'undefined' ? 'undefined' : _typeof(b)) !== 'object') {
return false;
}
length = aStack.length;
if ((function () {
var _results;
_results = [];
while (length--) {
_results.push(aStack[length] === a);
}
return _results;
})()) {
return bStack[length] === b;
}
aStack.push(a);
bStack.push(b);
size = 0;
result = true;
if (className === '[object Array]') {
size = a.length;
result = size === b.length;
if (result) {
while (size--) {
if (!(result = this.eq(a[size], b[size], aStack, bStack))) {
break;
}
}
}
} else {
aCtor = a.constructor;
bCtor = b.constructor;
if (aCtor !== bCtor && !(this.isFunction(aCtor) && aCtor instanceof aCtor && this.isFunction(bCtor) && bCtor instanceof bCtor)) {
return false;
}
for (key in a) {
if (this.has(a, key)) {
size++;
if (!(result = this.has(b, key) && this.eq(a[key], b[key], aStack, bStack))) {
break;
}
}
}
if (result) {
for (key in b) {
if (this.has(b, key) && ! size--) {
break;
}
}
result = !size;
}
}
aStack.pop();
bStack.pop();
return result;
};
JsonDiff.prototype.getParent = function (paths, path) {
var parsedPath = path.replace(/\/[^\/]*$/, '');
if (!parsedPath) {
parsedPath = '/';
}
return paths[parsedPath];
};
JsonDiff.prototype.flattenObject = function (obj, prefix, paths) {
var i, key, o, _i, _len;
if (prefix == null) {
prefix = '/';
}
if (paths == null) {
paths = {};
}
paths[prefix] = {
path: prefix,
value: obj
};
if (prefix !== '/') {
prefix = prefix + '/';
}
if (this.isArray(obj)) {
for (i = _i = 0, _len = obj.length; _i < _len; i = ++_i) {
o = obj[i];
this.flattenObject(o, prefix + i, paths);
}
} else if (this.isObject(obj)) {
for (key in obj) {
o = obj[key];
this.flattenObject(o, prefix + key, paths);
}
}
return paths;
};
JsonDiff.prototype.diff = function (obj1, obj2) {
var add, doc, doc1, doc2, key, key1, key2, keyfrom, keyto, move, patch, paths1, paths2, remove, replace;
if (!this.isSameContainer(obj1, obj2)) {
throw new Error('Patches can only be derived from objects or arrays');
}
paths1 = this.flattenObject(obj1);
paths2 = this.flattenObject(obj2);
add = {};
remove = {};
replace = {};
move = {};
for (key in paths1) {
doc1 = paths1[key];
doc2 = paths2[key];
if (!this.getParent(paths2, key)) {
continue;
} else if (!doc2) {
remove[key] = doc1;
} else if (this.isSameContainer(doc1.value, doc2.value)) {
continue;
} else if (!this.isEqual(doc1.value, doc2.value)) {
replace[key] = doc2;
}
}
for (key in paths2) {
doc1 = paths1[key];
doc2 = paths2[key];
if (!doc1 && this.isSameContainer(this.getParent(paths1, key), this.getParent(paths2, key))) {
add[key] = doc2;
}
}
for (key1 in remove) {
doc1 = remove[key1];
for (key2 in add) {
doc2 = add[key2];
if (this.isEqual(doc2.value, doc1.value)) {
delete remove[key1];
delete add[key2];
move[key2] = key1;
break;
}
}
}
patch = [];
for (key in add) {
doc = add[key];
patch.push({
op: 'add',
path: key,
value: doc.value
});
}
for (key in remove) {
patch.push({
op: 'remove',
path: key
});
}
for (key in replace) {
doc = replace[key];
patch.push({
op: 'replace',
path: key,
value: doc.value
});
}
for (keyto in move) {
keyfrom = move[keyto];
patch.push({
op: 'move',
from: keyfrom,
path: keyto
});
}
return patch;
};
JsonDiff.diff = function (o1, o2) {
var diff = new JsonDiff();
return diff.diff(o1, o2);
};
JsonDiff.isDeepEqual = function (o1, o2) {
return this.diff(o1, o2).length === 0;
};
module.exports = JsonDiff;
},{}],35:[function(require,module,exports){
(function (global){
"use strict";
require("core-js/shim");
require("regenerator/runtime");
if (global._babelPolyfill) {
throw new Error("only one instance of babel/polyfill is allowed");
}
global._babelPolyfill = true;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"core-js/shim":222,"regenerator/runtime":223}],36:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],37:[function(require,module,exports){
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = require('./$.wks')('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)require('./$.hide')(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
},{"./$.hide":65,"./$.wks":117}],38:[function(require,module,exports){
var isObject = require('./$.is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./$.is-object":72}],39:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = require('./$.to-object')
, toIndex = require('./$.to-index')
, toLength = require('./$.to-length');
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, $$ = arguments
, end = $$.length > 2 ? $$[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
},{"./$.to-index":110,"./$.to-length":113,"./$.to-object":114}],40:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = require('./$.to-object')
, toIndex = require('./$.to-index')
, toLength = require('./$.to-length');
module.exports = [].fill || function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, $$ = arguments
, $$len = $$.length
, index = toIndex($$len > 1 ? $$[1] : undefined, length)
, end = $$len > 2 ? $$[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
},{"./$.to-index":110,"./$.to-length":113,"./$.to-object":114}],41:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./$.to-iobject')
, toLength = require('./$.to-length')
, toIndex = require('./$.to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index;
} return !IS_INCLUDES && -1;
};
};
},{"./$.to-index":110,"./$.to-iobject":112,"./$.to-length":113}],42:[function(require,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = require('./$.ctx')
, IObject = require('./$.iobject')
, toObject = require('./$.to-object')
, toLength = require('./$.to-length')
, asc = require('./$.array-species-create');
module.exports = function(TYPE){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? asc($this, length) : IS_FILTER ? asc($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"./$.array-species-create":43,"./$.ctx":51,"./$.iobject":68,"./$.to-length":113,"./$.to-object":114}],43:[function(require,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var isObject = require('./$.is-object')
, isArray = require('./$.is-array')
, SPECIES = require('./$.wks')('species');
module.exports = function(original, length){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return new (C === undefined ? Array : C)(length);
};
},{"./$.is-array":70,"./$.is-object":72,"./$.wks":117}],44:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./$.cof')
, TAG = require('./$.wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = (O = Object(it))[TAG]) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./$.cof":45,"./$.wks":117}],45:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],46:[function(require,module,exports){
'use strict';
var $ = require('./$')
, hide = require('./$.hide')
, redefineAll = require('./$.redefine-all')
, ctx = require('./$.ctx')
, strictNew = require('./$.strict-new')
, defined = require('./$.defined')
, forOf = require('./$.for-of')
, $iterDefine = require('./$.iter-define')
, step = require('./$.iter-step')
, ID = require('./$.uid')('id')
, $has = require('./$.has')
, isObject = require('./$.is-object')
, setSpecies = require('./$.set-species')
, DESCRIPTORS = require('./$.descriptors')
, isExtensible = Object.isExtensible || isObject
, SIZE = DESCRIPTORS ? '_s' : 'size'
, id = 0;
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!$has(it, ID)){
// can't set id to frozen object
if(!isExtensible(it))return 'F';
// not necessary to add id
if(!create)return 'E';
// add missing object id
hide(it, ID, ++id);
// return object id with prefix
} return 'O' + it[ID];
};
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
strictNew(that, C, NAME);
that._i = $.create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)$.setDesc(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"./$":80,"./$.ctx":51,"./$.defined":52,"./$.descriptors":53,"./$.for-of":61,"./$.has":64,"./$.hide":65,"./$.is-object":72,"./$.iter-define":76,"./$.iter-step":78,"./$.redefine-all":94,"./$.set-species":99,"./$.strict-new":103,"./$.uid":116}],47:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var forOf = require('./$.for-of')
, classof = require('./$.classof');
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
var arr = [];
forOf(this, false, arr.push, arr);
return arr;
};
};
},{"./$.classof":44,"./$.for-of":61}],48:[function(require,module,exports){
'use strict';
var hide = require('./$.hide')
, redefineAll = require('./$.redefine-all')
, anObject = require('./$.an-object')
, isObject = require('./$.is-object')
, strictNew = require('./$.strict-new')
, forOf = require('./$.for-of')
, createArrayMethod = require('./$.array-methods')
, $has = require('./$.has')
, WEAK = require('./$.uid')('weak')
, isExtensible = Object.isExtensible || isObject
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for frozen keys
var frozenStore = function(that){
return that._l || (that._l = new FrozenStore);
};
var FrozenStore = function(){
this.a = [];
};
var findFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
FrozenStore.prototype = {
get: function(key){
var entry = findFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findFrozen(this, key);
},
set: function(key, value){
var entry = findFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
strictNew(that, C, NAME);
that._i = id++; // collection id
that._l = undefined; // leak store for frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
if(!isExtensible(key))return frozenStore(this)['delete'](key);
return $has(key, WEAK) && $has(key[WEAK], this._i) && delete key[WEAK][this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
if(!isExtensible(key))return frozenStore(this).has(key);
return $has(key, WEAK) && $has(key[WEAK], this._i);
}
});
return C;
},
def: function(that, key, value){
if(!isExtensible(anObject(key))){
frozenStore(that).set(key, value);
} else {
$has(key, WEAK) || hide(key, WEAK, {});
key[WEAK][that._i] = value;
} return that;
},
frozenStore: frozenStore,
WEAK: WEAK
};
},{"./$.an-object":38,"./$.array-methods":42,"./$.for-of":61,"./$.has":64,"./$.hide":65,"./$.is-object":72,"./$.redefine-all":94,"./$.strict-new":103,"./$.uid":116}],49:[function(require,module,exports){
'use strict';
var global = require('./$.global')
, $export = require('./$.export')
, redefine = require('./$.redefine')
, redefineAll = require('./$.redefine-all')
, forOf = require('./$.for-of')
, strictNew = require('./$.strict-new')
, isObject = require('./$.is-object')
, fails = require('./$.fails')
, $iterDetect = require('./$.iter-detect')
, setToStringTag = require('./$.set-to-string-tag');
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO;
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
strictNew(target, C, NAME);
var that = new Base;
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
IS_WEAK || instance.forEach(function(val, key){
BUGGY_ZERO = 1 / key === -Infinity;
});
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"./$.export":56,"./$.fails":58,"./$.for-of":61,"./$.global":63,"./$.is-object":72,"./$.iter-detect":77,"./$.redefine":95,"./$.redefine-all":94,"./$.set-to-string-tag":100,"./$.strict-new":103}],50:[function(require,module,exports){
var core = module.exports = {version: '1.2.6'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],51:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./$.a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./$.a-function":36}],52:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],53:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./$.fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./$.fails":58}],54:[function(require,module,exports){
var isObject = require('./$.is-object')
, document = require('./$.global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./$.global":63,"./$.is-object":72}],55:[function(require,module,exports){
// all enumerable object keys, includes symbols
var $ = require('./$');
module.exports = function(it){
var keys = $.getKeys(it)
, getSymbols = $.getSymbols;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = $.isEnum
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key);
}
return keys;
};
},{"./$":80}],56:[function(require,module,exports){
var global = require('./$.global')
, core = require('./$.core')
, hide = require('./$.hide')
, redefine = require('./$.redefine')
, ctx = require('./$.ctx')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && key in target;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target && !own)redefine(target, key, out);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
module.exports = $export;
},{"./$.core":50,"./$.ctx":51,"./$.global":63,"./$.hide":65,"./$.redefine":95}],57:[function(require,module,exports){
var MATCH = require('./$.wks')('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
},{"./$.wks":117}],58:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],59:[function(require,module,exports){
'use strict';
var hide = require('./$.hide')
, redefine = require('./$.redefine')
, fails = require('./$.fails')
, defined = require('./$.defined')
, wks = require('./$.wks');
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, original = ''[KEY];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, exec(defined, SYMBOL, original));
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return original.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return original.call(string, this); }
);
}
};
},{"./$.defined":52,"./$.fails":58,"./$.hide":65,"./$.redefine":95,"./$.wks":117}],60:[function(require,module,exports){
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = require('./$.an-object');
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
},{"./$.an-object":38}],61:[function(require,module,exports){
var ctx = require('./$.ctx')
, call = require('./$.iter-call')
, isArrayIter = require('./$.is-array-iter')
, anObject = require('./$.an-object')
, toLength = require('./$.to-length')
, getIterFn = require('./core.get-iterator-method');
module.exports = function(iterable, entries, fn, that){
var iterFn = getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
call(iterator, f, step.value, entries);
}
};
},{"./$.an-object":38,"./$.ctx":51,"./$.is-array-iter":69,"./$.iter-call":74,"./$.to-length":113,"./core.get-iterator-method":118}],62:[function(require,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./$.to-iobject')
, getNames = require('./$').getNames
, toString = {}.toString;
var windowNames = typeof window == 'object' && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return getNames(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.get = function getOwnPropertyNames(it){
if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it);
return getNames(toIObject(it));
};
},{"./$":80,"./$.to-iobject":112}],63:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],64:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],65:[function(require,module,exports){
var $ = require('./$')
, createDesc = require('./$.property-desc');
module.exports = require('./$.descriptors') ? function(object, key, value){
return $.setDesc(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./$":80,"./$.descriptors":53,"./$.property-desc":93}],66:[function(require,module,exports){
module.exports = require('./$.global').document && document.documentElement;
},{"./$.global":63}],67:[function(require,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],68:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./$.cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./$.cof":45}],69:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./$.iterators')
, ITERATOR = require('./$.wks')('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./$.iterators":79,"./$.wks":117}],70:[function(require,module,exports){
// 7.2.2 IsArray(argument)
var cof = require('./$.cof');
module.exports = Array.isArray || function(arg){
return cof(arg) == 'Array';
};
},{"./$.cof":45}],71:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var isObject = require('./$.is-object')
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"./$.is-object":72}],72:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],73:[function(require,module,exports){
// 7.2.8 IsRegExp(argument)
var isObject = require('./$.is-object')
, cof = require('./$.cof')
, MATCH = require('./$.wks')('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
},{"./$.cof":45,"./$.is-object":72,"./$.wks":117}],74:[function(require,module,exports){
// call something on iterator step with safe closing on error
var anObject = require('./$.an-object');
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"./$.an-object":38}],75:[function(require,module,exports){
'use strict';
var $ = require('./$')
, descriptor = require('./$.property-desc')
, setToStringTag = require('./$.set-to-string-tag')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./$.hide')(IteratorPrototype, require('./$.wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./$":80,"./$.hide":65,"./$.property-desc":93,"./$.set-to-string-tag":100,"./$.wks":117}],76:[function(require,module,exports){
'use strict';
var LIBRARY = require('./$.library')
, $export = require('./$.export')
, redefine = require('./$.redefine')
, hide = require('./$.hide')
, has = require('./$.has')
, Iterators = require('./$.iterators')
, $iterCreate = require('./$.iter-create')
, setToStringTag = require('./$.set-to-string-tag')
, getProto = require('./$').getProto
, ITERATOR = require('./$.wks')('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, methods, key;
// Fix native
if($native){
var IteratorPrototype = getProto($default.call(new Base));
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// FF fix
if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: !DEF_VALUES ? $default : getMethod('entries')
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./$":80,"./$.export":56,"./$.has":64,"./$.hide":65,"./$.iter-create":75,"./$.iterators":79,"./$.library":82,"./$.redefine":95,"./$.set-to-string-tag":100,"./$.wks":117}],77:[function(require,module,exports){
var ITERATOR = require('./$.wks')('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ safe = true; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
},{"./$.wks":117}],78:[function(require,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],79:[function(require,module,exports){
module.exports = {};
},{}],80:[function(require,module,exports){
var $Object = Object;
module.exports = {
create: $Object.create,
getProto: $Object.getPrototypeOf,
isEnum: {}.propertyIsEnumerable,
getDesc: $Object.getOwnPropertyDescriptor,
setDesc: $Object.defineProperty,
setDescs: $Object.defineProperties,
getKeys: $Object.keys,
getNames: $Object.getOwnPropertyNames,
getSymbols: $Object.getOwnPropertySymbols,
each: [].forEach
};
},{}],81:[function(require,module,exports){
var $ = require('./$')
, toIObject = require('./$.to-iobject');
module.exports = function(object, el){
var O = toIObject(object)
, keys = $.getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"./$":80,"./$.to-iobject":112}],82:[function(require,module,exports){
module.exports = false;
},{}],83:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
module.exports = Math.expm1 || function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
};
},{}],84:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
},{}],85:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
},{}],86:[function(require,module,exports){
var global = require('./$.global')
, macrotask = require('./$.task').set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = require('./$.cof')(process) == 'process'
, head, last, notify;
var flush = function(){
var parent, domain, fn;
if(isNode && (parent = process.domain)){
process.domain = null;
parent.exit();
}
while(head){
domain = head.domain;
fn = head.fn;
if(domain)domain.enter();
fn(); // <- currently we use it only for Promise - try / catch not required
if(domain)domain.exit();
head = head.next;
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = 1
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = -toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
notify = function(){
Promise.resolve().then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
module.exports = function asap(fn){
var task = {fn: fn, next: undefined, domain: isNode && process.domain};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
},{"./$.cof":45,"./$.global":63,"./$.task":109}],87:[function(require,module,exports){
// 19.1.2.1 Object.assign(target, source, ...)
var $ = require('./$')
, toObject = require('./$.to-object')
, IObject = require('./$.iobject');
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = require('./$.fails')(function(){
var a = Object.assign
, A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, $$ = arguments
, $$len = $$.length
, index = 1
, getKeys = $.getKeys
, getSymbols = $.getSymbols
, isEnum = $.isEnum;
while($$len > index){
var S = IObject($$[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
}
return T;
} : Object.assign;
},{"./$":80,"./$.fails":58,"./$.iobject":68,"./$.to-object":114}],88:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./$.export')
, core = require('./$.core')
, fails = require('./$.fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"./$.core":50,"./$.export":56,"./$.fails":58}],89:[function(require,module,exports){
var $ = require('./$')
, toIObject = require('./$.to-iobject')
, isEnum = $.isEnum;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = $.getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
},{"./$":80,"./$.to-iobject":112}],90:[function(require,module,exports){
// all object keys, includes non-enumerable and symbols
var $ = require('./$')
, anObject = require('./$.an-object')
, Reflect = require('./$.global').Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = $.getNames(anObject(it))
, getSymbols = $.getSymbols;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
},{"./$":80,"./$.an-object":38,"./$.global":63}],91:[function(require,module,exports){
'use strict';
var path = require('./$.path')
, invoke = require('./$.invoke')
, aFunction = require('./$.a-function');
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, $$ = arguments
, $$len = $$.length
, j = 0, k = 0, args;
if(!holder && !$$len)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = $$[k++];
while($$len > k)args.push($$[k++]);
return invoke(fn, args, that);
};
};
},{"./$.a-function":36,"./$.invoke":67,"./$.path":92}],92:[function(require,module,exports){
module.exports = require('./$.global');
},{"./$.global":63}],93:[function(require,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],94:[function(require,module,exports){
var redefine = require('./$.redefine');
module.exports = function(target, src){
for(var key in src)redefine(target, key, src[key]);
return target;
};
},{"./$.redefine":95}],95:[function(require,module,exports){
// add fake Function#toString
// for correct work wrapped methods / constructors with methods like LoDash isNative
var global = require('./$.global')
, hide = require('./$.hide')
, SRC = require('./$.uid')('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
require('./$.core').inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
if(typeof val == 'function'){
val.hasOwnProperty(SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
val.hasOwnProperty('name') || hide(val, 'name', key);
}
if(O === global){
O[key] = val;
} else {
if(!safe)delete O[key];
hide(O, key, val);
}
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
},{"./$.core":50,"./$.global":63,"./$.hide":65,"./$.uid":116}],96:[function(require,module,exports){
module.exports = function(regExp, replace){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(it).replace(regExp, replacer);
};
};
},{}],97:[function(require,module,exports){
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
},{}],98:[function(require,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var getDesc = require('./$').getDesc
, isObject = require('./$.is-object')
, anObject = require('./$.an-object');
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = require('./$.ctx')(Function.call, getDesc(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"./$":80,"./$.an-object":38,"./$.ctx":51,"./$.is-object":72}],99:[function(require,module,exports){
'use strict';
var global = require('./$.global')
, $ = require('./$')
, DESCRIPTORS = require('./$.descriptors')
, SPECIES = require('./$.wks')('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"./$":80,"./$.descriptors":53,"./$.global":63,"./$.wks":117}],100:[function(require,module,exports){
var def = require('./$').setDesc
, has = require('./$.has')
, TAG = require('./$.wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"./$":80,"./$.has":64,"./$.wks":117}],101:[function(require,module,exports){
var global = require('./$.global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./$.global":63}],102:[function(require,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = require('./$.an-object')
, aFunction = require('./$.a-function')
, SPECIES = require('./$.wks')('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"./$.a-function":36,"./$.an-object":38,"./$.wks":117}],103:[function(require,module,exports){
module.exports = function(it, Constructor, name){
if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!");
return it;
};
},{}],104:[function(require,module,exports){
var toInteger = require('./$.to-integer')
, defined = require('./$.defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./$.defined":52,"./$.to-integer":111}],105:[function(require,module,exports){
// helper for String#{startsWith, endsWith, includes}
var isRegExp = require('./$.is-regexp')
, defined = require('./$.defined');
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
},{"./$.defined":52,"./$.is-regexp":73}],106:[function(require,module,exports){
// https://github.com/ljharb/proposal-string-pad-left-right
var toLength = require('./$.to-length')
, repeat = require('./$.string-repeat')
, defined = require('./$.defined');
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength)return S;
if(fillStr == '')fillStr = ' ';
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
},{"./$.defined":52,"./$.string-repeat":107,"./$.to-length":113}],107:[function(require,module,exports){
'use strict';
var toInteger = require('./$.to-integer')
, defined = require('./$.defined');
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
},{"./$.defined":52,"./$.to-integer":111}],108:[function(require,module,exports){
var $export = require('./$.export')
, defined = require('./$.defined')
, fails = require('./$.fails')
, spaces = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec){
var exp = {};
exp[KEY] = exec(trim);
$export($export.P + $export.F * fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
}), 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
},{"./$.defined":52,"./$.export":56,"./$.fails":58}],109:[function(require,module,exports){
var ctx = require('./$.ctx')
, invoke = require('./$.invoke')
, html = require('./$.html')
, cel = require('./$.dom-create')
, global = require('./$.global')
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listner = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(require('./$.cof')(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listner;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listner, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"./$.cof":45,"./$.ctx":51,"./$.dom-create":54,"./$.global":63,"./$.html":66,"./$.invoke":67}],110:[function(require,module,exports){
var toInteger = require('./$.to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./$.to-integer":111}],111:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],112:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./$.iobject')
, defined = require('./$.defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./$.defined":52,"./$.iobject":68}],113:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./$.to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./$.to-integer":111}],114:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./$.defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./$.defined":52}],115:[function(require,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./$.is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./$.is-object":72}],116:[function(require,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],117:[function(require,module,exports){
var store = require('./$.shared')('wks')
, uid = require('./$.uid')
, Symbol = require('./$.global').Symbol;
module.exports = function(name){
return store[name] || (store[name] =
Symbol && Symbol[name] || (Symbol || uid)('Symbol.' + name));
};
},{"./$.global":63,"./$.shared":101,"./$.uid":116}],118:[function(require,module,exports){
var classof = require('./$.classof')
, ITERATOR = require('./$.wks')('iterator')
, Iterators = require('./$.iterators');
module.exports = require('./$.core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./$.classof":44,"./$.core":50,"./$.iterators":79,"./$.wks":117}],119:[function(require,module,exports){
'use strict';
var $ = require('./$')
, $export = require('./$.export')
, DESCRIPTORS = require('./$.descriptors')
, createDesc = require('./$.property-desc')
, html = require('./$.html')
, cel = require('./$.dom-create')
, has = require('./$.has')
, cof = require('./$.cof')
, invoke = require('./$.invoke')
, fails = require('./$.fails')
, anObject = require('./$.an-object')
, aFunction = require('./$.a-function')
, isObject = require('./$.is-object')
, toObject = require('./$.to-object')
, toIObject = require('./$.to-iobject')
, toInteger = require('./$.to-integer')
, toIndex = require('./$.to-index')
, toLength = require('./$.to-length')
, IObject = require('./$.iobject')
, IE_PROTO = require('./$.uid')('__proto__')
, createArrayMethod = require('./$.array-methods')
, arrayIndexOf = require('./$.array-includes')(false)
, ObjectProto = Object.prototype
, ArrayProto = Array.prototype
, arraySlice = ArrayProto.slice
, arrayJoin = ArrayProto.join
, defineProperty = $.setDesc
, getOwnDescriptor = $.getDesc
, defineProperties = $.setDescs
, factories = {}
, IE8_DOM_DEFINE;
if(!DESCRIPTORS){
IE8_DOM_DEFINE = !fails(function(){
return defineProperty(cel('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
$.setDesc = function(O, P, Attributes){
if(IE8_DOM_DEFINE)try {
return defineProperty(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)anObject(O)[P] = Attributes.value;
return O;
};
$.getDesc = function(O, P){
if(IE8_DOM_DEFINE)try {
return getOwnDescriptor(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]);
};
$.setDescs = defineProperties = function(O, Properties){
anObject(O);
var keys = $.getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)$.setDesc(O, P = keys[i++], Properties[P]);
return O;
};
}
$export($export.S + $export.F * !DESCRIPTORS, 'Object', {
// 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $.getDesc,
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
defineProperty: $.setDesc,
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
defineProperties: defineProperties
});
// IE 8- don't enum bug keys
var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' +
'toLocaleString,toString,valueOf').split(',')
// Additional keys for getOwnPropertyNames
, keys2 = keys1.concat('length', 'prototype')
, keysLen1 = keys1.length;
// Create object with `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = cel('iframe')
, i = keysLen1
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(' i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
};
var Empty = function(){};
$export($export.S, 'Object', {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
getPrototypeOf: $.getProto = $.getProto || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
},
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true),
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
create: $.create = $.create || function(O, /*?*/Properties){
var result;
if(O !== null){
Empty.prototype = anObject(O);
result = new Empty();
Empty.prototype = null;
// add "__proto__" for Object.getPrototypeOf shim
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : defineProperties(result, Properties);
},
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false)
});
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
}
return factories[len](F, args);
};
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
$export($export.P, 'Function', {
bind: function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
}
});
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * fails(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
$export($export.P + $export.F * (IObject != Object), 'Array', {
join: function join(separator){
return arrayJoin.call(IObject(this), separator === undefined ? ',' : separator);
}
});
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
$export($export.S, 'Array', {isArray: require('./$.is-array')});
var createArrayReduce = function(isRight){
return function(callbackfn, memo){
aFunction(callbackfn);
var O = IObject(this)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(arguments.length < 2)for(;;){
if(index in O){
memo = O[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in O){
memo = callbackfn(memo, O[index], index, this);
}
return memo;
};
};
var methodize = function($fn){
return function(arg1/*, arg2 = undefined */){
return $fn(this, arg1, arguments[1]);
};
};
$export($export.P, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: $.each = $.each || methodize(createArrayMethod(0)),
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: methodize(createArrayMethod(1)),
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: methodize(createArrayMethod(2)),
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: methodize(createArrayMethod(3)),
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: methodize(createArrayMethod(4)),
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: createArrayReduce(false),
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: createArrayReduce(true),
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: methodize(arrayIndexOf),
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function(el, fromIndex /* = @[*-1] */){
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(fromIndex));
if(index < 0)index = toLength(length + index);
for(;index >= 0; index--)if(index in O)if(O[index] === el)return index;
return -1;
}
});
// 20.3.3.1 / 15.9.4.4 Date.now()
$export($export.S, 'Date', {now: function(){ return +new Date; }});
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(this))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
},{"./$":80,"./$.a-function":36,"./$.an-object":38,"./$.array-includes":41,"./$.array-methods":42,"./$.cof":45,"./$.descriptors":53,"./$.dom-create":54,"./$.export":56,"./$.fails":58,"./$.has":64,"./$.html":66,"./$.invoke":67,"./$.iobject":68,"./$.is-array":70,"./$.is-object":72,"./$.property-desc":93,"./$.to-index":110,"./$.to-integer":111,"./$.to-iobject":112,"./$.to-length":113,"./$.to-object":114,"./$.uid":116}],120:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = require('./$.export');
$export($export.P, 'Array', {copyWithin: require('./$.array-copy-within')});
require('./$.add-to-unscopables')('copyWithin');
},{"./$.add-to-unscopables":37,"./$.array-copy-within":39,"./$.export":56}],121:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = require('./$.export');
$export($export.P, 'Array', {fill: require('./$.array-fill')});
require('./$.add-to-unscopables')('fill');
},{"./$.add-to-unscopables":37,"./$.array-fill":40,"./$.export":56}],122:[function(require,module,exports){
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = require('./$.export')
, $find = require('./$.array-methods')(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./$.add-to-unscopables')(KEY);
},{"./$.add-to-unscopables":37,"./$.array-methods":42,"./$.export":56}],123:[function(require,module,exports){
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = require('./$.export')
, $find = require('./$.array-methods')(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./$.add-to-unscopables')(KEY);
},{"./$.add-to-unscopables":37,"./$.array-methods":42,"./$.export":56}],124:[function(require,module,exports){
'use strict';
var ctx = require('./$.ctx')
, $export = require('./$.export')
, toObject = require('./$.to-object')
, call = require('./$.iter-call')
, isArrayIter = require('./$.is-array-iter')
, toLength = require('./$.to-length')
, getIterFn = require('./core.get-iterator-method');
$export($export.S + $export.F * !require('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, $$ = arguments
, $$len = $$.length
, mapfn = $$len > 1 ? $$[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value;
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
result[index] = mapping ? mapfn(O[index], index) : O[index];
}
}
result.length = index;
return result;
}
});
},{"./$.ctx":51,"./$.export":56,"./$.is-array-iter":69,"./$.iter-call":74,"./$.iter-detect":77,"./$.to-length":113,"./$.to-object":114,"./core.get-iterator-method":118}],125:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./$.add-to-unscopables')
, step = require('./$.iter-step')
, Iterators = require('./$.iterators')
, toIObject = require('./$.to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./$.iter-define')(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./$.add-to-unscopables":37,"./$.iter-define":76,"./$.iter-step":78,"./$.iterators":79,"./$.to-iobject":112}],126:[function(require,module,exports){
'use strict';
var $export = require('./$.export');
// WebKit Array.of isn't generic
$export($export.S + $export.F * require('./$.fails')(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, $$ = arguments
, $$len = $$.length
, result = new (typeof this == 'function' ? this : Array)($$len);
while($$len > index)result[index] = $$[index++];
result.length = $$len;
return result;
}
});
},{"./$.export":56,"./$.fails":58}],127:[function(require,module,exports){
require('./$.set-species')('Array');
},{"./$.set-species":99}],128:[function(require,module,exports){
'use strict';
var $ = require('./$')
, isObject = require('./$.is-object')
, HAS_INSTANCE = require('./$.wks')('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = $.getProto(O))if(this.prototype === O)return true;
return false;
}});
},{"./$":80,"./$.is-object":72,"./$.wks":117}],129:[function(require,module,exports){
var setDesc = require('./$').setDesc
, createDesc = require('./$.property-desc')
, has = require('./$.has')
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
// 19.2.4.2 name
NAME in FProto || require('./$.descriptors') && setDesc(FProto, NAME, {
configurable: true,
get: function(){
var match = ('' + this).match(nameRE)
, name = match ? match[1] : '';
has(this, NAME) || setDesc(this, NAME, createDesc(5, name));
return name;
}
});
},{"./$":80,"./$.descriptors":53,"./$.has":64,"./$.property-desc":93}],130:[function(require,module,exports){
'use strict';
var strong = require('./$.collection-strong');
// 23.1 Map Objects
require('./$.collection')('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
},{"./$.collection":49,"./$.collection-strong":46}],131:[function(require,module,exports){
// 20.2.2.3 Math.acosh(x)
var $export = require('./$.export')
, log1p = require('./$.math-log1p')
, sqrt = Math.sqrt
, $acosh = Math.acosh;
// V8 bug https://code.google.com/p/v8/issues/detail?id=3509
$export($export.S + $export.F * !($acosh && Math.floor($acosh(Number.MAX_VALUE)) == 710), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
},{"./$.export":56,"./$.math-log1p":84}],132:[function(require,module,exports){
// 20.2.2.5 Math.asinh(x)
var $export = require('./$.export');
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
$export($export.S, 'Math', {asinh: asinh});
},{"./$.export":56}],133:[function(require,module,exports){
// 20.2.2.7 Math.atanh(x)
var $export = require('./$.export');
$export($export.S, 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
},{"./$.export":56}],134:[function(require,module,exports){
// 20.2.2.9 Math.cbrt(x)
var $export = require('./$.export')
, sign = require('./$.math-sign');
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
},{"./$.export":56,"./$.math-sign":85}],135:[function(require,module,exports){
// 20.2.2.11 Math.clz32(x)
var $export = require('./$.export');
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
},{"./$.export":56}],136:[function(require,module,exports){
// 20.2.2.12 Math.cosh(x)
var $export = require('./$.export')
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
},{"./$.export":56}],137:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $export = require('./$.export');
$export($export.S, 'Math', {expm1: require('./$.math-expm1')});
},{"./$.export":56,"./$.math-expm1":83}],138:[function(require,module,exports){
// 20.2.2.16 Math.fround(x)
var $export = require('./$.export')
, sign = require('./$.math-sign')
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
},{"./$.export":56,"./$.math-sign":85}],139:[function(require,module,exports){
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = require('./$.export')
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, $$ = arguments
, $$len = $$.length
, larg = 0
, arg, div;
while(i < $$len){
arg = abs($$[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
},{"./$.export":56}],140:[function(require,module,exports){
// 20.2.2.18 Math.imul(x, y)
var $export = require('./$.export')
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * require('./$.fails')(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
},{"./$.export":56,"./$.fails":58}],141:[function(require,module,exports){
// 20.2.2.21 Math.log10(x)
var $export = require('./$.export');
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
},{"./$.export":56}],142:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
var $export = require('./$.export');
$export($export.S, 'Math', {log1p: require('./$.math-log1p')});
},{"./$.export":56,"./$.math-log1p":84}],143:[function(require,module,exports){
// 20.2.2.22 Math.log2(x)
var $export = require('./$.export');
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
},{"./$.export":56}],144:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
var $export = require('./$.export');
$export($export.S, 'Math', {sign: require('./$.math-sign')});
},{"./$.export":56,"./$.math-sign":85}],145:[function(require,module,exports){
// 20.2.2.30 Math.sinh(x)
var $export = require('./$.export')
, expm1 = require('./$.math-expm1')
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * require('./$.fails')(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
},{"./$.export":56,"./$.fails":58,"./$.math-expm1":83}],146:[function(require,module,exports){
// 20.2.2.33 Math.tanh(x)
var $export = require('./$.export')
, expm1 = require('./$.math-expm1')
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
},{"./$.export":56,"./$.math-expm1":83}],147:[function(require,module,exports){
// 20.2.2.34 Math.trunc(x)
var $export = require('./$.export');
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
},{"./$.export":56}],148:[function(require,module,exports){
'use strict';
var $ = require('./$')
, global = require('./$.global')
, has = require('./$.has')
, cof = require('./$.cof')
, toPrimitive = require('./$.to-primitive')
, fails = require('./$.fails')
, $trim = require('./$.string-trim').trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof($.create(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? new Base(toNumber(it)) : toNumber(it);
};
$.each.call(require('./$.descriptors') ? $.getNames(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), function(key){
if(has(Base, key) && !has($Number, key)){
$.setDesc($Number, key, $.getDesc(Base, key));
}
});
$Number.prototype = proto;
proto.constructor = $Number;
require('./$.redefine')(global, NUMBER, $Number);
}
},{"./$":80,"./$.cof":45,"./$.descriptors":53,"./$.fails":58,"./$.global":63,"./$.has":64,"./$.redefine":95,"./$.string-trim":108,"./$.to-primitive":115}],149:[function(require,module,exports){
// 20.1.2.1 Number.EPSILON
var $export = require('./$.export');
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
},{"./$.export":56}],150:[function(require,module,exports){
// 20.1.2.2 Number.isFinite(number)
var $export = require('./$.export')
, _isFinite = require('./$.global').isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
},{"./$.export":56,"./$.global":63}],151:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var $export = require('./$.export');
$export($export.S, 'Number', {isInteger: require('./$.is-integer')});
},{"./$.export":56,"./$.is-integer":71}],152:[function(require,module,exports){
// 20.1.2.4 Number.isNaN(number)
var $export = require('./$.export');
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
},{"./$.export":56}],153:[function(require,module,exports){
// 20.1.2.5 Number.isSafeInteger(number)
var $export = require('./$.export')
, isInteger = require('./$.is-integer')
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
},{"./$.export":56,"./$.is-integer":71}],154:[function(require,module,exports){
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = require('./$.export');
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
},{"./$.export":56}],155:[function(require,module,exports){
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = require('./$.export');
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
},{"./$.export":56}],156:[function(require,module,exports){
// 20.1.2.12 Number.parseFloat(string)
var $export = require('./$.export');
$export($export.S, 'Number', {parseFloat: parseFloat});
},{"./$.export":56}],157:[function(require,module,exports){
// 20.1.2.13 Number.parseInt(string, radix)
var $export = require('./$.export');
$export($export.S, 'Number', {parseInt: parseInt});
},{"./$.export":56}],158:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = require('./$.export');
$export($export.S + $export.F, 'Object', {assign: require('./$.object-assign')});
},{"./$.export":56,"./$.object-assign":87}],159:[function(require,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = require('./$.is-object');
require('./$.object-sap')('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(it) : it;
};
});
},{"./$.is-object":72,"./$.object-sap":88}],160:[function(require,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = require('./$.to-iobject');
require('./$.object-sap')('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"./$.object-sap":88,"./$.to-iobject":112}],161:[function(require,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
require('./$.object-sap')('getOwnPropertyNames', function(){
return require('./$.get-names').get;
});
},{"./$.get-names":62,"./$.object-sap":88}],162:[function(require,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = require('./$.to-object');
require('./$.object-sap')('getPrototypeOf', function($getPrototypeOf){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
},{"./$.object-sap":88,"./$.to-object":114}],163:[function(require,module,exports){
// 19.1.2.11 Object.isExtensible(O)
var isObject = require('./$.is-object');
require('./$.object-sap')('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
},{"./$.is-object":72,"./$.object-sap":88}],164:[function(require,module,exports){
// 19.1.2.12 Object.isFrozen(O)
var isObject = require('./$.is-object');
require('./$.object-sap')('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
},{"./$.is-object":72,"./$.object-sap":88}],165:[function(require,module,exports){
// 19.1.2.13 Object.isSealed(O)
var isObject = require('./$.is-object');
require('./$.object-sap')('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
},{"./$.is-object":72,"./$.object-sap":88}],166:[function(require,module,exports){
// 19.1.3.10 Object.is(value1, value2)
var $export = require('./$.export');
$export($export.S, 'Object', {is: require('./$.same-value')});
},{"./$.export":56,"./$.same-value":97}],167:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./$.to-object');
require('./$.object-sap')('keys', function($keys){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./$.object-sap":88,"./$.to-object":114}],168:[function(require,module,exports){
// 19.1.2.15 Object.preventExtensions(O)
var isObject = require('./$.is-object');
require('./$.object-sap')('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(it) : it;
};
});
},{"./$.is-object":72,"./$.object-sap":88}],169:[function(require,module,exports){
// 19.1.2.17 Object.seal(O)
var isObject = require('./$.is-object');
require('./$.object-sap')('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(it) : it;
};
});
},{"./$.is-object":72,"./$.object-sap":88}],170:[function(require,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = require('./$.export');
$export($export.S, 'Object', {setPrototypeOf: require('./$.set-proto').set});
},{"./$.export":56,"./$.set-proto":98}],171:[function(require,module,exports){
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = require('./$.classof')
, test = {};
test[require('./$.wks')('toStringTag')] = 'z';
if(test + '' != '[object z]'){
require('./$.redefine')(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
},{"./$.classof":44,"./$.redefine":95,"./$.wks":117}],172:[function(require,module,exports){
'use strict';
var $ = require('./$')
, LIBRARY = require('./$.library')
, global = require('./$.global')
, ctx = require('./$.ctx')
, classof = require('./$.classof')
, $export = require('./$.export')
, isObject = require('./$.is-object')
, anObject = require('./$.an-object')
, aFunction = require('./$.a-function')
, strictNew = require('./$.strict-new')
, forOf = require('./$.for-of')
, setProto = require('./$.set-proto').set
, same = require('./$.same-value')
, SPECIES = require('./$.wks')('species')
, speciesConstructor = require('./$.species-constructor')
, asap = require('./$.microtask')
, PROMISE = 'Promise'
, process = global.process
, isNode = classof(process) == 'process'
, P = global[PROMISE]
, Wrapper;
var testResolve = function(sub){
var test = new P(function(){});
if(sub)test.constructor = Object;
return P.resolve(test) === test;
};
var USE_NATIVE = function(){
var works = false;
function P2(x){
var self = new P(x);
setProto(self, P2.prototype);
return self;
}
try {
works = P && P.resolve && testResolve();
setProto(P2, P);
P2.prototype = $.create(P.prototype, {constructor: {value: P2}});
// actual Firefox has broken subclass support, test that
if(!(P2.resolve(5).then(function(){}) instanceof P2)){
works = false;
}
// actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162
if(works && require('./$.descriptors')){
var thenableThenGotten = false;
P.resolve($.setDesc({}, 'then', {
get: function(){ thenableThenGotten = true; }
}));
works = thenableThenGotten;
}
} catch(e){ works = false; }
return works;
}();
// helpers
var sameConstructor = function(a, b){
// library wrapper special case
if(LIBRARY && a === P && b === Wrapper)return true;
return same(a, b);
};
var getConstructor = function(C){
var S = anObject(C)[SPECIES];
return S != undefined ? S : C;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var PromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve),
this.reject = aFunction(reject)
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(record, isReject){
if(record.n)return;
record.n = true;
var chain = record.c;
asap(function(){
var value = record.v
, ok = record.s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, result, then;
try {
if(handler){
if(!ok)record.h = true;
result = handler === true ? value : handler(value);
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
chain.length = 0;
record.n = false;
if(isReject)setTimeout(function(){
var promise = record.p
, handler, console;
if(isUnhandled(promise)){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
} record.a = undefined;
}, 1);
});
};
var isUnhandled = function(promise){
var record = promise._d
, chain = record.a || record.c
, i = 0
, reaction;
if(record.h)return false;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var $reject = function(value){
var record = this;
if(record.d)return;
record.d = true;
record = record.r || record; // unwrap
record.v = value;
record.s = 2;
record.a = record.c.slice();
notify(record, true);
};
var $resolve = function(value){
var record = this
, then;
if(record.d)return;
record.d = true;
record = record.r || record; // unwrap
try {
if(record.p === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
asap(function(){
var wrapper = {r: record, d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
record.v = value;
record.s = 1;
notify(record, false);
}
} catch(e){
$reject.call({r: record, d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
P = function Promise(executor){
aFunction(executor);
var record = this._d = {
p: strictNew(this, P, PROMISE), // <- promise
c: [], // <- awaiting reactions
a: undefined, // <- checked in isUnhandled reactions
s: 0, // <- state
d: false, // <- done
v: undefined, // <- value
h: false, // <- handled rejection
n: false // <- notify
};
try {
executor(ctx($resolve, record, 1), ctx($reject, record, 1));
} catch(err){
$reject.call(record, err);
}
};
require('./$.redefine-all')(P.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = new PromiseCapability(speciesConstructor(this, P))
, promise = reaction.promise
, record = this._d;
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
record.c.push(reaction);
if(record.a)record.a.push(reaction);
if(record.s)notify(record, false);
return promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P});
require('./$.set-to-string-tag')(P, PROMISE);
require('./$.set-species')(PROMISE);
Wrapper = require('./$.core')[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = new PromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof P && sameConstructor(x.constructor, this))return x;
var capability = new PromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && require('./$.iter-detect')(function(iter){
P.all(iter)['catch'](function(){});
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = getConstructor(this)
, capability = new PromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject
, values = [];
var abrupt = perform(function(){
forOf(iterable, false, values.push, values);
var remaining = values.length
, results = Array(remaining);
if(remaining)$.each.call(values, function(promise, index){
var alreadyCalled = false;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
results[index] = value;
--remaining || resolve(results);
}, reject);
});
else resolve(results);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = getConstructor(this)
, capability = new PromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
},{"./$":80,"./$.a-function":36,"./$.an-object":38,"./$.classof":44,"./$.core":50,"./$.ctx":51,"./$.descriptors":53,"./$.export":56,"./$.for-of":61,"./$.global":63,"./$.is-object":72,"./$.iter-detect":77,"./$.library":82,"./$.microtask":86,"./$.redefine-all":94,"./$.same-value":97,"./$.set-proto":98,"./$.set-species":99,"./$.set-to-string-tag":100,"./$.species-constructor":102,"./$.strict-new":103,"./$.wks":117}],173:[function(require,module,exports){
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = require('./$.export')
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(target, thisArgument, argumentsList);
}
});
},{"./$.export":56}],174:[function(require,module,exports){
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $ = require('./$')
, $export = require('./$.export')
, aFunction = require('./$.a-function')
, anObject = require('./$.an-object')
, isObject = require('./$.is-object')
, bind = Function.bind || require('./$.core').Function.prototype.bind;
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * require('./$.fails')(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
if(args != undefined)switch(anObject(args).length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = $.create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
},{"./$":80,"./$.a-function":36,"./$.an-object":38,"./$.core":50,"./$.export":56,"./$.fails":58,"./$.is-object":72}],175:[function(require,module,exports){
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var $ = require('./$')
, $export = require('./$.export')
, anObject = require('./$.an-object');
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * require('./$.fails')(function(){
Reflect.defineProperty($.setDesc({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
try {
$.setDesc(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
},{"./$":80,"./$.an-object":38,"./$.export":56,"./$.fails":58}],176:[function(require,module,exports){
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = require('./$.export')
, getDesc = require('./$').getDesc
, anObject = require('./$.an-object');
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = getDesc(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
},{"./$":80,"./$.an-object":38,"./$.export":56}],177:[function(require,module,exports){
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = require('./$.export')
, anObject = require('./$.an-object');
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
require('./$.iter-create')(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
},{"./$.an-object":38,"./$.export":56,"./$.iter-create":75}],178:[function(require,module,exports){
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var $ = require('./$')
, $export = require('./$.export')
, anObject = require('./$.an-object');
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return $.getDesc(anObject(target), propertyKey);
}
});
},{"./$":80,"./$.an-object":38,"./$.export":56}],179:[function(require,module,exports){
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = require('./$.export')
, getProto = require('./$').getProto
, anObject = require('./$.an-object');
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
},{"./$":80,"./$.an-object":38,"./$.export":56}],180:[function(require,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var $ = require('./$')
, has = require('./$.has')
, $export = require('./$.export')
, isObject = require('./$.is-object')
, anObject = require('./$.an-object');
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = $.getDesc(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = $.getProto(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
},{"./$":80,"./$.an-object":38,"./$.export":56,"./$.has":64,"./$.is-object":72}],181:[function(require,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $export = require('./$.export');
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
},{"./$.export":56}],182:[function(require,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $export = require('./$.export')
, anObject = require('./$.an-object')
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
},{"./$.an-object":38,"./$.export":56}],183:[function(require,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $export = require('./$.export');
$export($export.S, 'Reflect', {ownKeys: require('./$.own-keys')});
},{"./$.export":56,"./$.own-keys":90}],184:[function(require,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $export = require('./$.export')
, anObject = require('./$.an-object')
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
},{"./$.an-object":38,"./$.export":56}],185:[function(require,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = require('./$.export')
, setProto = require('./$.set-proto');
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
},{"./$.export":56,"./$.set-proto":98}],186:[function(require,module,exports){
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var $ = require('./$')
, has = require('./$.has')
, $export = require('./$.export')
, createDesc = require('./$.property-desc')
, anObject = require('./$.an-object')
, isObject = require('./$.is-object');
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = $.getDesc(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = $.getProto(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = $.getDesc(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
$.setDesc(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
},{"./$":80,"./$.an-object":38,"./$.export":56,"./$.has":64,"./$.is-object":72,"./$.property-desc":93}],187:[function(require,module,exports){
var $ = require('./$')
, global = require('./$.global')
, isRegExp = require('./$.is-regexp')
, $flags = require('./$.flags')
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(require('./$.descriptors') && (!CORRECT_NEW || require('./$.fails')(function(){
re2[require('./$.wks')('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var piRE = isRegExp(p)
, fiU = f === undefined;
return !(this instanceof $RegExp) && piRE && p.constructor === $RegExp && fiU ? p
: CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f);
};
$.each.call($.getNames(Base), function(key){
key in $RegExp || $.setDesc($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
});
proto.constructor = $RegExp;
$RegExp.prototype = proto;
require('./$.redefine')(global, 'RegExp', $RegExp);
}
require('./$.set-species')('RegExp');
},{"./$":80,"./$.descriptors":53,"./$.fails":58,"./$.flags":60,"./$.global":63,"./$.is-regexp":73,"./$.redefine":95,"./$.set-species":99,"./$.wks":117}],188:[function(require,module,exports){
// 21.2.5.3 get RegExp.prototype.flags()
var $ = require('./$');
if(require('./$.descriptors') && /./g.flags != 'g')$.setDesc(RegExp.prototype, 'flags', {
configurable: true,
get: require('./$.flags')
});
},{"./$":80,"./$.descriptors":53,"./$.flags":60}],189:[function(require,module,exports){
// @@match logic
require('./$.fix-re-wks')('match', 1, function(defined, MATCH){
// 21.1.3.11 String.prototype.match(regexp)
return function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
};
});
},{"./$.fix-re-wks":59}],190:[function(require,module,exports){
// @@replace logic
require('./$.fix-re-wks')('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
};
});
},{"./$.fix-re-wks":59}],191:[function(require,module,exports){
// @@search logic
require('./$.fix-re-wks')('search', 1, function(defined, SEARCH){
// 21.1.3.15 String.prototype.search(regexp)
return function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
};
});
},{"./$.fix-re-wks":59}],192:[function(require,module,exports){
// @@split logic
require('./$.fix-re-wks')('split', 2, function(defined, SPLIT, $split){
// 21.1.3.17 String.prototype.split(separator, limit)
return function split(separator, limit){
'use strict';
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined
? fn.call(separator, O, limit)
: $split.call(String(O), separator, limit);
};
});
},{"./$.fix-re-wks":59}],193:[function(require,module,exports){
'use strict';
var strong = require('./$.collection-strong');
// 23.2 Set Objects
require('./$.collection')('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
},{"./$.collection":49,"./$.collection-strong":46}],194:[function(require,module,exports){
'use strict';
var $export = require('./$.export')
, $at = require('./$.string-at')(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
},{"./$.export":56,"./$.string-at":104}],195:[function(require,module,exports){
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = require('./$.export')
, toLength = require('./$.to-length')
, context = require('./$.string-context')
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * require('./$.fails-is-regexp')(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, $$ = arguments
, endPosition = $$.length > 1 ? $$[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
},{"./$.export":56,"./$.fails-is-regexp":57,"./$.string-context":105,"./$.to-length":113}],196:[function(require,module,exports){
var $export = require('./$.export')
, toIndex = require('./$.to-index')
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, $$ = arguments
, $$len = $$.length
, i = 0
, code;
while($$len > i){
code = +$$[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"./$.export":56,"./$.to-index":110}],197:[function(require,module,exports){
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = require('./$.export')
, context = require('./$.string-context')
, INCLUDES = 'includes';
$export($export.P + $export.F * require('./$.fails-is-regexp')(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"./$.export":56,"./$.fails-is-regexp":57,"./$.string-context":105}],198:[function(require,module,exports){
'use strict';
var $at = require('./$.string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./$.iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./$.iter-define":76,"./$.string-at":104}],199:[function(require,module,exports){
var $export = require('./$.export')
, toIObject = require('./$.to-iobject')
, toLength = require('./$.to-length');
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, $$ = arguments
, $$len = $$.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < $$len)res.push(String($$[i]));
} return res.join('');
}
});
},{"./$.export":56,"./$.to-iobject":112,"./$.to-length":113}],200:[function(require,module,exports){
var $export = require('./$.export');
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: require('./$.string-repeat')
});
},{"./$.export":56,"./$.string-repeat":107}],201:[function(require,module,exports){
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = require('./$.export')
, toLength = require('./$.to-length')
, context = require('./$.string-context')
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * require('./$.fails-is-regexp')(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, $$ = arguments
, index = toLength(Math.min($$.length > 1 ? $$[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
},{"./$.export":56,"./$.fails-is-regexp":57,"./$.string-context":105,"./$.to-length":113}],202:[function(require,module,exports){
'use strict';
// 21.1.3.25 String.prototype.trim()
require('./$.string-trim')('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
},{"./$.string-trim":108}],203:[function(require,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var $ = require('./$')
, global = require('./$.global')
, has = require('./$.has')
, DESCRIPTORS = require('./$.descriptors')
, $export = require('./$.export')
, redefine = require('./$.redefine')
, $fails = require('./$.fails')
, shared = require('./$.shared')
, setToStringTag = require('./$.set-to-string-tag')
, uid = require('./$.uid')
, wks = require('./$.wks')
, keyOf = require('./$.keyof')
, $names = require('./$.get-names')
, enumKeys = require('./$.enum-keys')
, isArray = require('./$.is-array')
, anObject = require('./$.an-object')
, toIObject = require('./$.to-iobject')
, createDesc = require('./$.property-desc')
, getDesc = $.getDesc
, setDesc = $.setDesc
, _create = $.create
, getNames = $names.get
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, setter = false
, HIDDEN = wks('_hidden')
, isEnum = $.isEnum
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, useNative = typeof $Symbol == 'function'
, ObjectProto = Object.prototype;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(setDesc({}, 'a', {
get: function(){ return setDesc(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = getDesc(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
setDesc(it, key, D);
if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc);
} : setDesc;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol.prototype);
sym._k = tag;
DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, {
configurable: true,
set: function(value){
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
}
});
return sym;
};
var isSymbol = function(it){
return typeof it == 'symbol';
};
var $defineProperty = function defineProperty(it, key, D){
if(D && has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))setDesc(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return setDesc(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key);
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key]
? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
var D = getDesc(it = toIObject(it), key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = getNames(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key);
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var names = getNames(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]);
return result;
};
var $stringify = function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, $$ = arguments
, replacer, $replacer;
while($$.length > i)args.push($$[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
};
var buggyJSON = $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
});
// 19.4.1.1 Symbol([description])
if(!useNative){
$Symbol = function Symbol(){
if(isSymbol(this))throw TypeError('Symbol is not a constructor');
return wrap(uid(arguments.length > 0 ? arguments[0] : undefined));
};
redefine($Symbol.prototype, 'toString', function toString(){
return this._k;
});
isSymbol = function(it){
return it instanceof $Symbol;
};
$.create = $create;
$.isEnum = $propertyIsEnumerable;
$.getDesc = $getOwnPropertyDescriptor;
$.setDesc = $defineProperty;
$.setDescs = $defineProperties;
$.getNames = $names.get = $getOwnPropertyNames;
$.getSymbols = $getOwnPropertySymbols;
if(DESCRIPTORS && !require('./$.library')){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
}
var symbolStatics = {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
return keyOf(SymbolRegistry, key);
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
};
// 19.4.2.2 Symbol.hasInstance
// 19.4.2.3 Symbol.isConcatSpreadable
// 19.4.2.4 Symbol.iterator
// 19.4.2.6 Symbol.match
// 19.4.2.8 Symbol.replace
// 19.4.2.9 Symbol.search
// 19.4.2.10 Symbol.species
// 19.4.2.11 Symbol.split
// 19.4.2.12 Symbol.toPrimitive
// 19.4.2.13 Symbol.toStringTag
// 19.4.2.14 Symbol.unscopables
$.each.call((
'hasInstance,isConcatSpreadable,iterator,match,replace,search,' +
'species,split,toPrimitive,toStringTag,unscopables'
).split(','), function(it){
var sym = wks(it);
symbolStatics[it] = useNative ? sym : wrap(sym);
});
setter = true;
$export($export.G + $export.W, {Symbol: $Symbol});
$export($export.S, 'Symbol', symbolStatics);
$export($export.S + $export.F * !useNative, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!useNative || buggyJSON), 'JSON', {stringify: $stringify});
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"./$":80,"./$.an-object":38,"./$.descriptors":53,"./$.enum-keys":55,"./$.export":56,"./$.fails":58,"./$.get-names":62,"./$.global":63,"./$.has":64,"./$.is-array":70,"./$.keyof":81,"./$.library":82,"./$.property-desc":93,"./$.redefine":95,"./$.set-to-string-tag":100,"./$.shared":101,"./$.to-iobject":112,"./$.uid":116,"./$.wks":117}],204:[function(require,module,exports){
'use strict';
var $ = require('./$')
, redefine = require('./$.redefine')
, weak = require('./$.collection-weak')
, isObject = require('./$.is-object')
, has = require('./$.has')
, frozenStore = weak.frozenStore
, WEAK = weak.WEAK
, isExtensible = Object.isExtensible || isObject
, tmp = {};
// 23.3 WeakMap Objects
var $WeakMap = require('./$.collection')('WeakMap', function(get){
return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
if(!isExtensible(key))return frozenStore(this).get(key);
if(has(key, WEAK))return key[WEAK][this._i];
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
}, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
$.each.call(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on leaky map
if(isObject(a) && !isExtensible(a)){
var result = frozenStore(this)[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"./$":80,"./$.collection":49,"./$.collection-weak":48,"./$.has":64,"./$.is-object":72,"./$.redefine":95}],205:[function(require,module,exports){
'use strict';
var weak = require('./$.collection-weak');
// 23.4 WeakSet Objects
require('./$.collection')('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
},{"./$.collection":49,"./$.collection-weak":48}],206:[function(require,module,exports){
'use strict';
var $export = require('./$.export')
, $includes = require('./$.array-includes')(true);
$export($export.P, 'Array', {
// https://github.com/domenic/Array.prototype.includes
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./$.add-to-unscopables')('includes');
},{"./$.add-to-unscopables":37,"./$.array-includes":41,"./$.export":56}],207:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./$.export');
$export($export.P, 'Map', {toJSON: require('./$.collection-to-json')('Map')});
},{"./$.collection-to-json":47,"./$.export":56}],208:[function(require,module,exports){
// http://goo.gl/XkBrjD
var $export = require('./$.export')
, $entries = require('./$.object-to-array')(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
},{"./$.export":56,"./$.object-to-array":89}],209:[function(require,module,exports){
// https://gist.github.com/WebReflection/9353781
var $ = require('./$')
, $export = require('./$.export')
, ownKeys = require('./$.own-keys')
, toIObject = require('./$.to-iobject')
, createDesc = require('./$.property-desc');
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, setDesc = $.setDesc
, getDesc = $.getDesc
, keys = ownKeys(O)
, result = {}
, i = 0
, key, D;
while(keys.length > i){
D = getDesc(O, key = keys[i++]);
if(key in result)setDesc(result, key, createDesc(0, D));
else result[key] = D;
} return result;
}
});
},{"./$":80,"./$.export":56,"./$.own-keys":90,"./$.property-desc":93,"./$.to-iobject":112}],210:[function(require,module,exports){
// http://goo.gl/XkBrjD
var $export = require('./$.export')
, $values = require('./$.object-to-array')(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
},{"./$.export":56,"./$.object-to-array":89}],211:[function(require,module,exports){
// https://github.com/benjamingr/RexExp.escape
var $export = require('./$.export')
, $re = require('./$.replacer')(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
},{"./$.export":56,"./$.replacer":96}],212:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./$.export');
$export($export.P, 'Set', {toJSON: require('./$.collection-to-json')('Set')});
},{"./$.collection-to-json":47,"./$.export":56}],213:[function(require,module,exports){
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = require('./$.export')
, $at = require('./$.string-at')(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
},{"./$.export":56,"./$.string-at":104}],214:[function(require,module,exports){
'use strict';
var $export = require('./$.export')
, $pad = require('./$.string-pad');
$export($export.P, 'String', {
padLeft: function padLeft(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
},{"./$.export":56,"./$.string-pad":106}],215:[function(require,module,exports){
'use strict';
var $export = require('./$.export')
, $pad = require('./$.string-pad');
$export($export.P, 'String', {
padRight: function padRight(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
},{"./$.export":56,"./$.string-pad":106}],216:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./$.string-trim')('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
});
},{"./$.string-trim":108}],217:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./$.string-trim')('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
});
},{"./$.string-trim":108}],218:[function(require,module,exports){
// JavaScript 1.6 / Strawman array statics shim
var $ = require('./$')
, $export = require('./$.export')
, $ctx = require('./$.ctx')
, $Array = require('./$.core').Array || Array
, statics = {};
var setStatics = function(keys, length){
$.each.call(keys.split(','), function(key){
if(length == undefined && key in $Array)statics[key] = $Array[key];
else if(key in [])statics[key] = $ctx(Function.call, [][key], length);
});
};
setStatics('pop,reverse,shift,keys,values,entries', 1);
setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3);
setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' +
'reduce,reduceRight,copyWithin,fill');
$export($export.S, 'Array', statics);
},{"./$":80,"./$.core":50,"./$.ctx":51,"./$.export":56}],219:[function(require,module,exports){
require('./es6.array.iterator');
var global = require('./$.global')
, hide = require('./$.hide')
, Iterators = require('./$.iterators')
, ITERATOR = require('./$.wks')('iterator')
, NL = global.NodeList
, HTC = global.HTMLCollection
, NLProto = NL && NL.prototype
, HTCProto = HTC && HTC.prototype
, ArrayValues = Iterators.NodeList = Iterators.HTMLCollection = Iterators.Array;
if(NLProto && !NLProto[ITERATOR])hide(NLProto, ITERATOR, ArrayValues);
if(HTCProto && !HTCProto[ITERATOR])hide(HTCProto, ITERATOR, ArrayValues);
},{"./$.global":63,"./$.hide":65,"./$.iterators":79,"./$.wks":117,"./es6.array.iterator":125}],220:[function(require,module,exports){
var $export = require('./$.export')
, $task = require('./$.task');
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"./$.export":56,"./$.task":109}],221:[function(require,module,exports){
// ie9- setTimeout & setInterval additional parameters fix
var global = require('./$.global')
, $export = require('./$.export')
, invoke = require('./$.invoke')
, partial = require('./$.partial')
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
},{"./$.export":56,"./$.global":63,"./$.invoke":67,"./$.partial":91}],222:[function(require,module,exports){
require('./modules/es5');
require('./modules/es6.symbol');
require('./modules/es6.object.assign');
require('./modules/es6.object.is');
require('./modules/es6.object.set-prototype-of');
require('./modules/es6.object.to-string');
require('./modules/es6.object.freeze');
require('./modules/es6.object.seal');
require('./modules/es6.object.prevent-extensions');
require('./modules/es6.object.is-frozen');
require('./modules/es6.object.is-sealed');
require('./modules/es6.object.is-extensible');
require('./modules/es6.object.get-own-property-descriptor');
require('./modules/es6.object.get-prototype-of');
require('./modules/es6.object.keys');
require('./modules/es6.object.get-own-property-names');
require('./modules/es6.function.name');
require('./modules/es6.function.has-instance');
require('./modules/es6.number.constructor');
require('./modules/es6.number.epsilon');
require('./modules/es6.number.is-finite');
require('./modules/es6.number.is-integer');
require('./modules/es6.number.is-nan');
require('./modules/es6.number.is-safe-integer');
require('./modules/es6.number.max-safe-integer');
require('./modules/es6.number.min-safe-integer');
require('./modules/es6.number.parse-float');
require('./modules/es6.number.parse-int');
require('./modules/es6.math.acosh');
require('./modules/es6.math.asinh');
require('./modules/es6.math.atanh');
require('./modules/es6.math.cbrt');
require('./modules/es6.math.clz32');
require('./modules/es6.math.cosh');
require('./modules/es6.math.expm1');
require('./modules/es6.math.fround');
require('./modules/es6.math.hypot');
require('./modules/es6.math.imul');
require('./modules/es6.math.log10');
require('./modules/es6.math.log1p');
require('./modules/es6.math.log2');
require('./modules/es6.math.sign');
require('./modules/es6.math.sinh');
require('./modules/es6.math.tanh');
require('./modules/es6.math.trunc');
require('./modules/es6.string.from-code-point');
require('./modules/es6.string.raw');
require('./modules/es6.string.trim');
require('./modules/es6.string.iterator');
require('./modules/es6.string.code-point-at');
require('./modules/es6.string.ends-with');
require('./modules/es6.string.includes');
require('./modules/es6.string.repeat');
require('./modules/es6.string.starts-with');
require('./modules/es6.array.from');
require('./modules/es6.array.of');
require('./modules/es6.array.iterator');
require('./modules/es6.array.species');
require('./modules/es6.array.copy-within');
require('./modules/es6.array.fill');
require('./modules/es6.array.find');
require('./modules/es6.array.find-index');
require('./modules/es6.regexp.constructor');
require('./modules/es6.regexp.flags');
require('./modules/es6.regexp.match');
require('./modules/es6.regexp.replace');
require('./modules/es6.regexp.search');
require('./modules/es6.regexp.split');
require('./modules/es6.promise');
require('./modules/es6.map');
require('./modules/es6.set');
require('./modules/es6.weak-map');
require('./modules/es6.weak-set');
require('./modules/es6.reflect.apply');
require('./modules/es6.reflect.construct');
require('./modules/es6.reflect.define-property');
require('./modules/es6.reflect.delete-property');
require('./modules/es6.reflect.enumerate');
require('./modules/es6.reflect.get');
require('./modules/es6.reflect.get-own-property-descriptor');
require('./modules/es6.reflect.get-prototype-of');
require('./modules/es6.reflect.has');
require('./modules/es6.reflect.is-extensible');
require('./modules/es6.reflect.own-keys');
require('./modules/es6.reflect.prevent-extensions');
require('./modules/es6.reflect.set');
require('./modules/es6.reflect.set-prototype-of');
require('./modules/es7.array.includes');
require('./modules/es7.string.at');
require('./modules/es7.string.pad-left');
require('./modules/es7.string.pad-right');
require('./modules/es7.string.trim-left');
require('./modules/es7.string.trim-right');
require('./modules/es7.regexp.escape');
require('./modules/es7.object.get-own-property-descriptors');
require('./modules/es7.object.values');
require('./modules/es7.object.entries');
require('./modules/es7.map.to-json');
require('./modules/es7.set.to-json');
require('./modules/js.array.statics');
require('./modules/web.timers');
require('./modules/web.immediate');
require('./modules/web.dom.iterable');
module.exports = require('./modules/$.core');
},{"./modules/$.core":50,"./modules/es5":119,"./modules/es6.array.copy-within":120,"./modules/es6.array.fill":121,"./modules/es6.array.find":123,"./modules/es6.array.find-index":122,"./modules/es6.array.from":124,"./modules/es6.array.iterator":125,"./modules/es6.array.of":126,"./modules/es6.array.species":127,"./modules/es6.function.has-instance":128,"./modules/es6.function.name":129,"./modules/es6.map":130,"./modules/es6.math.acosh":131,"./modules/es6.math.asinh":132,"./modules/es6.math.atanh":133,"./modules/es6.math.cbrt":134,"./modules/es6.math.clz32":135,"./modules/es6.math.cosh":136,"./modules/es6.math.expm1":137,"./modules/es6.math.fround":138,"./modules/es6.math.hypot":139,"./modules/es6.math.imul":140,"./modules/es6.math.log10":141,"./modules/es6.math.log1p":142,"./modules/es6.math.log2":143,"./modules/es6.math.sign":144,"./modules/es6.math.sinh":145,"./modules/es6.math.tanh":146,"./modules/es6.math.trunc":147,"./modules/es6.number.constructor":148,"./modules/es6.number.epsilon":149,"./modules/es6.number.is-finite":150,"./modules/es6.number.is-integer":151,"./modules/es6.number.is-nan":152,"./modules/es6.number.is-safe-integer":153,"./modules/es6.number.max-safe-integer":154,"./modules/es6.number.min-safe-integer":155,"./modules/es6.number.parse-float":156,"./modules/es6.number.parse-int":157,"./modules/es6.object.assign":158,"./modules/es6.object.freeze":159,"./modules/es6.object.get-own-property-descriptor":160,"./modules/es6.object.get-own-property-names":161,"./modules/es6.object.get-prototype-of":162,"./modules/es6.object.is":166,"./modules/es6.object.is-extensible":163,"./modules/es6.object.is-frozen":164,"./modules/es6.object.is-sealed":165,"./modules/es6.object.keys":167,"./modules/es6.object.prevent-extensions":168,"./modules/es6.object.seal":169,"./modules/es6.object.set-prototype-of":170,"./modules/es6.object.to-string":171,"./modules/es6.promise":172,"./modules/es6.reflect.apply":173,"./modules/es6.reflect.construct":174,"./modules/es6.reflect.define-property":175,"./modules/es6.reflect.delete-property":176,"./modules/es6.reflect.enumerate":177,"./modules/es6.reflect.get":180,"./modules/es6.reflect.get-own-property-descriptor":178,"./modules/es6.reflect.get-prototype-of":179,"./modules/es6.reflect.has":181,"./modules/es6.reflect.is-extensible":182,"./modules/es6.reflect.own-keys":183,"./modules/es6.reflect.prevent-extensions":184,"./modules/es6.reflect.set":186,"./modules/es6.reflect.set-prototype-of":185,"./modules/es6.regexp.constructor":187,"./modules/es6.regexp.flags":188,"./modules/es6.regexp.match":189,"./modules/es6.regexp.replace":190,"./modules/es6.regexp.search":191,"./modules/es6.regexp.split":192,"./modules/es6.set":193,"./modules/es6.string.code-point-at":194,"./modules/es6.string.ends-with":195,"./modules/es6.string.from-code-point":196,"./modules/es6.string.includes":197,"./modules/es6.string.iterator":198,"./modules/es6.string.raw":199,"./modules/es6.string.repeat":200,"./modules/es6.string.starts-with":201,"./modules/es6.string.trim":202,"./modules/es6.symbol":203,"./modules/es6.weak-map":204,"./modules/es6.weak-set":205,"./modules/es7.array.includes":206,"./modules/es7.map.to-json":207,"./modules/es7.object.entries":208,"./modules/es7.object.get-own-property-descriptors":209,"./modules/es7.object.values":210,"./modules/es7.regexp.escape":211,"./modules/es7.set.to-json":212,"./modules/es7.string.at":213,"./modules/es7.string.pad-left":214,"./modules/es7.string.pad-right":215,"./modules/es7.string.trim-left":216,"./modules/es7.string.trim-right":217,"./modules/js.array.statics":218,"./modules/web.dom.iterable":219,"./modules/web.immediate":220,"./modules/web.timers":221}],223:[function(require,module,exports){
(function (process,global){
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
!(function(global) {
"use strict";
var hasOwn = Object.prototype.hasOwnProperty;
var undefined; // More compressible than void 0.
var iteratorSymbol =
typeof Symbol === "function" && Symbol.iterator || "@@iterator";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided, then outerFn.prototype instanceof Generator.
var generator = Object.create((outerFn || Generator).prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype;
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `value instanceof AwaitArgument` to determine if the yielded value is
// meant to be awaited. Some may consider the name of this method too
// cutesy, but they are curmudgeons.
runtime.awrap = function(arg) {
return new AwaitArgument(arg);
};
function AwaitArgument(arg) {
this.arg = arg;
}
function AsyncIterator(generator) {
// This invoke function is written in a style that assumes some
// calling function (or Promise) will handle exceptions.
function invoke(method, arg) {
var result = generator[method](arg);
var value = result.value;
return value instanceof AwaitArgument
? Promise.resolve(value.arg).then(invokeNext, invokeThrow)
: Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
return result;
});
}
if (typeof process === "object" && process.domain) {
invoke = process.domain.bind(invoke);
}
var invokeNext = invoke.bind(generator, "next");
var invokeThrow = invoke.bind(generator, "throw");
var invokeReturn = invoke.bind(generator, "return");
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return invoke(method, arg);
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : new Promise(function (resolve) {
resolve(callInvokeWithMethodAndArg());
});
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
while (true) {
var delegate = context.delegate;
if (delegate) {
if (method === "return" ||
(method === "throw" && delegate.iterator[method] === undefined)) {
// A return or throw (when the delegate iterator has no throw
// method) always terminates the yield* loop.
context.delegate = null;
// If the delegate iterator has a return method, give it a
// chance to clean up.
var returnMethod = delegate.iterator["return"];
if (returnMethod) {
var record = tryCatch(returnMethod, delegate.iterator, arg);
if (record.type === "throw") {
// If the return method threw an exception, let that
// exception prevail over the original return or throw.
method = "throw";
arg = record.arg;
continue;
}
}
if (method === "return") {
// Continue with the outer return, now that the delegate
// iterator has been terminated.
continue;
}
}
var record = tryCatch(
delegate.iterator[method],
delegate.iterator,
arg
);
if (record.type === "throw") {
context.delegate = null;
// Like returning generator.throw(uncaught), but without the
// overhead of an extra function call.
method = "throw";
arg = record.arg;
continue;
}
// Delegate generator ran and handled its own exceptions so
// regardless of what the method was, we continue as if it is
// "next" with an undefined arg.
method = "next";
arg = undefined;
var info = record.arg;
if (info.done) {
context[delegate.resultName] = info.value;
context.next = delegate.nextLoc;
} else {
state = GenStateSuspendedYield;
return info;
}
context.delegate = null;
}
if (method === "next") {
if (state === GenStateSuspendedYield) {
context.sent = arg;
} else {
context.sent = undefined;
}
} else if (method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw arg;
}
if (context.dispatchException(arg)) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
method = "next";
arg = undefined;
}
} else if (method === "return") {
context.abrupt("return", arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
var info = {
value: record.arg,
done: context.done
};
if (record.arg === ContinueSentinel) {
if (context.delegate && method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
arg = undefined;
}
} else {
return info;
}
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(arg) call above.
method = "throw";
arg = record.arg;
}
}
};
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
this.sent = undefined;
this.done = false;
this.delegate = null;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.next = finallyEntry.finallyLoc;
} else {
this.complete(record);
}
return ContinueSentinel;
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = record.arg;
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
return ContinueSentinel;
}
};
})(
// Among the various tricks for obtaining a reference to the global
// object, this seems to be the most reliable technique that does not
// use indirect eval (which violates Content Security Policy).
typeof global === "object" ? global :
typeof window === "object" ? window :
typeof self === "object" ? self : this
);
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":241}],224:[function(require,module,exports){
module.exports = require("./lib/polyfill");
},{"./lib/polyfill":35}],225:[function(require,module,exports){
module.exports = require("babel-core/polyfill");
},{"babel-core/polyfill":224}],226:[function(require,module,exports){
},{}],227:[function(require,module,exports){
arguments[4][226][0].apply(exports,arguments)
},{"dup":226}],228:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
* on objects.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
function typedArraySupport () {
function Bar () {}
try {
var arr = new Uint8Array(1)
arr.foo = function () { return 42 }
arr.constructor = Bar
return arr.foo() === 42 && // typed array instances can be augmented
arr.constructor === Bar && // constructor can be set
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (arg) {
if (!(this instanceof Buffer)) {
// Avoid going through an ArgumentsAdaptorTrampoline in the common case.
if (arguments.length > 1) return new Buffer(arg, arguments[1])
return new Buffer(arg)
}
this.length = 0
this.parent = undefined
// Common case.
if (typeof arg === 'number') {
return fromNumber(this, arg)
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
}
// Unusual.
return fromObject(this, arg)
}
function fromNumber (that, length) {
that = allocate(that, length < 0 ? 0 : checked(length) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < length; i++) {
that[i] = 0
}
}
return that
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
// Assumption: byteLength() return value is always < kMaxLength.
var length = byteLength(string, encoding) | 0
that = allocate(that, length)
that.write(string, encoding)
return that
}
function fromObject (that, object) {
if (Buffer.isBuffer(object)) return fromBuffer(that, object)
if (isArray(object)) return fromArray(that, object)
if (object == null) {
throw new TypeError('must start with number, buffer, array or string')
}
if (typeof ArrayBuffer !== 'undefined') {
if (object.buffer instanceof ArrayBuffer) {
return fromTypedArray(that, object)
}
if (object instanceof ArrayBuffer) {
return fromArrayBuffer(that, object)
}
}
if (object.length) return fromArrayLike(that, object)
return fromJsonObject(that, object)
}
function fromBuffer (that, buffer) {
var length = checked(buffer.length) | 0
that = allocate(that, length)
buffer.copy(that, 0, 0, length)
return that
}
function fromArray (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
// Duplicate of fromArray() to keep fromArray() monomorphic.
function fromTypedArray (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
// Truncating the elements is probably not what people expect from typed
// arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
// of the old Buffer constructor.
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array) {
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
array.byteLength
that = Buffer._augment(new Uint8Array(array))
} else {
// Fallback: Return an object instance of the Buffer class
that = fromTypedArray(that, new Uint8Array(array))
}
return that
}
function fromArrayLike (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
// Returns a zero-length buffer for inputs that don't conform to the spec.
function fromJsonObject (that, object) {
var array
var length = 0
if (object.type === 'Buffer' && isArray(object.data)) {
array = object.data
length = checked(array.length) | 0
}
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
}
function allocate (that, length) {
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = Buffer._augment(new Uint8Array(length))
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that.length = length
that._isBuffer = true
}
var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
if (fromPool) that.parent = rootParent
return that
}
function checked (length) {
// Note: cannot use `length < kMaxLength` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
var i = 0
var len = Math.min(x, y)
while (i < len) {
if (a[i] !== b[i]) break
++i
}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; i++) {
length += list[i].length
}
}
var buf = new Buffer(length)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
function byteLength (string, encoding) {
if (typeof string !== 'string') string = '' + string
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'binary':
// Deprecated
case 'raw':
case 'raws':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
function slowToString (encoding, start, end) {
var loweredCase = false
start = start | 0
end = end === undefined || end === Infinity ? this.length : end | 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return ''
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` is deprecated
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` is deprecated
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
var swap = encoding
encoding = offset
offset = length | 0
length = swap
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'binary':
return binaryWrite(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; i--) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; i++) {
target[i + targetStart] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), targetStart)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"base64-js":229,"ieee754":230,"isarray":231}],229:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],230:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],231:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],232:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],233:[function(require,module,exports){
var http = module.exports;
var EventEmitter = require('events').EventEmitter;
var Request = require('./lib/request');
var url = require('url')
http.request = function (params, cb) {
if (typeof params === 'string') {
params = url.parse(params)
}
if (!params) params = {};
if (!params.host && !params.port) {
params.port = parseInt(window.location.port, 10);
}
if (!params.host && params.hostname) {
params.host = params.hostname;
}
if (!params.protocol) {
if (params.scheme) {
params.protocol = params.scheme + ':';
} else {
params.protocol = window.location.protocol;
}
}
if (!params.host) {
params.host = window.location.hostname || window.location.host;
}
if (/:/.test(params.host)) {
if (!params.port) {
params.port = params.host.split(':')[1];
}
params.host = params.host.split(':')[0];
}
if (!params.port) params.port = params.protocol == 'https:' ? 443 : 80;
var req = new Request(new xhrHttp, params);
if (cb) req.on('response', cb);
return req;
};
http.get = function (params, cb) {
params.method = 'GET';
var req = http.request(params, cb);
req.end();
return req;
};
http.Agent = function () {};
http.Agent.defaultMaxSockets = 4;
var xhrHttp = (function () {
if (typeof window === 'undefined') {
throw new Error('no window object present');
}
else if (window.XMLHttpRequest) {
return window.XMLHttpRequest;
}
else if (window.ActiveXObject) {
var axs = [
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.3.0',
'Microsoft.XMLHTTP'
];
for (var i = 0; i < axs.length; i++) {
try {
var ax = new(window.ActiveXObject)(axs[i]);
return function () {
if (ax) {
var ax_ = ax;
ax = null;
return ax_;
}
else {
return new(window.ActiveXObject)(axs[i]);
}
};
}
catch (e) {}
}
throw new Error('ajax not supported in this browser')
}
else {
throw new Error('ajax not supported in this browser');
}
})();
http.STATUS_CODES = {
100 : 'Continue',
101 : 'Switching Protocols',
102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
200 : 'OK',
201 : 'Created',
202 : 'Accepted',
203 : 'Non-Authoritative Information',
204 : 'No Content',
205 : 'Reset Content',
206 : 'Partial Content',
207 : 'Multi-Status', // RFC 4918
300 : 'Multiple Choices',
301 : 'Moved Permanently',
302 : 'Moved Temporarily',
303 : 'See Other',
304 : 'Not Modified',
305 : 'Use Proxy',
307 : 'Temporary Redirect',
400 : 'Bad Request',
401 : 'Unauthorized',
402 : 'Payment Required',
403 : 'Forbidden',
404 : 'Not Found',
405 : 'Method Not Allowed',
406 : 'Not Acceptable',
407 : 'Proxy Authentication Required',
408 : 'Request Time-out',
409 : 'Conflict',
410 : 'Gone',
411 : 'Length Required',
412 : 'Precondition Failed',
413 : 'Request Entity Too Large',
414 : 'Request-URI Too Large',
415 : 'Unsupported Media Type',
416 : 'Requested Range Not Satisfiable',
417 : 'Expectation Failed',
418 : 'I\'m a teapot', // RFC 2324
422 : 'Unprocessable Entity', // RFC 4918
423 : 'Locked', // RFC 4918
424 : 'Failed Dependency', // RFC 4918
425 : 'Unordered Collection', // RFC 4918
426 : 'Upgrade Required', // RFC 2817
428 : 'Precondition Required', // RFC 6585
429 : 'Too Many Requests', // RFC 6585
431 : 'Request Header Fields Too Large',// RFC 6585
500 : 'Internal Server Error',
501 : 'Not Implemented',
502 : 'Bad Gateway',
503 : 'Service Unavailable',
504 : 'Gateway Time-out',
505 : 'HTTP Version Not Supported',
506 : 'Variant Also Negotiates', // RFC 2295
507 : 'Insufficient Storage', // RFC 4918
509 : 'Bandwidth Limit Exceeded',
510 : 'Not Extended', // RFC 2774
511 : 'Network Authentication Required' // RFC 6585
};
},{"./lib/request":234,"events":232,"url":259}],234:[function(require,module,exports){
var Stream = require('stream');
var Response = require('./response');
var Base64 = require('Base64');
var inherits = require('inherits');
var Request = module.exports = function (xhr, params) {
var self = this;
self.writable = true;
self.xhr = xhr;
self.body = [];
self.uri = (params.protocol || 'http:') + '//'
+ params.host
+ (params.port ? ':' + params.port : '')
+ (params.path || '/')
;
if (typeof params.withCredentials === 'undefined') {
params.withCredentials = true;
}
try { xhr.withCredentials = params.withCredentials }
catch (e) {}
if (params.responseType) try { xhr.responseType = params.responseType }
catch (e) {}
xhr.open(
params.method || 'GET',
self.uri,
true
);
xhr.onerror = function(event) {
self.emit('error', new Error('Network error'));
};
self._headers = {};
if (params.headers) {
var keys = objectKeys(params.headers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!self.isSafeRequestHeader(key)) continue;
var value = params.headers[key];
self.setHeader(key, value);
}
}
if (params.auth) {
//basic auth
this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth));
}
var res = new Response;
res.on('close', function () {
self.emit('close');
});
res.on('ready', function () {
self.emit('response', res);
});
res.on('error', function (err) {
self.emit('error', err);
});
xhr.onreadystatechange = function () {
// Fix for IE9 bug
// SCRIPT575: Could not complete the operation due to error c00c023f
// It happens when a request is aborted, calling the success callback anyway with readyState === 4
if (xhr.__aborted) return;
res.handle(xhr);
};
};
inherits(Request, Stream);
Request.prototype.setHeader = function (key, value) {
this._headers[key.toLowerCase()] = value
};
Request.prototype.getHeader = function (key) {
return this._headers[key.toLowerCase()]
};
Request.prototype.removeHeader = function (key) {
delete this._headers[key.toLowerCase()]
};
Request.prototype.write = function (s) {
this.body.push(s);
};
Request.prototype.destroy = function (s) {
this.xhr.__aborted = true;
this.xhr.abort();
this.emit('close');
};
Request.prototype.end = function (s) {
if (s !== undefined) this.body.push(s);
var keys = objectKeys(this._headers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = this._headers[key];
if (isArray(value)) {
for (var j = 0; j < value.length; j++) {
this.xhr.setRequestHeader(key, value[j]);
}
}
else this.xhr.setRequestHeader(key, value)
}
if (this.body.length === 0) {
this.xhr.send('');
}
else if (typeof this.body[0] === 'string') {
this.xhr.send(this.body.join(''));
}
else if (isArray(this.body[0])) {
var body = [];
for (var i = 0; i < this.body.length; i++) {
body.push.apply(body, this.body[i]);
}
this.xhr.send(body);
}
else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) {
var len = 0;
for (var i = 0; i < this.body.length; i++) {
len += this.body[i].length;
}
var body = new(this.body[0].constructor)(len);
var k = 0;
for (var i = 0; i < this.body.length; i++) {
var b = this.body[i];
for (var j = 0; j < b.length; j++) {
body[k++] = b[j];
}
}
this.xhr.send(body);
}
else if (isXHR2Compatible(this.body[0])) {
this.xhr.send(this.body[0]);
}
else {
var body = '';
for (var i = 0; i < this.body.length; i++) {
body += this.body[i].toString();
}
this.xhr.send(body);
}
};
// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
Request.unsafeHeaders = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"content-transfer-encoding",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
"via"
];
Request.prototype.isSafeRequestHeader = function (headerName) {
if (!headerName) return false;
return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1;
};
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
var indexOf = function (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0; i < xs.length; i++) {
if (xs[i] === x) return i;
}
return -1;
};
var isXHR2Compatible = function (obj) {
if (typeof Blob !== 'undefined' && obj instanceof Blob) return true;
if (typeof ArrayBuffer !== 'undefined' && obj instanceof ArrayBuffer) return true;
if (typeof FormData !== 'undefined' && obj instanceof FormData) return true;
};
},{"./response":235,"Base64":236,"inherits":238,"stream":257}],235:[function(require,module,exports){
var Stream = require('stream');
var util = require('util');
var Response = module.exports = function (res) {
this.offset = 0;
this.readable = true;
};
util.inherits(Response, Stream);
var capable = {
streaming : true,
status2 : true
};
function parseHeaders (res) {
var lines = res.getAllResponseHeaders().split(/\r?\n/);
var headers = {};
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line === '') continue;
var m = line.match(/^([^:]+):\s*(.*)/);
if (m) {
var key = m[1].toLowerCase(), value = m[2];
if (headers[key] !== undefined) {
if (isArray(headers[key])) {
headers[key].push(value);
}
else {
headers[key] = [ headers[key], value ];
}
}
else {
headers[key] = value;
}
}
else {
headers[line] = true;
}
}
return headers;
}
Response.prototype.getResponse = function (xhr) {
var respType = String(xhr.responseType).toLowerCase();
if (respType === 'blob') return xhr.responseBlob || xhr.response;
if (respType === 'arraybuffer') return xhr.response;
return xhr.responseText;
}
Response.prototype.getHeader = function (key) {
return this.headers[key.toLowerCase()];
};
Response.prototype.handle = function (res) {
if (res.readyState === 2 && capable.status2) {
try {
this.statusCode = res.status;
this.headers = parseHeaders(res);
}
catch (err) {
capable.status2 = false;
}
if (capable.status2) {
this.emit('ready');
}
}
else if (capable.streaming && res.readyState === 3) {
try {
if (!this.statusCode) {
this.statusCode = res.status;
this.headers = parseHeaders(res);
this.emit('ready');
}
}
catch (err) {}
try {
this._emitData(res);
}
catch (err) {
capable.streaming = false;
}
}
else if (res.readyState === 4) {
if (!this.statusCode) {
this.statusCode = res.status;
this.emit('ready');
}
this._emitData(res);
if (res.error) {
this.emit('error', this.getResponse(res));
}
else this.emit('end');
this.emit('close');
}
};
Response.prototype._emitData = function (res) {
var respBody = this.getResponse(res);
if (respBody.toString().match(/ArrayBuffer/)) {
this.emit('data', new Uint8Array(respBody, this.offset));
this.offset = respBody.byteLength;
return;
}
if (respBody.length > this.offset) {
this.emit('data', respBody.slice(this.offset));
this.offset = respBody.length;
}
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{"stream":257,"util":261}],236:[function(require,module,exports){
;(function () {
var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
// encoder
// [https://gist.github.com/999166] by [https://github.com/nignag]
object.btoa || (
object.btoa = function (input) {
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next input index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
input.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = input.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
});
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
object.atob || (
object.atob = function (input) {
input = input.replace(/=+$/, '');
if (input.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = input.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
});
}());
},{}],237:[function(require,module,exports){
var http = require('http');
var https = module.exports;
for (var key in http) {
if (http.hasOwnProperty(key)) https[key] = http[key];
};
https.request = function (params, cb) {
if (!params) params = {};
params.scheme = 'https';
params.protocol = 'https:';
return http.request.call(this, params, cb);
}
},{"http":233}],238:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],239:[function(require,module,exports){
/**
* Determine if an object is Buffer
*
* Author: Feross Aboukhadijeh
* License: MIT
*
* `npm install is-buffer`
*/
module.exports = function (obj) {
return !!(obj != null &&
(obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
(obj.constructor &&
typeof obj.constructor.isBuffer === 'function' &&
obj.constructor.isBuffer(obj))
))
}
},{}],240:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],241:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],242:[function(require,module,exports){
(function (global){
/*! http://mths.be/punycode v1.2.4 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports;
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings.
* @private
* @param {String} domain The domain name.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols to a Punycode string of ASCII-only
* symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's state to ,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name to Unicode. Only the
* Punycoded parts of the domain name will be converted, i.e. it doesn't
* matter if you call it on a string that has already been converted to
* Unicode.
* @memberOf punycode
* @param {String} domain The Punycode domain name to convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name to Punycode. Only the
* non-ASCII parts of the domain name will be converted, i.e. it doesn't
* matter if you call it with a domain that's already in ASCII.
* @memberOf punycode
* @param {String} domain The domain name to convert, as a Unicode string.
* @returns {String} The Punycode representation of the given domain name.
*/
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.2.4',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = punycode;
} else { // in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else { // in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],243:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],244:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],245:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":243,"./encode":244}],246:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":247}],247:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/**/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/* */
/**/
var util = require('core-util-is');
util.inherits = require('inherits');
/* */
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
forEach(objectKeys(Writable.prototype), function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
}).call(this,require('_process'))
},{"./_stream_readable":249,"./_stream_writable":251,"_process":241,"core-util-is":252,"inherits":238}],248:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/**/
var util = require('core-util-is');
util.inherits = require('inherits');
/* */
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":250,"core-util-is":252,"inherits":238}],249:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Readable;
/**/
var isArray = require('isarray');
/* */
/**/
var Buffer = require('buffer').Buffer;
/* */
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/**/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/* */
var Stream = require('stream');
/**/
var util = require('core-util-is');
util.inherits = require('inherits');
/* */
var StringDecoder;
/**/
var debug = require('util');
if (debug && debug.debuglog) {
debug = debug.debuglog('stream');
} else {
debug = function () {};
}
/* */
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.readableObjectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
var Duplex = require('./_stream_duplex');
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (util.isString(chunk) && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (util.isNullOrUndefined(chunk)) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
if (!addToFront)
state.reading = false;
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront)
state.buffer.unshift(chunk);
else
state.buffer.push(chunk);
if (state.needReadable)
emitReadable(stream);
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (isNaN(n) || util.isNull(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
debug('read', n);
var state = this._readableState;
var nOrig = n;
if (!util.isNumber(n) || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended)
endReadable(this);
else
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
}
if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
var ret;
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (util.isNull(ret)) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended && state.length === 0)
endReadable(this);
if (!util.isNull(ret))
this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(function() {
maybeReadMore_(stream, state);
});
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended &&
state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function(dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
dest !== process.stdout &&
dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted)
process.nextTick(endFn);
else
src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain &&
(!dest._writableState || dest._writableState.needDrain))
ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
if (false === ret) {
debug('false write response, pause',
src._readableState.awaitDrain);
src._readableState.awaitDrain++;
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
if (!dest._events || !dest._events.error)
dest.on('error', onerror);
else if (isArray(dest._events.error))
dest._events.error.unshift(onerror);
else
dest._events.error = [onerror, dest._events.error];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain)
state.awaitDrain--;
if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1)
return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
// If listening to data, and it has not explicitly been paused,
// then call resume to start the flow of data on the next tick.
if (ev === 'data' && false !== this._readableState.flowing) {
this.resume();
}
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
var self = this;
process.nextTick(function() {
debug('readable nexttick read 0');
self.read(0);
});
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
if (!state.reading) {
debug('resume read 0');
this.read(0);
}
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
process.nextTick(function() {
resume_(stream, state);
});
}
}
function resume_(stream, state) {
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading)
stream.read(0);
}
Readable.prototype.pause = function() {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
if (state.flowing) {
do {
var chunk = stream.read();
} while (null !== chunk && state.flowing);
}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length)
self.push(chunk);
}
self.push(null);
});
stream.on('data', function(chunk) {
debug('wrapped data');
if (state.decoder)
chunk = state.decoder.write(chunk);
if (!chunk || !state.objectMode && !chunk.length)
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode)
ret = '';
else
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
if (stringMode)
ret += buf.slice(0, cpy);
else
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length)
list[0] = buf.slice(cpy);
else
list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
});
}
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf (xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":247,"_process":241,"buffer":228,"core-util-is":252,"events":232,"inherits":238,"isarray":240,"stream":257,"string_decoder/":258,"util":227}],250:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/**/
var util = require('core-util-is');
util.inherits = require('inherits');
/* */
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (!util.isNullOrUndefined(data))
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('prefinish', function() {
if (util.isFunction(this._flush))
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":247,"core-util-is":252,"inherits":238}],251:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/**/
var Buffer = require('buffer').Buffer;
/* */
Writable.WritableState = WritableState;
/**/
var util = require('core-util-is');
util.inherits = require('inherits');
/* */
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
cb(er);
}
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished &&
!state.corked &&
!state.bufferProcessing &&
state.buffer.length) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
if (stream._writev && state.buffer.length > 1) {
// Fast case, write everything using _writev()
var cbs = [];
for (var c = 0; c < state.buffer.length; c++)
cbs.push(state.buffer[c].callback);
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
state.buffer = [];
} else {
// Slow case, write chunks one-by-one
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
state.bufferProcessing = false;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (util.isFunction(chunk)) {
cb = chunk;
chunk = null;
encoding = null;
} else if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (!util.isNullOrUndefined(chunk))
this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else
prefinish(stream, state);
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
}).call(this,require('_process'))
},{"./_stream_duplex":247,"_process":241,"buffer":228,"core-util-is":252,"inherits":238,"stream":257}],252:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})
},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":239}],253:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":248}],254:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('stream');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":247,"./lib/_stream_passthrough.js":248,"./lib/_stream_readable.js":249,"./lib/_stream_transform.js":250,"./lib/_stream_writable.js":251,"stream":257}],255:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":250}],256:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":251}],257:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":232,"inherits":238,"readable-stream/duplex.js":246,"readable-stream/passthrough.js":253,"readable-stream/readable.js":254,"readable-stream/transform.js":255,"readable-stream/writable.js":256}],258:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":228}],259:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var punycode = require('punycode');
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a puny coded representation of "domain".
// It only converts the part of the domain name that
// has non ASCII characters. I.e. it dosent matter if
// you call it with a domain that already is in ASCII.
var domainArray = this.hostname.split('.');
var newOut = [];
for (var i = 0; i < domainArray.length; ++i) {
var s = domainArray[i];
newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
'xn--' + punycode.encode(s) : s);
}
this.hostname = newOut.join('.');
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
Object.keys(this).forEach(function(k) {
result[k] = this[k];
}, this);
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
Object.keys(relative).forEach(function(k) {
if (k !== 'protocol')
result[k] = relative[k];
});
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
Object.keys(relative).forEach(function(k) {
result[k] = relative[k];
});
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especialy happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!isNull(result.pathname) || !isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host) && (last === '.' || last === '..') ||
last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last == '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especialy happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!isNull(result.pathname) || !isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
function isString(arg) {
return typeof arg === "string";
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
},{"punycode":242,"querystring":245}],260:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],261:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":260,"_process":241,"inherits":238}],262:[function(require,module,exports){
module.exports = require('./lib');
},{"./lib":263}],263:[function(require,module,exports){
var FORMAT_REGEXP = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;
function matchToInteger(match){
return match === undefined ? 0 : parseInt(match, 10);
}
exports.fromSeconds = function(seconds){
if(typeof seconds !== 'number'){
throw new TypeError('Argument `seconds` must be a number');
}
var fullSeconds = seconds % 60;
var fullMinutesInSeconds = (seconds - fullSeconds) % 3600;
return {
hours: (seconds - fullSeconds - fullMinutesInSeconds) / 3600,
minutes: fullMinutesInSeconds / 60,
seconds: fullSeconds
};
};
exports.fromString = function(string){
if(typeof string !== 'string'){
throw new TypeError('Argument `string` must be a string');
}
var matches = string.match(FORMAT_REGEXP);
if(matches === null || (matches[1] === undefined && matches[2] === undefined && matches[3] === undefined)){
throw new Error('Could not parse "' + string + '" as a duration.');
}
return {
hours: matchToInteger(matches[1]),
minutes: matchToInteger(matches[2]),
seconds: matchToInteger(matches[3])
};
};
exports.toString = function(duration) {
if(typeof duration === 'number'){
duration = exports.fromSeconds(duration);
}
var result = 'PT';
if(duration.hours > 0){
result += duration.hours + 'H';
}
if(duration.minutes > 0){
result += duration.minutes + 'M';
}
if(duration.seconds > 0){
result += duration.seconds + 'S';
}
if(result === 'PT'){
result += '0S';
}
return result;
};
exports.toSeconds = function(stringOrDuration) {
var duration = stringOrDuration;
if(typeof stringOrDuration === 'string') {
duration = exports.fromString(stringOrDuration);
}
return duration.hours * 3600 + duration.minutes * 60 + duration.seconds;
};
},{}],264:[function(require,module,exports){
/*
Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
*/
(function () {
var StateMachine = {
//---------------------------------------------------------------------------
VERSION: "2.3.5",
//---------------------------------------------------------------------------
Result: {
SUCCEEDED: 1, // the event transitioned successfully from one state to another
NOTRANSITION: 2, // the event was successfull but no state transition was necessary
CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
},
Error: {
INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
INVALID_CALLBACK: 300 // caller provided callback function threw an exception
},
WILDCARD: '*',
ASYNC: 'async',
//---------------------------------------------------------------------------
create: function(cfg, target) {
var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
var terminal = cfg.terminal || cfg['final'];
var fsm = target || cfg.target || {};
var events = cfg.events || [];
var callbacks = cfg.callbacks || {};
var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
var transitions = {}; // track events allowed from a state { state: [ event ] }
var add = function(e) {
var from = (e.from instanceof Array) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
map[e.name] = map[e.name] || {};
for (var n = 0 ; n < from.length ; n++) {
transitions[from[n]] = transitions[from[n]] || [];
transitions[from[n]].push(e.name);
map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
}
};
if (initial) {
initial.event = initial.event || 'startup';
add({ name: initial.event, from: 'none', to: initial.state });
}
for(var n = 0 ; n < events.length ; n++)
add(events[n]);
for(var name in map) {
if (map.hasOwnProperty(name))
fsm[name] = StateMachine.buildEvent(name, map[name]);
}
for(var name in callbacks) {
if (callbacks.hasOwnProperty(name))
fsm[name] = callbacks[name]
}
fsm.current = 'none';
fsm.is = function(state) { return (state instanceof Array) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
fsm.can = function(event) { return !this.transition && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); }
fsm.cannot = function(event) { return !this.can(event); };
fsm.transitions = function() { return transitions[this.current]; };
fsm.isFinished = function() { return this.is(terminal); };
fsm.error = cfg.error || function(name, from, to, args, error, msg, e) { throw e || msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3 and #17)
if (initial && !initial.defer)
fsm[initial.event]();
return fsm;
},
//===========================================================================
doCallback: function(fsm, func, name, from, to, args) {
if (func) {
try {
return func.apply(fsm, [name, from, to].concat(args));
}
catch(e) {
return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
}
}
},
beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
beforeEvent: function(fsm, name, from, to, args) {
if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
(false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
return false;
},
afterEvent: function(fsm, name, from, to, args) {
StateMachine.afterThisEvent(fsm, name, from, to, args);
StateMachine.afterAnyEvent( fsm, name, from, to, args);
},
leaveState: function(fsm, name, from, to, args) {
var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
general = StateMachine.leaveAnyState( fsm, name, from, to, args);
if ((false === specific) || (false === general))
return false;
else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
return StateMachine.ASYNC;
},
enterState: function(fsm, name, from, to, args) {
StateMachine.enterThisState(fsm, name, from, to, args);
StateMachine.enterAnyState( fsm, name, from, to, args);
},
//===========================================================================
buildEvent: function(name, map) {
return function() {
var from = this.current;
var to = map[from] || map[StateMachine.WILDCARD] || from;
var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
if (this.transition)
return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
if (this.cannot(name))
return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
if (false === StateMachine.beforeEvent(this, name, from, to, args))
return StateMachine.Result.CANCELLED;
if (from === to) {
StateMachine.afterEvent(this, name, from, to, args);
return StateMachine.Result.NOTRANSITION;
}
// prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
var fsm = this;
this.transition = function() {
fsm.transition = null; // this method should only ever be called once
fsm.current = to;
StateMachine.enterState( fsm, name, from, to, args);
StateMachine.changeState(fsm, name, from, to, args);
StateMachine.afterEvent( fsm, name, from, to, args);
return StateMachine.Result.SUCCEEDED;
};
this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
fsm.transition = null;
StateMachine.afterEvent(fsm, name, from, to, args);
}
var leave = StateMachine.leaveState(this, name, from, to, args);
if (false === leave) {
this.transition = null;
return StateMachine.Result.CANCELLED;
}
else if (StateMachine.ASYNC === leave) {
return StateMachine.Result.PENDING;
}
else {
if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
return this.transition();
}
};
}
}; // StateMachine
//===========================================================================
//======
// NODE
//======
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = StateMachine;
}
exports.StateMachine = StateMachine;
}
//============
// AMD/REQUIRE
//============
else if (typeof define === 'function' && define.amd) {
define(function(require) { return StateMachine; });
}
//========
// BROWSER
//========
else if (typeof window !== 'undefined') {
window.StateMachine = StateMachine;
}
//===========
// WEB WORKER
//===========
else if (typeof self !== 'undefined') {
self.StateMachine = StateMachine;
}
}());
},{}],265:[function(require,module,exports){
/*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/
(function (root, definition) {
"use strict";
if (typeof module === 'object' && module.exports && typeof require === 'function') {
module.exports = definition();
} else if (typeof define === 'function' && typeof define.amd === 'object') {
define(definition);
} else {
root.log = definition();
}
}(this, function () {
"use strict";
var noop = function() {};
var undefinedType = "undefined";
function realMethod(methodName) {
if (typeof console === undefinedType) {
return false; // We can't build a real method without a console to log to
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}
// these private functions always need `this` to be set properly
function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
return function () {
if (typeof console !== undefinedType) {
replaceLoggingMethods.call(this, level, loggerName);
this[methodName].apply(this, arguments);
}
};
}
function replaceLoggingMethods(level, loggerName) {
/*jshint validthis:true */
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = (i < level) ?
noop :
this.methodFactory(methodName, level, loggerName);
}
}
function defaultMethodFactory(methodName, level, loggerName) {
/*jshint validthis:true */
return realMethod(methodName) ||
enableLoggingWhenConsoleArrives.apply(this, arguments);
}
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
function Logger(name, defaultLevel, factory) {
var self = this;
var currentLevel;
var storageKey = "loglevel";
if (name) {
storageKey += ":" + name;
}
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
// Use localStorage if available
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {}
if (typeof storedLevel === undefinedType) {
try {
var cookie = window.document.cookie;
var location = cookie.indexOf(
encodeURIComponent(storageKey) + "=");
if (location) {
storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
}
} catch (ignore) {}
}
// If the stored level is not valid, treat it as if nothing was stored.
if (self.levels[storedLevel] === undefined) {
storedLevel = undefined;
}
return storedLevel;
}
/*
*
* Public API
*
*/
self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
"ERROR": 4, "SILENT": 5};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function () {
return currentLevel;
};
self.setLevel = function (level, persist) {
if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
level = self.levels[level.toUpperCase()];
}
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
currentLevel = level;
if (persist !== false) { // defaults to true
persistLevelIfPossible(level);
}
replaceLoggingMethods.call(self, level, name);
if (typeof console === undefinedType && level < self.levels.SILENT) {
return "No console available for logging";
}
} else {
throw "log.setLevel() called with invalid level: " + level;
}
};
self.setDefaultLevel = function (level) {
if (!getPersistedLevel()) {
self.setLevel(level, false);
}
};
self.enableAll = function(persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function(persist) {
self.setLevel(self.levels.SILENT, persist);
};
// Initialize with the right level
var initialLevel = getPersistedLevel();
if (initialLevel == null) {
initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
}
self.setLevel(initialLevel, false);
}
/*
*
* Package-level API
*
*/
var defaultLogger = new Logger();
var _loggersByName = {};
defaultLogger.getLogger = function getLogger(name) {
if (typeof name !== "string" || name === "") {
throw new TypeError("You must supply a name when creating a logger.");
}
var logger = _loggersByName[name];
if (!logger) {
logger = _loggersByName[name] = new Logger(
name, defaultLogger.getLevel(), defaultLogger.methodFactory);
}
return logger;
};
// Grab the current global log variable in case of overwrite
var _log = (typeof window !== undefinedType) ? window.log : undefined;
defaultLogger.noConflict = function() {
if (typeof window !== undefinedType &&
window.log === defaultLogger) {
window.log = _log;
}
return defaultLogger;
};
return defaultLogger;
}));
},{}],266:[function(require,module,exports){
(function (global){
/*!
* Platform.js v1.3.0
* Copyright 2010-2014 John-David Dalton
* Available under MIT license
*/
;(function() {
'use strict';
/** Used to determine if values are of the language type `Object` */
var objectTypes = {
'function': true,
'object': true
};
/** Used as a reference to the global object */
var root = (objectTypes[typeof window] && window) || this;
/** Backup possible global object */
var oldRoot = root;
/** Detect free variable `exports` */
var freeExports = objectTypes[typeof exports] && exports;
/** Detect free variable `module` */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
root = freeGlobal;
}
/**
* Used as the maximum length of an array-like object.
* See the [ES6 spec](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)
* for more details.
*/
var maxSafeInteger = Math.pow(2, 53) - 1;
/** Opera regexp */
var reOpera = /\bOpera/;
/** Possible global object */
var thisBinding = this;
/** Used for native method references */
var objectProto = Object.prototype;
/** Used to check for own properties of an object */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to resolve the internal `[[Class]]` of values */
var toString = objectProto.toString;
/*--------------------------------------------------------------------------*/
/**
* Capitalizes a string value.
*
* @private
* @param {string} string The string to capitalize.
* @returns {string} The capitalized string.
*/
function capitalize(string) {
string = String(string);
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* A utility function to clean up the OS name.
*
* @private
* @param {string} os The OS name to clean up.
* @param {string} [pattern] A `RegExp` pattern matching the OS name.
* @param {string} [label] A label for the OS.
*/
function cleanupOS(os, pattern, label) {
// platform tokens defined at
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
var data = {
'6.4': '10',
'6.3': '8.1',
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// detect Windows version from platform tokens
if (pattern && label && /^Win/i.test(os) &&
(data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(os)])) {
os = 'Windows ' + data;
}
// correct character case and cleanup
os = String(os);
if (pattern && label) {
os = os.replace(RegExp(pattern, 'i'), label);
}
os = format(
os.replace(/ ce$/i, ' CE')
.replace(/\bhpw/i, 'web')
.replace(/\bMacintosh\b/, 'Mac OS')
.replace(/_PowerPC\b/i, ' OS')
.replace(/\b(OS X) [^ \d]+/i, '$1')
.replace(/\bMac (OS X)\b/, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/\bx86\.64\b/gi, 'x86_64')
.replace(/\b(Windows Phone) OS\b/, '$1')
.split(' on ')[0]
);
return os;
}
/**
* An iteration utility for arrays and objects.
*
* @private
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
*/
function each(object, callback) {
var index = -1,
length = object ? object.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
}
/**
* Trim and conditionally capitalize string values.
*
* @private
* @param {string} string The string to format.
* @returns {string} The formatted string.
*/
function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
*/
function forOwn(object, callback) {
for (var key in object) {
if (hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
}
/**
* Gets the internal `[[Class]]` of a value.
*
* @private
* @param {*} value The value.
* @returns {string} The `[[Class]]`.
*/
function getClassOf(value) {
return value == null
? capitalize(value)
: toString.call(value).slice(8, -1);
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of "object", "function", or "unknown".
*
* @private
* @param {*} object The owner of the property.
* @param {string} property The property to check.
* @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* Prepares a string for use in a `RegExp` by making hyphens and spaces optional.
*
* @private
* @param {string} string The string to qualify.
* @returns {string} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* A bare-bones `Array#reduce` like utility function.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @returns {*} The accumulated result.
*/
function reduce(array, callback) {
var accumulator = null;
each(array, function(value, index) {
accumulator = callback(accumulator, value, index, array);
});
return accumulator;
}
/**
* Removes leading and trailing whitespace from a string.
*
* @private
* @param {string} string The string to trim.
* @returns {string} The trimmed string.
*/
function trim(string) {
return String(string).replace(/^ +| +$/g, '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new platform object.
*
* @memberOf platform
* @param {Object|string} [ua=navigator.userAgent] The user agent string or
* context object.
* @returns {Object} A platform object.
*/
function parse(ua) {
/** The environment context object */
var context = root;
/** Used to flag when a custom context is provided */
var isCustomContext = ua && typeof ua == 'object' && getClassOf(ua) != 'String';
// juggle arguments
if (isCustomContext) {
context = ua;
ua = null;
}
/** Browser navigator object */
var nav = context.navigator || {};
/** Browser user agent string */
var userAgent = nav.userAgent || '';
ua || (ua = userAgent);
/** Used to flag when `thisBinding` is the [ModuleScope] */
var isModuleScope = isCustomContext || thisBinding == oldRoot;
/** Used to detect if browser is like Chrome */
var likeChrome = isCustomContext
? !!nav.likeChrome
: /\bChrome\b/.test(ua) && !/internal|\n/i.test(toString.toString());
/** Internal `[[Class]]` value shortcuts */
var objectClass = 'Object',
airRuntimeClass = isCustomContext ? objectClass : 'ScriptBridgingProxyObject',
enviroClass = isCustomContext ? objectClass : 'Environment',
javaClass = (isCustomContext && context.java) ? 'JavaPackage' : getClassOf(context.java),
phantomClass = isCustomContext ? objectClass : 'RuntimeObject';
/** Detect Java environment */
var java = /\bJava/.test(javaClass) && context.java;
/** Detect Rhino */
var rhino = java && getClassOf(context.environment) == enviroClass;
/** A character to represent alpha */
var alpha = java ? 'a' : '\u03b1';
/** A character to represent beta */
var beta = java ? 'b' : '\u03b2';
/** Browser document object */
var doc = context.document || {};
/**
* Detect Opera browser (Presto-based)
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
var opera = context.operamini || context.opera;
/** Opera `[[Class]]` */
var operaClass = reOpera.test(operaClass = (isCustomContext && opera) ? opera['[[Class]]'] : getClassOf(opera))
? operaClass
: (opera = null);
/*------------------------------------------------------------------------*/
/** Temporary variable used over the script's lifetime */
var data;
/** The CPU architecture */
var arch = ua;
/** Platform description array */
var description = [];
/** Platform alpha/beta indicator */
var prerelease = null;
/** A flag to indicate that environment features should be used to resolve the platform */
var useFeatures = ua == userAgent;
/** The browser/environment version */
var version = useFeatures && opera && typeof opera.version == 'function' && opera.version();
/** A flag to indicate if the OS ends with "/ Version" */
var isSpecialCasedOS;
/* Detectable layout engines (order is important) */
var layout = getLayout([
'Trident',
{ 'label': 'WebKit', 'pattern': 'AppleWebKit' },
'iCab',
'Presto',
'NetFront',
'Tasman',
'KHTML',
'Gecko'
]);
/* Detectable browser names (order is important) */
var name = getName([
'Adobe AIR',
'Arora',
'Avant Browser',
'Breach',
'Camino',
'Epiphany',
'Fennec',
'Flock',
'Galeon',
'GreenBrowser',
'iCab',
'Iceweasel',
{ 'label': 'SRWare Iron', 'pattern': 'Iron' },
'K-Meleon',
'Konqueror',
'Lunascape',
'Maxthon',
'Midori',
'Nook Browser',
'PhantomJS',
'Raven',
'Rekonq',
'RockMelt',
'SeaMonkey',
{ 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' },
'Sleipnir',
'SlimBrowser',
'Sunrise',
'Swiftfox',
'WebPositive',
'Opera Mini',
{ 'label': 'Opera Mini', 'pattern': 'OPiOS' },
'Opera',
{ 'label': 'Opera', 'pattern': 'OPR' },
'Chrome',
{ 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' },
{ 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' },
{ 'label': 'IE', 'pattern': 'IEMobile' },
{ 'label': 'IE', 'pattern': 'MSIE' },
'Safari'
]);
/* Detectable products (order is important) */
var product = getProduct([
{ 'label': 'BlackBerry', 'pattern': 'BB10' },
'BlackBerry',
{ 'label': 'Galaxy S', 'pattern': 'GT-I9000' },
{ 'label': 'Galaxy S2', 'pattern': 'GT-I9100' },
{ 'label': 'Galaxy S3', 'pattern': 'GT-I9300' },
{ 'label': 'Galaxy S4', 'pattern': 'GT-I9500' },
'Google TV',
'Lumia',
'iPad',
'iPod',
'iPhone',
'Kindle',
{ 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' },
'Nook',
'PlayBook',
'PlayStation 4',
'PlayStation 3',
'PlayStation Vita',
'TouchPad',
'Transformer',
{ 'label': 'Wii U', 'pattern': 'WiiU' },
'Wii',
'Xbox One',
{ 'label': 'Xbox 360', 'pattern': 'Xbox' },
'Xoom'
]);
/* Detectable manufacturers */
var manufacturer = getManufacturer({
'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 },
'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 },
'Asus': { 'Transformer': 1 },
'Barnes & Noble': { 'Nook': 1 },
'BlackBerry': { 'PlayBook': 1 },
'Google': { 'Google TV': 1 },
'HP': { 'TouchPad': 1 },
'HTC': {},
'LG': {},
'Microsoft': { 'Xbox': 1, 'Xbox One': 1 },
'Motorola': { 'Xoom': 1 },
'Nintendo': { 'Wii U': 1, 'Wii': 1 },
'Nokia': { 'Lumia': 1 },
'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1, 'Galaxy S3': 1, 'Galaxy S4': 1 },
'Sony': { 'PlayStation 4': 1, 'PlayStation 3': 1, 'PlayStation Vita': 1 }
});
/* Detectable OSes (order is important) */
var os = getOS([
'Windows Phone ',
'Android',
'CentOS',
'Debian',
'Fedora',
'FreeBSD',
'Gentoo',
'Haiku',
'Kubuntu',
'Linux Mint',
'Red Hat',
'SuSE',
'Ubuntu',
'Xubuntu',
'Cygwin',
'Symbian OS',
'hpwOS',
'webOS ',
'webOS',
'Tablet OS',
'Linux',
'Mac OS X',
'Macintosh',
'Mac',
'Windows 98;',
'Windows '
]);
/*------------------------------------------------------------------------*/
/**
* Picks the layout engine from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected layout engine.
*/
function getLayout(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the manufacturer from an array of guesses.
*
* @private
* @param {Array} guesses An object of guesses.
* @returns {null|string} The detected manufacturer.
*/
function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// lookup the manufacturer by product or scan the UA for the manufacturer
return result || (
value[product] ||
value[0/*Opera 9.25 fix*/, /^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] ||
RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && key;
});
}
/**
* Picks the browser name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected browser name.
*/
function getName(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the OS name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected OS name.
*/
function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua)
)) {
result = cleanupOS(result, pattern, guess.label || guess);
}
return result;
});
}
/**
* Picks the product name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected product name.
*/
function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// split by forward slash and append product version if needed
if ((result = String((guess.label && !RegExp(pattern, 'i').test(guess.label)) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// correct character case and cleanup
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2'));
}
return result;
});
}
/**
* Resolves the version using an array of UA patterns.
*
* @private
* @param {Array} patterns An array of UA patterns.
* @returns {null|string} The detected version.
*/
function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null;
});
}
/**
* Returns `platform.description` when the platform object is coerced to a string.
*
* @name toString
* @memberOf platform
* @returns {string} Returns `platform.description` if available, else an empty string.
*/
function toStringPlatform() {
return this.description || '';
}
/*------------------------------------------------------------------------*/
// convert layout to an array so we can add extra details
layout && (layout = [layout]);
// detect product names that contain their manufacturer's name
if (manufacturer && !product) {
product = getProduct([manufacturer]);
}
// clean up Google TV
if ((data = /\bGoogle TV\b/.exec(product))) {
product = data[0];
}
// detect simulators
if (/\bSimulator\b/i.test(ua)) {
product = (product ? product + ' ' : '') + 'Simulator';
}
// detect Opera Mini 8+ running in Turbo/Uncompressed mode on iOS
if (name == 'Opera Mini' && /\bOPiOS\b/.test(ua)) {
description.push('running in Turbo/Uncompressed mode');
}
// detect iOS
if (/^iP/.test(product)) {
name || (name = 'Safari');
os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua))
? ' ' + data[1].replace(/_/g, '.')
: '');
}
// detect Kubuntu
else if (name == 'Konqueror' && !/buntu/i.test(os)) {
os = 'Kubuntu';
}
// detect Android browsers
else if (manufacturer && manufacturer != 'Google' &&
((/Chrome/.test(name) && !/\bMobile Safari\b/i.test(ua)) || /\bVita\b/.test(product))) {
name = 'Android Browser';
os = /\bAndroid\b/.test(os) ? os : 'Android';
}
// detect false positives for Firefox/Safari
else if (!name || (data = !/\bMinefield\b|\(Android;/i.test(ua) && /\b(?:Firefox|Safari)\b/.exec(name))) {
// escape the `/` for Firefox 1
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// clear name of false positives
name = null;
}
// reassign a generic name
if ((data = product || manufacturer || os) &&
(product || manufacturer || /\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))) {
name = /[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os) ? os : data) + ' Browser';
}
}
// detect Firefox OS
if ((data = /\((Mobile|Tablet).*?Firefox\b/i.exec(ua)) && data[1]) {
os = 'Firefox OS';
if (!product) {
product = data[1];
}
}
// detect non-Opera versions (order is important)
if (!version) {
version = getVersion([
'(?:Cloud9|CriOS|CrMo|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|Silk(?!/[\\d.]+$))',
'Version',
qualify(name),
'(?:Firefox|Minefield|NetFront)'
]);
}
// detect stubborn layout engines
if (layout == 'iCab' && parseFloat(version) > 3) {
layout = ['WebKit'];
} else if (
layout != 'Trident' &&
(data =
/\bOpera\b/.test(name) && (/\bOPR\b/.test(ua) ? 'Blink' : 'Presto') ||
/\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' ||
!layout && /\bMSIE\b/i.test(ua) && (os == 'Mac OS' ? 'Tasman' : 'Trident')
)
) {
layout = [data];
}
// detect NetFront on PlayStation
else if (/\bPlayStation\b(?! Vita\b)/i.test(name) && layout == 'WebKit') {
layout = ['NetFront'];
}
// detect Windows Phone 7 desktop mode
if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) {
name += ' Mobile';
os = 'Windows Phone ' + (/\+$/.test(data) ? data : data + '.x');
description.unshift('desktop mode');
}
// detect Windows Phone 8+ desktop mode
else if (/\bWPDesktop\b/i.test(ua)) {
name = 'IE Mobile';
os = 'Windows Phone 8+';
description.unshift('desktop mode');
version || (version = (/\brv:([\d.]+)/.exec(ua) || 0)[1]);
}
// detect IE 11 and above
else if (name != 'IE' && layout == 'Trident' && (data = /\brv:([\d.]+)/.exec(ua))) {
if (!/\bWPDesktop\b/i.test(ua)) {
if (name) {
description.push('identifying as ' + name + (version ? ' ' + version : ''));
}
name = 'IE';
}
version = data[1];
}
// detect IE Tech Preview
else if ((name == 'Chrome' || name != 'IE') && (data = /\bEdge\/([\d.]+)/.exec(ua))) {
name = 'IE';
version = data[1];
layout = ['Trident'];
description.unshift('platform preview');
}
// leverage environment features
if (useFeatures) {
// detect server-side environments
// Rhino has a global function while others have a global object
if (isHostType(context, 'global')) {
if (java) {
data = java.lang.System;
arch = data.getProperty('os.arch');
os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version');
}
if (isModuleScope && isHostType(context, 'system') && (data = [context.system])[0]) {
os || (os = data[0].os || null);
try {
data[1] = context.require('ringo/engine').version;
version = data[1].join('.');
name = 'RingoJS';
} catch(e) {
if (data[0].global.system == context.system) {
name = 'Narwhal';
}
}
}
else if (typeof context.process == 'object' && (data = context.process)) {
name = 'Node.js';
arch = data.arch;
os = data.platform;
version = /[\d.]+/.exec(data.version)[0];
}
else if (rhino) {
name = 'Rhino';
}
}
// detect Adobe AIR
else if (getClassOf((data = context.runtime)) == airRuntimeClass) {
name = 'Adobe AIR';
os = data.flash.system.Capabilities.os;
}
// detect PhantomJS
else if (getClassOf((data = context.phantom)) == phantomClass) {
name = 'PhantomJS';
version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch);
}
// detect IE compatibility modes
else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) {
// we're in compatibility mode when the Trident version + 4 doesn't
// equal the document mode
version = [version, doc.documentMode];
if ((data = +data[1] + 4) != version[1]) {
description.push('IE ' + version[1] + ' mode');
layout && (layout[1] = '');
version[1] = data;
}
version = name == 'IE' ? String(version[1].toFixed(1)) : version[0];
}
os = os && format(os);
}
// detect prerelease phases
if (version && (data =
/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) ||
/(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) ||
/\bMinefield\b/i.test(ua) && 'a'
)) {
prerelease = /b/i.test(data) ? 'beta' : 'alpha';
version = version.replace(RegExp(data + '\\+?$'), '') +
(prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || '');
}
// detect Firefox Mobile
if (name == 'Fennec' || name == 'Firefox' && /\b(?:Android|Firefox OS)\b/.test(os)) {
name = 'Firefox Mobile';
}
// obscure Maxthon's unreliable version
else if (name == 'Maxthon' && version) {
version = version.replace(/\.[\d.]+/, '.x');
}
// detect Silk desktop/accelerated modes
else if (name == 'Silk') {
if (!/\bMobi/i.test(ua)) {
os = 'Android';
description.unshift('desktop mode');
}
if (/Accelerated *= *true/i.test(ua)) {
description.unshift('accelerated');
}
}
// detect Xbox 360 and Xbox One
else if (/\bXbox\b/i.test(product)) {
os = null;
if (product == 'Xbox 360' && /\bIEMobile\b/.test(ua)) {
description.unshift('mobile mode');
}
}
// add mobile postfix
else if ((/^(?:Chrome|IE|Opera)$/.test(name) || name && !product && !/Browser|Mobi/.test(name)) &&
(os == 'Windows CE' || /Mobi/i.test(ua))) {
name += ' Mobile';
}
// detect IE platform preview
else if (name == 'IE' && useFeatures && context.external === null) {
description.unshift('platform preview');
}
// detect BlackBerry OS version
// http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp
else if ((/\bBlackBerry\b/.test(product) || /\bBB10\b/.test(ua)) && (data =
(RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] ||
version
)) {
data = [data, /BB10/.test(ua)];
os = (data[1] ? (product = null, manufacturer = 'BlackBerry') : 'Device Software') + ' ' + data[0];
version = null;
}
// detect Opera identifying/masking itself as another browser
// http://www.opera.com/support/kb/view/843/
else if (this != forOwn && (
product != 'Wii' && (
(useFeatures && opera) ||
(/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) ||
(name == 'Firefox' && /\bOS X (?:\d+\.){2,}/.test(os)) ||
(name == 'IE' && (
(os && !/^Win/.test(os) && version > 5.5) ||
/\bWindows XP\b/.test(os) && version > 8 ||
version == 8 && !/\bTrident\b/.test(ua)
))
)
) && !reOpera.test((data = parse.call(forOwn, ua.replace(reOpera, '') + ';'))) && data.name) {
// when "indentifying", the UA contains both Opera and the other browser's name
data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : '');
if (reOpera.test(name)) {
if (/\bIE\b/.test(data) && os == 'Mac OS') {
os = null;
}
data = 'identify' + data;
}
// when "masking", the UA contains only the other browser's name
else {
data = 'mask' + data;
if (operaClass) {
name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2'));
} else {
name = 'Opera';
}
if (/\bIE\b/.test(data)) {
os = null;
}
if (!useFeatures) {
version = null;
}
}
layout = ['Presto'];
description.push(data);
}
// detect WebKit Nightly and approximate Chrome/Safari versions
if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
// correct build for numeric comparison
// (e.g. "532.5" becomes "532.05")
data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data];
// nightly builds are postfixed with a `+`
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
version = data[1].slice(0, -1);
}
// clear incorrect browser versions
else if (version == data[1] ||
version == (data[2] = (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
version = null;
}
// use the full Chrome version when available
data[1] = (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1];
// detect Blink layout engine
if (data[0] == 537.36 && data[2] == 537.36 && parseFloat(data[1]) >= 28 && name != 'IE') {
layout = ['Blink'];
}
// detect JavaScriptCore
// http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi
if (!useFeatures || (!likeChrome && !data[1])) {
layout && (layout[1] = 'like Safari');
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : data < 537 ? 6 : data < 538 ? 7 : data < 601 ? 8 : '8');
} else {
layout && (layout[1] = 'like Chrome');
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : data < 537.11 ? '21+' : data < 537.13 ? 23 : data < 537.18 ? 24 : data < 537.24 ? 25 : data < 537.36 ? 26 : layout != 'Blink' ? '27' : '28');
}
// add the postfix of ".x" or "+" for approximate versions
layout && (layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+'));
// obscure version for some Safari 1-2 releases
if (name == 'Safari' && (!version || parseInt(version) > 45)) {
version = data;
}
}
// detect Opera desktop modes
if (name == 'Opera' && (data = /\bzbov|zvav$/.exec(os))) {
name += ' ';
description.unshift('desktop mode');
if (data == 'zvav') {
name += 'Mini';
version = null;
} else {
name += 'Mobile';
}
os = os.replace(RegExp(' *' + data + '$'), '');
}
// detect Chrome desktop mode
else if (name == 'Safari' && /\bChrome\b/.exec(layout && layout[1])) {
description.unshift('desktop mode');
name = 'Chrome Mobile';
version = null;
if (/\bOS X\b/.test(os)) {
manufacturer = 'Apple';
os = 'iOS 4.3+';
} else {
os = null;
}
}
// strip incorrect OS versions
if (version && version.indexOf((data = /[\d.]+$/.exec(os))) == 0 &&
ua.indexOf('/' + data + '-') > -1) {
os = trim(os.replace(data, ''));
}
// add layout engine
if (layout && !/\b(?:Avant|Nook)\b/.test(name) && (
/Browser|Lunascape|Maxthon/.test(name) ||
/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) {
// don't add layout details to description if they are falsey
(data = layout[layout.length - 1]) && description.push(data);
}
// combine contextual information
if (description.length) {
description = ['(' + description.join('; ') + ')'];
}
// append manufacturer
if (manufacturer && product && product.indexOf(manufacturer) < 0) {
description.push('on ' + manufacturer);
}
// append product
if (product) {
description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product);
}
// parse OS into an object
if (os) {
data = / ([\d.+]+)$/.exec(os);
isSpecialCasedOS = data && os.charAt(os.length - data[0].length - 1) == '/';
os = {
'architecture': 32,
'family': (data && !isSpecialCasedOS) ? os.replace(data[0], '') : os,
'version': data ? data[1] : null,
'toString': function() {
var version = this.version;
return this.family + ((version && !isSpecialCasedOS) ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : '');
}
};
}
// add browser/OS architecture
if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) {
if (os) {
os.architecture = 64;
os.family = os.family.replace(RegExp(' *' + data), '');
}
if (
name && (/\bWOW64\b/i.test(ua) ||
(useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform) && !/\bWin64; x64\b/i.test(ua)))
) {
description.unshift('32-bit');
}
}
ua || (ua = null);
/*------------------------------------------------------------------------*/
/**
* The platform object.
*
* @name platform
* @type Object
*/
var platform = {};
/**
* The platform description.
*
* @memberOf platform
* @type string|null
*/
platform.description = ua;
/**
* The name of the browser's layout engine.
*
* @memberOf platform
* @type string|null
*/
platform.layout = layout && layout[0];
/**
* The name of the product's manufacturer.
*
* @memberOf platform
* @type string|null
*/
platform.manufacturer = manufacturer;
/**
* The name of the browser/environment.
*
* @memberOf platform
* @type string|null
*/
platform.name = name;
/**
* The alpha/beta release indicator.
*
* @memberOf platform
* @type string|null
*/
platform.prerelease = prerelease;
/**
* The name of the product hosting the browser.
*
* @memberOf platform
* @type string|null
*/
platform.product = product;
/**
* The browser's user agent string.
*
* @memberOf platform
* @type string|null
*/
platform.ua = ua;
/**
* The browser/environment version.
*
* @memberOf platform
* @type string|null
*/
platform.version = name && version;
/**
* The name of the operating system.
*
* @memberOf platform
* @type Object
*/
platform.os = os || {
/**
* The CPU architecture the OS is built for.
*
* @memberOf platform.os
* @type number|null
*/
'architecture': null,
/**
* The family of the OS.
*
* Common values include:
* "Windows", "Windows Server 2008 R2 / 7", "Windows Server 2008 / Vista",
* "Windows XP", "OS X", "Ubuntu", "Debian", "Fedora", "Red Hat", "SuSE",
* "Android", "iOS" and "Windows Phone"
*
* @memberOf platform.os
* @type string|null
*/
'family': null,
/**
* The version of the OS.
*
* @memberOf platform.os
* @type string|null
*/
'version': null,
/**
* Returns the OS string.
*
* @memberOf platform.os
* @returns {string} The OS string.
*/
'toString': function() { return 'null'; }
};
platform.parse = parse;
platform.toString = toStringPlatform;
if (platform.version) {
description.unshift(version);
}
if (platform.name) {
description.unshift(name);
}
if (os && name && !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product))) {
description.push(product ? '(' + os + ')' : 'on ' + os);
}
if (description.length) {
platform.description = description.join(' ');
}
return platform;
}
/*--------------------------------------------------------------------------*/
// export platform
// some AMD build optimizers, like r.js, check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// define as an anonymous module so, through path mapping, it can be aliased
define(function() {
return parse();
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports && freeModule) {
// in Narwhal, Node.js, Rhino -require, or RingoJS
forOwn(parse(), function(value, key) {
freeExports[key] = value;
});
}
// in a browser or Rhino
else {
root.platform = parse();
}
}.call(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],267:[function(require,module,exports){
(function (process){
// vim:ts=4:sts=4:sw=4:
/*!
*
* Copyright 2009-2012 Kris Kowal under the terms of the MIT
* license found at http://github.com/kriskowal/q/raw/master/LICENSE
*
* With parts by Tyler Close
* Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
* at http://www.opensource.org/licenses/mit-license.html
* Forked at ref_send.js version: 2009-05-11
*
* With parts by Mark Miller
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function (definition) {
"use strict";
// This file will function properly as a