Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
Merge branch 'chat-subject-new' of https://github.com/isymchych/jitsi-meet into jitsi-meet-new
damencho66212862cebf
diff --cc libs/lib-jitsi-meet.jsindex 3d5459695c,48e8bd5832..e41babff71--- a/libs/lib-jitsi-meet.js+++ b/libs/lib-jitsi-meet.js@@@ -1001,7 -1015,7 +1015,7 @@@ function setupListeners(conference)module.exports = JitsiConference;}).call(this,"/JitsiConference.js")- },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":131,"./service/authentication/AuthenticationEvents":133,"./service/xmpp/XMPPEvents":137,"events":51,"jitsi-meet-logger":79}],2:[function(require,module,exports){-},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":136,"./service/authentication/AuthenticationEvents":138,"./service/xmpp/XMPPEvents":142,"events":45,"jitsi-meet-logger":49}],2:[function(require,module,exports){++},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":133,"./service/authentication/AuthenticationEvents":135,"./service/xmpp/XMPPEvents":139,"events":46,"jitsi-meet-logger":50}],2:[function(require,module,exports){/*** Enumeration with the errors for the conference.* @type {{string: string}}@@@ -1428,7 -1437,7 +1446,7 @@@ window.Promise = window.Promise || requmodule.exports = LibJitsiMeet;- },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./modules/util/ScriptUtil":27,"./service/RTC/Resolutions":132,"es6-promise":72,"jitsi-meet-logger":79}],8:[function(require,module,exports){-},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./service/RTC/Resolutions":137,"es6-promise":47,"jitsi-meet-logger":49}],8:[function(require,module,exports){++},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./modules/util/ScriptUtil":27,"./service/RTC/Resolutions":134,"es6-promise":48,"jitsi-meet-logger":50}],8:[function(require,module,exports){/* global Strophe *//**@@@ -1652,7 -1661,7 +1670,7 @@@ JitsiDTMFManager.prototype.sendTones =};}).call(this,"/modules/DTMF/JitsiDTMFManager.js")- },{"jitsi-meet-logger":79}],12:[function(require,module,exports){-},{"jitsi-meet-logger":49}],12:[function(require,module,exports){++},{"jitsi-meet-logger":50}],12:[function(require,module,exports){(function (__filename){/* global config, APP, Strophe */@@@ -1876,7 -1885,7 +1894,7 @@@ module.exports = DataChannels}).call(this,"/modules/RTC/DataChannels.js")- },{"../../service/RTC/RTCEvents":131,"jitsi-meet-logger":79}],13:[function(require,module,exports){-},{"../../service/RTC/RTCEvents":136,"jitsi-meet-logger":49}],13:[function(require,module,exports){++},{"../../service/RTC/RTCEvents":133,"jitsi-meet-logger":50}],13:[function(require,module,exports){var JitsiTrack = require("./JitsiTrack");var RTCBrowserType = require("./RTCBrowserType");var JitsiTrackEvents = require('../../JitsiTrackEvents');@@@ -2401,7 -2402,7 +2419,7 @@@ JitsiTrack.prototype.setAudioLevel = fumodule.exports = JitsiTrack;- },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":51}],16:[function(require,module,exports){-},{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":45}],16:[function(require,module,exports){++},{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":46}],16:[function(require,module,exports){/* global APP */var EventEmitter = require("events");var RTCBrowserType = require("./RTCBrowserType");@@@ -2670,7 -2662,7 +2688,7 @@@ RTC.prototype.setAudioLevel = function}module.exports = RTC;- },{"../../service/RTC/MediaStreamTypes":130,"../../service/RTC/RTCEvents.js":131,"../../service/desktopsharing/DesktopSharingEventTypes":134,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":51}],17:[function(require,module,exports){-},{"../../service/RTC/MediaStreamTypes":135,"../../service/RTC/RTCEvents.js":136,"../../service/desktopsharing/DesktopSharingEventTypes":139,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":45}],17:[function(require,module,exports){++},{"../../service/RTC/MediaStreamTypes":132,"../../service/RTC/RTCEvents.js":133,"../../service/desktopsharing/DesktopSharingEventTypes":136,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":46}],17:[function(require,module,exports){var currentBrowser;@@@ -3663,7 -3655,7 +3681,7 @@@ var RTCUtils =module.exports = RTCUtils;}).call(this,"/modules/RTC/RTCUtils.js")- },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":131,"../../service/RTC/Resolutions":132,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":51,"jitsi-meet-logger":79}],19:[function(require,module,exports){-},{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":136,"../../service/RTC/Resolutions":137,"../xmpp/SDPUtil":33,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":45,"jitsi-meet-logger":49}],19:[function(require,module,exports){++},{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":133,"../../service/RTC/Resolutions":134,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":46,"jitsi-meet-logger":50}],19:[function(require,module,exports){(function (__filename){/* global chrome, $, alert *//* jshint -W003 */@@@ -4079,7 -4071,7 +4097,7 @@@ function initFirefoxExtensionDetection(module.exports = ScreenObtainer;}).call(this,"/modules/RTC/ScreenObtainer.js")- },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":134,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":79}],20:[function(require,module,exports){-},{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":139,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":49}],20:[function(require,module,exports){++},{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":136,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":50}],20:[function(require,module,exports){(function (__filename){/*! adapterjs - v0.12.3 - 2015-11-16 */var console = require("jitsi-meet-logger").getLogger(__filename);@@@ -5263,7 -5255,7 +5281,7 @@@ if (navigator.mozGetUserMedia)}}).call(this,"/modules/RTC/adapter.screenshare.js")- },{"jitsi-meet-logger":79}],21:[function(require,module,exports){-},{"jitsi-meet-logger":49}],21:[function(require,module,exports){++},{"jitsi-meet-logger":50}],21:[function(require,module,exports){(function (__filename){var logger = require("jitsi-meet-logger").getLogger(__filename);@@@ -5352,7 -5344,7 +5370,7 @@@ Settings.prototype.getCallStatsUserNammodule.exports = Settings;}).call(this,"/modules/settings/Settings.js")- },{"../util/UsernameGenerator":28,"jitsi-meet-logger":79}],22:[function(require,module,exports){-},{"../util/UsernameGenerator":27,"jitsi-meet-logger":49}],22:[function(require,module,exports){++},{"../util/UsernameGenerator":28,"jitsi-meet-logger":50}],22:[function(require,module,exports){(function (__filename){/* global $, Strophe, callstats */var logger = require("jitsi-meet-logger").getLogger(__filename);@@@ -5613,7 -5605,7 +5631,7 @@@ CallStats.sendAddIceCandidateFailed = _module.exports = CallStats;}).call(this,"/modules/statistics/CallStats.js")- },{"jitsi-meet-logger":79,"jssha":81,"socket.io-client":118}],23:[function(require,module,exports){-},{"jitsi-meet-logger":49,"jssha":50,"socket.io-client":85}],23:[function(require,module,exports){++},{"jitsi-meet-logger":50,"jssha":51,"socket.io-client":82}],23:[function(require,module,exports){/* global config *//*** Provides statistics for the local stream.@@@ -6470,7 -6462,7 +6488,7 @@@ StatsCollector.prototype.processAudioLe};}).call(this,"/modules/statistics/RTPStatsCollector.js")- },{"../../service/statistics/Events":135,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":79}],25:[function(require,module,exports){-},{"../../service/statistics/Events":140,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],25:[function(require,module,exports){++},{"../../service/statistics/Events":137,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],25:[function(require,module,exports){/* global require, APP */var LocalStats = require("./LocalStatsCollector.js");var RTPStats = require("./RTPStatsCollector.js");@@@ -6750,7 -6746,7 +6768,7 @@@ Statistics.LOCAL_JID = require("../../smodule.exports = Statistics;- },{"../../service/statistics/Events":135,"../../service/statistics/constants":136,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":51}],26:[function(require,module,exports){-},{"../../service/statistics/Events":140,"../../service/statistics/constants":141,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":45}],26:[function(require,module,exports){++},{"../../service/statistics/Events":137,"../../service/statistics/constants":138,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":46}],26:[function(require,module,exports){/**/*** @const@@@ -8118,7 -8065,7 +8135,7 @@@ ChatRoom.prototype.onMute = function (imodule.exports = ChatRoom;}).call(this,"/modules/xmpp/ChatRoom.js")- },{"../../service/xmpp/XMPPEvents":137,"./moderator":36,"./recording":37,"events":51,"jitsi-meet-logger":79}],30:[function(require,module,exports){-},{"../../service/xmpp/XMPPEvents":142,"./moderator":35,"./recording":36,"events":45,"jitsi-meet-logger":49}],29:[function(require,module,exports){++},{"../../service/xmpp/XMPPEvents":139,"./moderator":36,"./recording":37,"events":46,"jitsi-meet-logger":50}],30:[function(require,module,exports){(function (__filename){/** JingleSession provides an API to manage a single Jingle session. We will@@@ -8254,7 -8201,7 +8271,7 @@@ JingleSession.prototype.setAnswer = funmodule.exports = JingleSession;}).call(this,"/modules/xmpp/JingleSession.js")- },{"jitsi-meet-logger":79}],31:[function(require,module,exports){-},{"jitsi-meet-logger":49}],30:[function(require,module,exports){++},{"jitsi-meet-logger":50}],31:[function(require,module,exports){(function (__filename){/* jshint -W117 */@@@ -9917,7 -9864,7 +9934,7 @@@ JingleSessionPC.prototype.getIceConnectmodule.exports = JingleSessionPC;}).call(this,"/modules/xmpp/JingleSessionPC.js")- },{"../../service/xmpp/XMPPEvents":137,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":47,"jitsi-meet-logger":79,"sdp-transform":115}],32:[function(require,module,exports){-},{"../../service/xmpp/XMPPEvents":142,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":29,"./SDP":31,"./SDPDiffer":32,"./SDPUtil":33,"./TraceablePeerConnection":34,"async":44,"jitsi-meet-logger":49,"sdp-transform":82}],31:[function(require,module,exports){++},{"../../service/xmpp/XMPPEvents":139,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":45,"jitsi-meet-logger":50,"sdp-transform":79}],32:[function(require,module,exports){(function (__filename){/* jshint -W117 */@@@ -10568,7 -10515,7 +10585,7 @@@ SDP.prototype.jingle2media = function (module.exports = SDP;}).call(this,"/modules/xmpp/SDP.js")- },{"./SDPUtil":34,"jitsi-meet-logger":79}],33:[function(require,module,exports){-},{"./SDPUtil":33,"jitsi-meet-logger":49}],32:[function(require,module,exports){++},{"./SDPUtil":34,"jitsi-meet-logger":50}],33:[function(require,module,exports){var SDPUtil = require("./SDPUtil");function SDPDiffer(mySDP, otherSDP)@@@ -11105,7 -11052,7 +11122,7 @@@ SDPUtil =module.exports = SDPUtil;}).call(this,"/modules/xmpp/SDPUtil.js")- },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":79}],35:[function(require,module,exports){-},{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],34:[function(require,module,exports){++},{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],35:[function(require,module,exports){(function (__filename){/* global $ */var RTC = require('../RTC/RTC');@@@ -11612,7 -11559,7 +11629,7 @@@ TraceablePeerConnection.prototype.getStmodule.exports = TraceablePeerConnection;}).call(this,"/modules/xmpp/TraceablePeerConnection.js")- },{"../../service/xmpp/XMPPEvents":137,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":79,"sdp-interop":105,"sdp-simulcast":112,"sdp-transform":115}],36:[function(require,module,exports){-},{"../../service/xmpp/XMPPEvents":142,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":49,"sdp-interop":68,"sdp-simulcast":75,"sdp-transform":82}],35:[function(require,module,exports){++},{"../../service/xmpp/XMPPEvents":139,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":50,"sdp-interop":69,"sdp-simulcast":76,"sdp-transform":79}],36:[function(require,module,exports){(function (__filename){/* global $, $iq, Promise, Strophe */@@@ -12068,7 -12015,7 +12085,7 @@@ Moderator.prototype.logout = functionmodule.exports = Moderator;}).call(this,"/modules/xmpp/moderator.js")- },{"../../service/authentication/AuthenticationEvents":133,"../../service/xmpp/XMPPEvents":137,"jitsi-meet-logger":79}],37:[function(require,module,exports){-},{"../../service/authentication/AuthenticationEvents":138,"../../service/xmpp/XMPPEvents":142,"jitsi-meet-logger":49}],36:[function(require,module,exports){++},{"../../service/authentication/AuthenticationEvents":135,"../../service/xmpp/XMPPEvents":139,"jitsi-meet-logger":50}],37:[function(require,module,exports){(function (__filename){/* global $, $iq, config, connection, focusMucJid, messageHandler,Toolbar, Util, Promise */@@@ -12295,7 -12242,7 +12312,7 @@@ Recording.prototype.getURL = function (module.exports = Recording;}).call(this,"/modules/xmpp/recording.js")- },{"../../service/xmpp/XMPPEvents":137,"jitsi-meet-logger":79}],38:[function(require,module,exports){-},{"../../service/xmpp/XMPPEvents":142,"jitsi-meet-logger":49}],37:[function(require,module,exports){++},{"../../service/xmpp/XMPPEvents":139,"jitsi-meet-logger":50}],38:[function(require,module,exports){(function (__filename){/* jshint -W117 *//* a simple MUC connection plugin@@@ -12408,7 -12355,7 +12425,7 @@@ module.exports = function(XMPP)};}).call(this,"/modules/xmpp/strophe.emuc.js")- },{"./ChatRoom":29,"jitsi-meet-logger":79}],39:[function(require,module,exports){-},{"./ChatRoom":28,"jitsi-meet-logger":49}],38:[function(require,module,exports){++},{"./ChatRoom":29,"jitsi-meet-logger":50}],39:[function(require,module,exports){(function (__filename){/* jshint -W117 */@@@ -12705,7 -12652,7 +12722,7 @@@ module.exports = function(XMPP, eventEm}).call(this,"/modules/xmpp/strophe.jingle.js")- },{"../../service/xmpp/XMPPEvents":137,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":79}],40:[function(require,module,exports){-},{"../../service/xmpp/XMPPEvents":142,"../RTC/RTCBrowserType":17,"./JingleSessionPC":30,"jitsi-meet-logger":49}],39:[function(require,module,exports){++},{"../../service/xmpp/XMPPEvents":139,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":50}],40:[function(require,module,exports){/* global Strophe */module.exports = function () {@@@ -12853,7 -12800,7 +12870,7 @@@ module.exports = function (XMPP, eventE};}).call(this,"/modules/xmpp/strophe.ping.js")- },{"../../service/xmpp/XMPPEvents":137,"jitsi-meet-logger":79}],42:[function(require,module,exports){-},{"../../service/xmpp/XMPPEvents":142,"jitsi-meet-logger":49}],41:[function(require,module,exports){++},{"../../service/xmpp/XMPPEvents":139,"jitsi-meet-logger":50}],42:[function(require,module,exports){(function (__filename){/* jshint -W117 */var logger = require("jitsi-meet-logger").getLogger(__filename);@@@ -12970,7 -12917,7 +12987,7 @@@ module.exports = function()};}).call(this,"/modules/xmpp/strophe.rayo.js")- },{"jitsi-meet-logger":79}],43:[function(require,module,exports){-},{"jitsi-meet-logger":49}],42:[function(require,module,exports){++},{"jitsi-meet-logger":50}],43:[function(require,module,exports){(function (__filename){/* global Strophe *//**@@@ -13019,7 -12966,7 +13036,7 @@@ module.exports = function ()};}).call(this,"/modules/xmpp/strophe.util.js")- },{"jitsi-meet-logger":79}],44:[function(require,module,exports){-},{"jitsi-meet-logger":49}],43:[function(require,module,exports){++},{"jitsi-meet-logger":50}],44:[function(require,module,exports){(function (__filename){/* global $, APP, config, Strophe*/@@@ -13345,68 -13278,7 +13362,7 @@@ XMPP.prototype.disconnect = function (module.exports = XMPP;}).call(this,"/modules/xmpp/xmpp.js")- },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":131,"../../service/xmpp/XMPPEvents":137,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":51,"jitsi-meet-logger":79,"pako":84}],45:[function(require,module,exports){- module.exports = after-- function after(count, callback, err_cb) {- var bail = false- err_cb = err_cb || noop- proxy.count = count-- return (count === 0) ? callback() : proxy-- function proxy(err, result) {- if (proxy.count <= 0) {- throw new Error('after called too many times')- }- --proxy.count-- // after first error, rest are passed to err_cb- if (err) {- bail = true- callback(err)- // future error callbacks will go to error handler- callback = err_cb- } else if (proxy.count === 0 && !bail) {- callback(null, result)- }- }- }-- function noop() {}-- },{}],46:[function(require,module,exports){- /**- * An abstraction for slicing an arraybuffer even when- * ArrayBuffer.prototype.slice is not supported- *- * @api public- */-- module.exports = function(arraybuffer, start, end) {- var bytes = arraybuffer.byteLength;- start = start || 0;- end = end || bytes;-- if (arraybuffer.slice) { return arraybuffer.slice(start, end); }-- if (start < 0) { start += bytes; }- if (end < 0) { end += bytes; }- if (end > bytes) { end = bytes; }-- if (start >= bytes || start >= end || bytes === 0) {- return new ArrayBuffer(0);- }-- var abv = new Uint8Array(arraybuffer);- var result = new Uint8Array(end - start);- for (var i = start, ii = 0; i < end; i++, ii++) {- result[ii] = abv[i];- }- return result.buffer;- };-- },{}],47:[function(require,module,exports){-},{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":136,"../../service/xmpp/XMPPEvents":142,"../RTC/RTC":16,"./strophe.emuc":37,"./strophe.jingle":38,"./strophe.logger":39,"./strophe.ping":40,"./strophe.rayo":41,"./strophe.util":42,"events":45,"jitsi-meet-logger":49,"pako":51}],44:[function(require,module,exports){++},{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":133,"../../service/xmpp/XMPPEvents":139,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":46,"jitsi-meet-logger":50,"pako":52}],45:[function(require,module,exports){(function (process){/*!* async@@@ -14533,327 -14405,126 +14489,126 @@@}());}).call(this,require('_process'))- },{"_process":103}],48:[function(require,module,exports){-- /**- * Expose `Backoff`.- */-},{"_process":46}],45:[function(require,module,exports){++},{"_process":47}],46:[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 = Backoff;+ function EventEmitter() {+ this._events = this._events || {};+ this._maxListeners = this._maxListeners || undefined;+ }+ module.exports = EventEmitter;- /**- * Initialize backoff timer with `opts`.- *- * - `min` initial timeout in milliseconds [100]- * - `max` max timeout [10000]- * - `jitter` [0]- * - `factor` [2]- *- * @param {Object} opts- * @api public- */+ // Backwards-compat with node 0.10.x+ EventEmitter.EventEmitter = EventEmitter;- function Backoff(opts) {- opts = opts || {};- this.ms = opts.min || 100;- this.max = opts.max || 10000;- this.factor = opts.factor || 2;- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;- this.attempts = 0;- }+ EventEmitter.prototype._events = undefined;+ EventEmitter.prototype._maxListeners = undefined;- /**- * Return the backoff duration.- *- * @return {Number}- * @api public- */+ // 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;- Backoff.prototype.duration = function(){- var ms = this.ms * Math.pow(this.factor, this.attempts++);- if (this.jitter) {- var rand = Math.random();- var deviation = Math.floor(rand * this.jitter * ms);- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;- }- return Math.min(ms, this.max) | 0;+ // 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;};- /**- * Reset the number of attempts.- *- * @api public- */+ EventEmitter.prototype.emit = function(type) {+ var er, handler, len, args, i, listeners;- Backoff.prototype.reset = function(){- this.attempts = 0;- };+ if (!this._events)+ this._events = {};- /**- * Set the minimum duration- *- * @api public- */+ // 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.');+ }+ }- Backoff.prototype.setMin = function(min){- this.ms = min;- };+ handler = this._events[type];- /**- * Set the maximum duration- *- * @api public- */+ if (isUndefined(handler))+ return false;- Backoff.prototype.setMax = function(max){- this.max = max;- };+ 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];- /**- * Set the jitter- *- * @api public- */+ listeners = handler.slice();+ len = listeners.length;+ for (i = 0; i < len; i++)+ listeners[i].apply(this, args);+ }- Backoff.prototype.setJitter = function(jitter){- this.jitter = jitter;+ return true;};+ EventEmitter.prototype.addListener = function(type, listener) {+ var m;- },{}],49:[function(require,module,exports){- /*- * base64-arraybuffer- * https://github.com/niklasvh/base64-arraybuffer- *- * Copyright (c) 2012 Niklas von Hertzen- * Licensed under the MIT license.- */- (function(chars){- "use strict";+ if (!isFunction(listener))+ throw TypeError('listener must be a function');- exports.encode = function(arraybuffer) {- var bytes = new Uint8Array(arraybuffer),- i, len = bytes.length, base64 = "";+ if (!this._events)+ this._events = {};- for (i = 0; i < len; i+=3) {- base64 += chars[bytes[i] >> 2];- base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];- base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];- base64 += chars[bytes[i + 2] & 63];- }-- if ((len % 3) === 2) {- base64 = base64.substring(0, base64.length - 1) + "=";- } else if (len % 3 === 1) {- base64 = base64.substring(0, base64.length - 2) + "==";- }-- return base64;- };-- exports.decode = function(base64) {- var bufferLength = base64.length * 0.75,- len = base64.length, i, p = 0,- encoded1, encoded2, encoded3, encoded4;-- if (base64[base64.length - 1] === "=") {- bufferLength--;- if (base64[base64.length - 2] === "=") {- bufferLength--;- }- }-- var arraybuffer = new ArrayBuffer(bufferLength),- bytes = new Uint8Array(arraybuffer);-- for (i = 0; i < len; i+=4) {- encoded1 = chars.indexOf(base64[i]);- encoded2 = chars.indexOf(base64[i+1]);- encoded3 = chars.indexOf(base64[i+2]);- encoded4 = chars.indexOf(base64[i+3]);-- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);- }-- return arraybuffer;- };- })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");-- },{}],50:[function(require,module,exports){- (function (global){- /**- * Create a blob builder even when vendor prefixes exist- */-- var BlobBuilder = global.BlobBuilder- || global.WebKitBlobBuilder- || global.MSBlobBuilder- || global.MozBlobBuilder;-- /**- * Check if Blob constructor is supported- */-- var blobSupported = (function() {- try {- var b = new Blob(['hi']);- return b.size == 2;- } catch(e) {- return false;- }- })();-- /**- * Check if BlobBuilder is supported- */-- var blobBuilderSupported = BlobBuilder- && BlobBuilder.prototype.append- && BlobBuilder.prototype.getBlob;-- function BlobBuilderConstructor(ary, options) {- options = options || {};-- var bb = new BlobBuilder();- for (var i = 0; i < ary.length; i++) {- bb.append(ary[i]);- }- return (options.type) ? bb.getBlob(options.type) : bb.getBlob();- };-- module.exports = (function() {- if (blobSupported) {- return global.Blob;- } else if (blobBuilderSupported) {- return BlobBuilderConstructor;- } else {- return undefined;- }- })();-- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{}],51:[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);+ // 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.@@@ -15037,7125 -14708,6707 +14792,6707 @@@ function isUndefined(arg)return arg === void 0;}- },{}],52:[function(require,module,exports){- /**- * Slice reference.- */-- var slice = [].slice;-- /**- * Bind `obj` to `fn`.- *- * @param {Object} obj- * @param {Function|String} fn or string- * @return {Function}- * @api public- */-},{}],46:[function(require,module,exports){++},{}],47:[function(require,module,exports){+ // shim for using process in browser- module.exports = function(obj, fn){- if ('string' == typeof fn) fn = obj[fn];- if ('function' != typeof fn) throw new Error('bind() requires a function');- var args = slice.call(arguments, 2);- return function(){- return fn.apply(obj, args.concat(slice.call(arguments)));- }- };+ var process = module.exports = {};+ var queue = [];+ var draining = false;+ var currentQueue;+ var queueIndex = -1;- },{}],53:[function(require,module,exports){+ function cleanUpNextTick() {+ draining = false;+ if (currentQueue.length) {+ queue = currentQueue.concat(queue);+ } else {+ queueIndex = -1;+ }+ if (queue.length) {+ drainQueue();+ }+ }- /**- * Expose `Emitter`.- */-- module.exports = Emitter;+ function drainQueue() {+ if (draining) {+ return;+ }+ var timeout = setTimeout(cleanUpNextTick);+ draining = true;- /**- * Initialize a new `Emitter`.- *- * @api public- */+ var len = queue.length;+ while(len) {+ currentQueue = queue;+ queue = [];+ while (++queueIndex < len) {+ if (currentQueue) {+ currentQueue[queueIndex].run();+ }+ }+ queueIndex = -1;+ len = queue.length;+ }+ currentQueue = null;+ draining = false;+ clearTimeout(timeout);+ }- function Emitter(obj) {- if (obj) return mixin(obj);+ process.nextTick = function (fun) {+ var args = new Array(arguments.length - 1);+ if (arguments.length > 1) {+ for (var i = 1; i < arguments.length; i++) {+ args[i - 1] = arguments[i];+ }+ }+ queue.push(new Item(fun, args));+ if (queue.length === 1 && !draining) {+ setTimeout(drainQueue, 0);+ }};- /**- * Mixin the emitter properties.- *- * @param {Object} obj- * @return {Object}- * @api private- */-- function mixin(obj) {- for (var key in Emitter.prototype) {- obj[key] = Emitter.prototype[key];- }- return obj;+ // v8 likes predictible objects+ function Item(fun, array) {+ this.fun = fun;+ this.array = array;}-- /**- * Listen on the given `event` with `fn`.- *- * @param {String} event- * @param {Function} fn- * @return {Emitter}- * @api public- */-- Emitter.prototype.on =- Emitter.prototype.addEventListener = function(event, fn){- this._callbacks = this._callbacks || {};- (this._callbacks[event] = this._callbacks[event] || [])- .push(fn);- return this;+ Item.prototype.run = function () {+ this.fun.apply(null, this.array);};+ process.title = 'browser';+ process.browser = true;+ process.env = {};+ process.argv = [];+ process.version = ''; // empty string to avoid regexp issues+ process.versions = {};- /**- * Adds an `event` listener that will be invoked a single- * time then automatically removed.- *- * @param {String} event- * @param {Function} fn- * @return {Emitter}- * @api public- */+ function noop() {}- Emitter.prototype.once = function(event, fn){- var self = this;- this._callbacks = this._callbacks || {};+ process.on = noop;+ process.addListener = noop;+ process.once = noop;+ process.off = noop;+ process.removeListener = noop;+ process.removeAllListeners = noop;+ process.emit = noop;- function on() {- self.off(event, on);- fn.apply(this, arguments);- }+ process.binding = function (name) {+ throw new Error('process.binding is not supported');+ };- on.fn = fn;- this.on(event, on);- return this;+ process.cwd = function () { return '/' };+ process.chdir = function (dir) {+ throw new Error('process.chdir is not supported');};+ process.umask = function() { return 0; };- /**- * Remove the given callback for `event` or all- * registered callbacks.- *- * @param {String} event- * @param {Function} fn- * @return {Emitter}- * @api public-},{}],47:[function(require,module,exports){++},{}],48:[function(require,module,exports){+ (function (process,global){+ /*!+ * @overview es6-promise - a tiny implementation of Promises/A+.+ * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)+ * @license Licensed under MIT license+ * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE+ * @version 3.0.2*/- Emitter.prototype.off =- Emitter.prototype.removeListener =- Emitter.prototype.removeAllListeners =- Emitter.prototype.removeEventListener = function(event, fn){- this._callbacks = this._callbacks || {};-- // all- if (0 == arguments.length) {- this._callbacks = {};- return this;- }+ (function() {+ "use strict";+ function lib$es6$promise$utils$$objectOrFunction(x) {+ return typeof x === 'function' || (typeof x === 'object' && x !== null);+ }- // specific event- var callbacks = this._callbacks[event];- if (!callbacks) return this;+ function lib$es6$promise$utils$$isFunction(x) {+ return typeof x === 'function';+ }- // remove all handlers- if (1 == arguments.length) {- delete this._callbacks[event];- return this;- }+ function lib$es6$promise$utils$$isMaybeThenable(x) {+ return typeof x === 'object' && x !== null;+ }- // remove specific handler- var cb;- for (var i = 0; i < callbacks.length; i++) {- cb = callbacks[i];- if (cb === fn || cb.fn === fn) {- callbacks.splice(i, 1);- break;+ var lib$es6$promise$utils$$_isArray;+ if (!Array.isArray) {+ lib$es6$promise$utils$$_isArray = function (x) {+ return Object.prototype.toString.call(x) === '[object Array]';+ };+ } else {+ lib$es6$promise$utils$$_isArray = Array.isArray;}- }- return this;- };- /**- * Emit `event` with the given args.- *- * @param {String} event- * @param {Mixed} ...- * @return {Emitter}- */+ var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;+ var lib$es6$promise$asap$$len = 0;+ var lib$es6$promise$asap$$toString = {}.toString;+ var lib$es6$promise$asap$$vertxNext;+ var lib$es6$promise$asap$$customSchedulerFn;- Emitter.prototype.emit = function(event){- this._callbacks = this._callbacks || {};- var args = [].slice.call(arguments, 1)- , callbacks = this._callbacks[event];+ var lib$es6$promise$asap$$asap = function asap(callback, arg) {+ lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;+ lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;+ lib$es6$promise$asap$$len += 2;+ if (lib$es6$promise$asap$$len === 2) {+ // If len is 2, that means that we need to schedule an async flush.+ // If additional callbacks are queued before the queue is flushed, they+ // will be processed by this flush that we are scheduling.+ if (lib$es6$promise$asap$$customSchedulerFn) {+ lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);+ } else {+ lib$es6$promise$asap$$scheduleFlush();+ }+ }+ }- if (callbacks) {- callbacks = callbacks.slice(0);- for (var i = 0, len = callbacks.length; i < len; ++i) {- callbacks[i].apply(this, args);+ function lib$es6$promise$asap$$setScheduler(scheduleFn) {+ lib$es6$promise$asap$$customSchedulerFn = scheduleFn;}- }- return this;- };+ function lib$es6$promise$asap$$setAsap(asapFn) {+ lib$es6$promise$asap$$asap = asapFn;+ }- /**- * Return array of callbacks for `event`.- *- * @param {String} event- * @return {Array}- * @api public- */+ var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;+ var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};+ var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;+ var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';- Emitter.prototype.listeners = function(event){- this._callbacks = this._callbacks || {};- return this._callbacks[event] || [];- };+ // test for web worker but not in IE10+ var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&+ typeof importScripts !== 'undefined' &&+ typeof MessageChannel !== 'undefined';- /**- * Check if this emitter has `event` handlers.- *- * @param {String} event- * @return {Boolean}- * @api public- */+ // node+ function lib$es6$promise$asap$$useNextTick() {+ // node version 0.10.x displays a deprecation warning when nextTick is used recursively+ // see https://github.com/cujojs/when/issues/410 for details+ return function() {+ process.nextTick(lib$es6$promise$asap$$flush);+ };+ }- Emitter.prototype.hasListeners = function(event){- return !! this.listeners(event).length;- };-- },{}],54:[function(require,module,exports){+ // vertx+ function lib$es6$promise$asap$$useVertxTimer() {+ return function() {+ lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);+ };+ }- module.exports = function(a, b){- var fn = function(){};- fn.prototype = b.prototype;- a.prototype = new fn;- a.prototype.constructor = a;- };- },{}],55:[function(require,module,exports){+ function lib$es6$promise$asap$$useMutationObserver() {+ var iterations = 0;+ var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);+ var node = document.createTextNode('');+ observer.observe(node, { characterData: true });- /**- * Expose `debug()` as the module.- */+ return function() {+ node.data = (iterations = ++iterations % 2);+ };+ }- module.exports = debug;+ // web worker+ function lib$es6$promise$asap$$useMessageChannel() {+ var channel = new MessageChannel();+ channel.port1.onmessage = lib$es6$promise$asap$$flush;+ return function () {+ channel.port2.postMessage(0);+ };+ }- /**- * Create a debugger with the given `name`.- *- * @param {String} name- * @return {Type}- * @api public- */+ function lib$es6$promise$asap$$useSetTimeout() {+ return function() {+ setTimeout(lib$es6$promise$asap$$flush, 1);+ };+ }- function debug(name) {- if (!debug.enabled(name)) return function(){};+ var lib$es6$promise$asap$$queue = new Array(1000);+ function lib$es6$promise$asap$$flush() {+ for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {+ var callback = lib$es6$promise$asap$$queue[i];+ var arg = lib$es6$promise$asap$$queue[i+1];- return function(fmt){- fmt = coerce(fmt);+ callback(arg);- var curr = new Date;- var ms = curr - (debug[name] || curr);- debug[name] = curr;+ lib$es6$promise$asap$$queue[i] = undefined;+ lib$es6$promise$asap$$queue[i+1] = undefined;+ }- fmt = name- + ' '- + fmt- + ' +' + debug.humanize(ms);+ lib$es6$promise$asap$$len = 0;+ }- // This hackery is required for IE8- // where `console.log` doesn't have 'apply'- window.console- && console.log- && Function.prototype.apply.call(console.log, console, arguments);- }- }+ function lib$es6$promise$asap$$attemptVertx() {+ try {+ var r = require;+ var vertx = r('vertx');+ lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;+ return lib$es6$promise$asap$$useVertxTimer();+ } catch(e) {+ return lib$es6$promise$asap$$useSetTimeout();+ }+ }- /**- * The currently active debug mode names.- */+ var lib$es6$promise$asap$$scheduleFlush;+ // Decide what async method to use to triggering processing of queued callbacks:+ if (lib$es6$promise$asap$$isNode) {+ lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();+ } else if (lib$es6$promise$asap$$BrowserMutationObserver) {+ lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();+ } else if (lib$es6$promise$asap$$isWorker) {+ lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();+ } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {+ lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();+ } else {+ lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();+ }- debug.names = [];- debug.skips = [];+ function lib$es6$promise$$internal$$noop() {}- /**- * Enables a debug mode by name. This can include modes- * separated by a colon and wildcards.- *- * @param {String} name- * @api public- */+ var lib$es6$promise$$internal$$PENDING = void 0;+ var lib$es6$promise$$internal$$FULFILLED = 1;+ var lib$es6$promise$$internal$$REJECTED = 2;- debug.enable = function(name) {- try {- localStorage.debug = name;- } catch(e){}+ var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();- var split = (name || '').split(/[\s,]+/)- , len = split.length;+ function lib$es6$promise$$internal$$selfFulfillment() {+ return new TypeError("You cannot resolve a promise with itself");+ }- for (var i = 0; i < len; i++) {- name = split[i].replace('*', '.*?');- if (name[0] === '-') {- debug.skips.push(new RegExp('^' + name.substr(1) + '$'));+ function lib$es6$promise$$internal$$cannotReturnOwn() {+ return new TypeError('A promises callback cannot return that same promise.');}- else {- debug.names.push(new RegExp('^' + name + '$'));++ function lib$es6$promise$$internal$$getThen(promise) {+ try {+ return promise.then;+ } catch(error) {+ lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;+ return lib$es6$promise$$internal$$GET_THEN_ERROR;+ }}- }- };- /**- * Disable debug output.- *- * @api public- */+ function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {+ try {+ then.call(value, fulfillmentHandler, rejectionHandler);+ } catch(e) {+ return e;+ }+ }- debug.disable = function(){- debug.enable('');- };+ function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {+ lib$es6$promise$asap$$asap(function(promise) {+ var sealed = false;+ var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {+ if (sealed) { return; }+ sealed = true;+ if (thenable !== value) {+ lib$es6$promise$$internal$$resolve(promise, value);+ } else {+ lib$es6$promise$$internal$$fulfill(promise, value);+ }+ }, function(reason) {+ if (sealed) { return; }+ sealed = true;- /**- * Humanize the given `ms`.- *- * @param {Number} m- * @return {String}- * @api private- */+ lib$es6$promise$$internal$$reject(promise, reason);+ }, 'Settle: ' + (promise._label || ' unknown promise'));- debug.humanize = function(ms) {- var sec = 1000- , min = 60 * 1000- , hour = 60 * min;+ if (!sealed && error) {+ sealed = true;+ lib$es6$promise$$internal$$reject(promise, error);+ }+ }, promise);+ }- if (ms >= hour) return (ms / hour).toFixed(1) + 'h';- if (ms >= min) return (ms / min).toFixed(1) + 'm';- if (ms >= sec) return (ms / sec | 0) + 's';- return ms + 'ms';- };+ function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {+ if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {+ lib$es6$promise$$internal$$fulfill(promise, thenable._result);+ } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {+ lib$es6$promise$$internal$$reject(promise, thenable._result);+ } else {+ lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {+ lib$es6$promise$$internal$$resolve(promise, value);+ }, function(reason) {+ lib$es6$promise$$internal$$reject(promise, reason);+ });+ }+ }- /**- * Returns true if the given mode name is enabled, false otherwise.- *- * @param {String} name- * @return {Boolean}- * @api public- */+ function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {+ if (maybeThenable.constructor === promise.constructor) {+ lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);+ } else {+ var then = lib$es6$promise$$internal$$getThen(maybeThenable);- debug.enabled = function(name) {- for (var i = 0, len = debug.skips.length; i < len; i++) {- if (debug.skips[i].test(name)) {- return false;+ if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {+ lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);+ } else if (then === undefined) {+ lib$es6$promise$$internal$$fulfill(promise, maybeThenable);+ } else if (lib$es6$promise$utils$$isFunction(then)) {+ lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);+ } else {+ lib$es6$promise$$internal$$fulfill(promise, maybeThenable);+ }+ }}- }- for (var i = 0, len = debug.names.length; i < len; i++) {- if (debug.names[i].test(name)) {- return true;++ function lib$es6$promise$$internal$$resolve(promise, value) {+ if (promise === value) {+ lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());+ } else if (lib$es6$promise$utils$$objectOrFunction(value)) {+ lib$es6$promise$$internal$$handleMaybeThenable(promise, value);+ } else {+ lib$es6$promise$$internal$$fulfill(promise, value);+ }}- }- return false;- };- /**- * Coerce `val`.- */-- function coerce(val) {- if (val instanceof Error) return val.stack || val.message;- return val;- }-- // persist-- try {- if (window.localStorage) debug.enable(localStorage.debug);- } catch(e){}-- },{}],56:[function(require,module,exports){-- module.exports = require('./lib/');+ function lib$es6$promise$$internal$$publishRejection(promise) {+ if (promise._onerror) {+ promise._onerror(promise._result);+ }- },{"./lib/":57}],57:[function(require,module,exports){+ lib$es6$promise$$internal$$publish(promise);+ }- module.exports = require('./socket');+ function lib$es6$promise$$internal$$fulfill(promise, value) {+ if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }- /**- * Exports parser- *- * @api public- *- */- module.exports.parser = require('engine.io-parser');+ promise._result = value;+ promise._state = lib$es6$promise$$internal$$FULFILLED;- },{"./socket":58,"engine.io-parser":69}],58:[function(require,module,exports){- (function (global){- /**- * Module dependencies.- */+ if (promise._subscribers.length !== 0) {+ lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);+ }+ }- var transports = require('./transports');- var Emitter = require('component-emitter');- var debug = require('debug')('engine.io-client:socket');- var index = require('indexof');- var parser = require('engine.io-parser');- var parseuri = require('parseuri');- var parsejson = require('parsejson');- var parseqs = require('parseqs');+ function lib$es6$promise$$internal$$reject(promise, reason) {+ if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }+ promise._state = lib$es6$promise$$internal$$REJECTED;+ promise._result = reason;- /**- * Module exports.- */+ lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);+ }- module.exports = Socket;+ function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {+ var subscribers = parent._subscribers;+ var length = subscribers.length;- /**- * Noop function.- *- * @api private- */+ parent._onerror = null;- function noop(){}+ subscribers[length] = child;+ subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;+ subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;- /**- * Socket constructor.- *- * @param {String|Object} uri or options- * @param {Object} options- * @api public- */+ if (length === 0 && parent._state) {+ lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);+ }+ }- function Socket(uri, opts){- if (!(this instanceof Socket)) return new Socket(uri, opts);+ function lib$es6$promise$$internal$$publish(promise) {+ var subscribers = promise._subscribers;+ var settled = promise._state;- opts = opts || {};+ if (subscribers.length === 0) { return; }- if (uri && 'object' == typeof uri) {- opts = uri;- uri = null;- }+ var child, callback, detail = promise._result;- if (uri) {- uri = parseuri(uri);- opts.host = uri.host;- opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';- opts.port = uri.port;- if (uri.query) opts.query = uri.query;- }+ for (var i = 0; i < subscribers.length; i += 3) {+ child = subscribers[i];+ callback = subscribers[i + settled];- this.secure = null != opts.secure ? opts.secure :- (global.location && 'https:' == location.protocol);+ if (child) {+ lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);+ } else {+ callback(detail);+ }+ }- if (opts.host) {- var pieces = opts.host.split(':');- opts.hostname = pieces.shift();- if (pieces.length) {- opts.port = pieces.pop();- } else if (!opts.port) {- // if no port is specified manually, use the protocol default- opts.port = this.secure ? '443' : '80';+ promise._subscribers.length = 0;}- }- this.agent = opts.agent || false;- this.hostname = opts.hostname ||- (global.location ? location.hostname : 'localhost');- this.port = opts.port || (global.location && location.port ?- location.port :- (this.secure ? 443 : 80));- this.query = opts.query || {};- if ('string' == typeof this.query) this.query = parseqs.decode(this.query);- this.upgrade = false !== opts.upgrade;- this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';- this.forceJSONP = !!opts.forceJSONP;- this.jsonp = false !== opts.jsonp;- this.forceBase64 = !!opts.forceBase64;- this.enablesXDR = !!opts.enablesXDR;- this.timestampParam = opts.timestampParam || 't';- this.timestampRequests = opts.timestampRequests;- this.transports = opts.transports || ['polling', 'websocket'];- this.readyState = '';- this.writeBuffer = [];- this.callbackBuffer = [];- this.policyPort = opts.policyPort || 843;- this.rememberUpgrade = opts.rememberUpgrade || false;- this.binaryType = null;- this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;+ function lib$es6$promise$$internal$$ErrorObject() {+ this.error = null;+ }- // SSL options for Node.js client- this.pfx = opts.pfx || null;- this.key = opts.key || null;- this.passphrase = opts.passphrase || null;- this.cert = opts.cert || null;- this.ca = opts.ca || null;- this.ciphers = opts.ciphers || null;- this.rejectUnauthorized = opts.rejectUnauthorized || null;+ var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();- this.open();- }+ function lib$es6$promise$$internal$$tryCatch(callback, detail) {+ try {+ return callback(detail);+ } catch(e) {+ lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;+ return lib$es6$promise$$internal$$TRY_CATCH_ERROR;+ }+ }- Socket.priorWebsocketSuccess = false;+ function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {+ var hasCallback = lib$es6$promise$utils$$isFunction(callback),+ value, error, succeeded, failed;- /**- * Mix in `Emitter`.- */+ if (hasCallback) {+ value = lib$es6$promise$$internal$$tryCatch(callback, detail);- Emitter(Socket.prototype);+ if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {+ failed = true;+ error = value.error;+ value = null;+ } else {+ succeeded = true;+ }- /**- * Protocol version.- *- * @api public- */+ if (promise === value) {+ lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());+ return;+ }- Socket.protocol = parser.protocol; // this is an int+ } else {+ value = detail;+ succeeded = true;+ }- /**- * Expose deps for legacy compatibility- * and standalone browser access.- */+ if (promise._state !== lib$es6$promise$$internal$$PENDING) {+ // noop+ } else if (hasCallback && succeeded) {+ lib$es6$promise$$internal$$resolve(promise, value);+ } else if (failed) {+ lib$es6$promise$$internal$$reject(promise, error);+ } else if (settled === lib$es6$promise$$internal$$FULFILLED) {+ lib$es6$promise$$internal$$fulfill(promise, value);+ } else if (settled === lib$es6$promise$$internal$$REJECTED) {+ lib$es6$promise$$internal$$reject(promise, value);+ }+ }- Socket.Socket = Socket;- Socket.Transport = require('./transport');- Socket.transports = require('./transports');- Socket.parser = require('engine.io-parser');+ function lib$es6$promise$$internal$$initializePromise(promise, resolver) {+ try {+ resolver(function resolvePromise(value){+ lib$es6$promise$$internal$$resolve(promise, value);+ }, function rejectPromise(reason) {+ lib$es6$promise$$internal$$reject(promise, reason);+ });+ } catch(e) {+ lib$es6$promise$$internal$$reject(promise, e);+ }+ }- /**- * Creates transport of the given type.- *- * @param {String} transport name- * @return {Transport}- * @api private- */+ function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {+ var enumerator = this;- Socket.prototype.createTransport = function (name) {- debug('creating transport "%s"', name);- var query = clone(this.query);+ enumerator._instanceConstructor = Constructor;+ enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);- // append engine.io protocol identifier- query.EIO = parser.protocol;+ if (enumerator._validateInput(input)) {+ enumerator._input = input;+ enumerator.length = input.length;+ enumerator._remaining = input.length;- // transport name- query.transport = name;+ enumerator._init();- // session id if we already have one- if (this.id) query.sid = this.id;+ if (enumerator.length === 0) {+ lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);+ } else {+ enumerator.length = enumerator.length || 0;+ enumerator._enumerate();+ if (enumerator._remaining === 0) {+ lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);+ }+ }+ } else {+ lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());+ }+ }- var transport = new transports[name]({- agent: this.agent,- hostname: this.hostname,- port: this.port,- secure: this.secure,- path: this.path,- query: query,- forceJSONP: this.forceJSONP,- jsonp: this.jsonp,- forceBase64: this.forceBase64,- enablesXDR: this.enablesXDR,- timestampRequests: this.timestampRequests,- timestampParam: this.timestampParam,- policyPort: this.policyPort,- socket: this,- pfx: this.pfx,- key: this.key,- passphrase: this.passphrase,- cert: this.cert,- ca: this.ca,- ciphers: this.ciphers,- rejectUnauthorized: this.rejectUnauthorized- });+ lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {+ return lib$es6$promise$utils$$isArray(input);+ };- return transport;- };+ lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {+ return new Error('Array Methods must be provided an Array');+ };- function clone (obj) {- var o = {};- for (var i in obj) {- if (obj.hasOwnProperty(i)) {- o[i] = obj[i];- }- }- return o;- }+ lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {+ this._result = new Array(this.length);+ };- /**- * Initializes transport to use and starts probe.- *- * @api private- */- Socket.prototype.open = function () {- var transport;- if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {- transport = 'websocket';- } else if (0 == this.transports.length) {- // Emit error on next tick so it can be listened to- var self = this;- setTimeout(function() {- self.emit('error', 'No transports available');- }, 0);- return;- } else {- transport = this.transports[0];- }- this.readyState = 'opening';+ var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;- // Retry with the next transport if the transport is disabled (jsonp: false)- var transport;- try {- transport = this.createTransport(transport);- } catch (e) {- this.transports.shift();- this.open();- return;- }+ lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {+ var enumerator = this;- transport.open();- this.setTransport(transport);- };+ var length = enumerator.length;+ var promise = enumerator.promise;+ var input = enumerator._input;- /**- * Sets the current transport. Disables the existing one (if any).- *- * @api private- */+ for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {+ enumerator._eachEntry(input[i], i);+ }+ };- Socket.prototype.setTransport = function(transport){- debug('setting transport %s', transport.name);- var self = this;+ lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {+ var enumerator = this;+ var c = enumerator._instanceConstructor;- if (this.transport) {- debug('clearing existing transport %s', this.transport.name);- this.transport.removeAllListeners();- }+ if (lib$es6$promise$utils$$isMaybeThenable(entry)) {+ if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {+ entry._onerror = null;+ enumerator._settledAt(entry._state, i, entry._result);+ } else {+ enumerator._willSettleAt(c.resolve(entry), i);+ }+ } else {+ enumerator._remaining--;+ enumerator._result[i] = entry;+ }+ };- // set up transport- this.transport = transport;+ lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {+ var enumerator = this;+ var promise = enumerator.promise;- // set up transport listeners- transport- .on('drain', function(){- self.onDrain();- })- .on('packet', function(packet){- self.onPacket(packet);- })- .on('error', function(e){- self.onError(e);- })- .on('close', function(){- self.onClose('transport close');- });- };+ if (promise._state === lib$es6$promise$$internal$$PENDING) {+ enumerator._remaining--;- /**- * Probes a transport.- *- * @param {String} transport name- * @api private- */+ if (state === lib$es6$promise$$internal$$REJECTED) {+ lib$es6$promise$$internal$$reject(promise, value);+ } else {+ enumerator._result[i] = value;+ }+ }- Socket.prototype.probe = function (name) {- debug('probing transport "%s"', name);- var transport = this.createTransport(name, { probe: 1 })- , failed = false- , self = this;+ if (enumerator._remaining === 0) {+ lib$es6$promise$$internal$$fulfill(promise, enumerator._result);+ }+ };- Socket.priorWebsocketSuccess = false;+ lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {+ var enumerator = this;- function onTransportOpen(){- if (self.onlyBinaryUpgrades) {- var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;- failed = failed || upgradeLosesBinary;+ lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {+ enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);+ }, function(reason) {+ enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);+ });+ };+ function lib$es6$promise$promise$all$$all(entries) {+ return new lib$es6$promise$enumerator$$default(this, entries).promise;}- if (failed) return;-- debug('probe transport "%s" opened', name);- transport.send([{ type: 'ping', data: 'probe' }]);- transport.once('packet', function (msg) {- if (failed) return;- if ('pong' == msg.type && 'probe' == msg.data) {- debug('probe transport "%s" pong', name);- self.upgrading = true;- self.emit('upgrading', transport);- if (!transport) return;- Socket.priorWebsocketSuccess = 'websocket' == transport.name;-- debug('pausing current transport "%s"', self.transport.name);- self.transport.pause(function () {- if (failed) return;- if ('closed' == self.readyState) return;- debug('changing transport and sending upgrade packet');+ var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;+ function lib$es6$promise$promise$race$$race(entries) {+ /*jshint validthis:true */+ var Constructor = this;- cleanup();+ var promise = new Constructor(lib$es6$promise$$internal$$noop);- self.setTransport(transport);- transport.send([{ type: 'upgrade' }]);- self.emit('upgrade', transport);- transport = null;- self.upgrading = false;- self.flush();- });- } else {- debug('probe transport "%s" failed', name);- var err = new Error('probe error');- err.transport = transport.name;- self.emit('upgradeError', err);+ if (!lib$es6$promise$utils$$isArray(entries)) {+ lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));+ return promise;}- });- }- function freezeTransport() {- if (failed) return;+ var length = entries.length;- // Any callback called by transport should be ignored since now- failed = true;+ function onFulfillment(value) {+ lib$es6$promise$$internal$$resolve(promise, value);+ }- cleanup();+ function onRejection(reason) {+ lib$es6$promise$$internal$$reject(promise, reason);+ }- transport.close();- transport = null;- }+ for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {+ lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);+ }- //Handle any error that happens while probing- function onerror(err) {- var error = new Error('probe error: ' + err);- error.transport = transport.name;+ return promise;+ }+ var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;+ function lib$es6$promise$promise$resolve$$resolve(object) {+ /*jshint validthis:true */+ var Constructor = this;- freezeTransport();+ if (object && typeof object === 'object' && object.constructor === Constructor) {+ return object;+ }- debug('probe transport "%s" failed because of error: %s', name, err);-- self.emit('upgradeError', error);- }+ var promise = new Constructor(lib$es6$promise$$internal$$noop);+ lib$es6$promise$$internal$$resolve(promise, object);+ return promise;+ }+ var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;+ function lib$es6$promise$promise$reject$$reject(reason) {+ /*jshint validthis:true */+ var Constructor = this;+ var promise = new Constructor(lib$es6$promise$$internal$$noop);+ lib$es6$promise$$internal$$reject(promise, reason);+ return promise;+ }+ var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;- function onTransportClose(){- onerror("transport closed");- }+ var lib$es6$promise$promise$$counter = 0;- //When the socket is closed while we're probing- function onclose(){- onerror("socket closed");- }+ function lib$es6$promise$promise$$needsResolver() {+ throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');+ }- //When the socket is upgraded while we're probing- function onupgrade(to){- if (transport && to.name != transport.name) {- debug('"%s" works - aborting "%s"', to.name, transport.name);- freezeTransport();+ function lib$es6$promise$promise$$needsNew() {+ throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");}- }- //Remove all listeners on the transport and on self- function cleanup(){- transport.removeListener('open', onTransportOpen);- transport.removeListener('error', onerror);- transport.removeListener('close', onTransportClose);- self.removeListener('close', onclose);- self.removeListener('upgrading', onupgrade);- }+ var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;+ /**+ Promise objects represent the eventual result of an asynchronous operation. The+ primary way of interacting with a promise is through its `then` method, which+ registers callbacks to receive either a promise's eventual value or the reason+ why the promise cannot be fulfilled.- transport.once('open', onTransportOpen);- transport.once('error', onerror);- transport.once('close', onTransportClose);+ Terminology+ ------------ this.once('close', onclose);- this.once('upgrading', onupgrade);+ - `promise` is an object or function with a `then` method whose behavior conforms to this specification.+ - `thenable` is an object or function that defines a `then` method.+ - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).+ - `exception` is a value that is thrown using the throw statement.+ - `reason` is a value that indicates why a promise was rejected.+ - `settled` the final resting state of a promise, fulfilled or rejected.- transport.open();+ A promise can be in one of three states: pending, fulfilled, or rejected.- };+ Promises that are fulfilled have a fulfillment value and are in the fulfilled+ state. Promises that are rejected have a rejection reason and are in the+ rejected state. A fulfillment value is never a thenable.- /**- * Called when connection is deemed open.- *- * @api public- */+ Promises can also be said to *resolve* a value. If this value is also a+ promise, then the original promise's settled state will match the value's+ settled state. So a promise that *resolves* a promise that rejects will+ itself reject, and a promise that *resolves* a promise that fulfills will+ itself fulfill.- Socket.prototype.onOpen = function () {- debug('socket open');- this.readyState = 'open';- Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;- this.emit('open');- this.flush();- // we check for `readyState` in case an `open`- // listener already closed the socket- if ('open' == this.readyState && this.upgrade && this.transport.pause) {- debug('starting upgrade probes');- for (var i = 0, l = this.upgrades.length; i < l; i++) {- this.probe(this.upgrades[i]);- }- }- };+ Basic Usage:+ ------------- /**- * Handles a packet.- *- * @api private- */+ ```js+ var promise = new Promise(function(resolve, reject) {+ // on success+ resolve(value);- Socket.prototype.onPacket = function (packet) {- if ('opening' == this.readyState || 'open' == this.readyState) {- debug('socket receive: type "%s", data "%s"', packet.type, packet.data);+ // on failure+ reject(reason);+ });- this.emit('packet', packet);+ promise.then(function(value) {+ // on fulfillment+ }, function(reason) {+ // on rejection+ });+ ```- // Socket is live - any packet counts- this.emit('heartbeat');+ Advanced Usage:+ ---------------- switch (packet.type) {- case 'open':- this.onHandshake(parsejson(packet.data));- break;+ Promises shine when abstracting away asynchronous interactions such as+ `XMLHttpRequest`s.- case 'pong':- this.setPing();- break;+ ```js+ function getJSON(url) {+ return new Promise(function(resolve, reject){+ var xhr = new XMLHttpRequest();- case 'error':- var err = new Error('server error');- err.code = packet.data;- this.emit('error', err);- break;+ xhr.open('GET', url);+ xhr.onreadystatechange = handler;+ xhr.responseType = 'json';+ xhr.setRequestHeader('Accept', 'application/json');+ xhr.send();- case 'message':- this.emit('data', packet.data);- this.emit('message', packet.data);- break;- }- } else {- debug('packet received with socket readyState "%s"', this.readyState);- }- };+ function handler() {+ if (this.readyState === this.DONE) {+ if (this.status === 200) {+ resolve(this.response);+ } else {+ reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));+ }+ }+ };+ });+ }- /**- * Called upon handshake completion.- *- * @param {Object} handshake obj- * @api private- */+ getJSON('/posts.json').then(function(json) {+ // on fulfillment+ }, function(reason) {+ // on rejection+ });+ ```- Socket.prototype.onHandshake = function (data) {- this.emit('handshake', data);- this.id = data.sid;- this.transport.query.sid = data.sid;- this.upgrades = this.filterUpgrades(data.upgrades);- this.pingInterval = data.pingInterval;- this.pingTimeout = data.pingTimeout;- this.onOpen();- // In case open handler closes socket- if ('closed' == this.readyState) return;- this.setPing();+ Unlike callbacks, promises are great composable primitives.- // Prolong liveness of socket on heartbeat- this.removeListener('heartbeat', this.onHeartbeat);- this.on('heartbeat', this.onHeartbeat);- };+ ```js+ Promise.all([+ getJSON('/posts'),+ getJSON('/comments')+ ]).then(function(values){+ values[0] // => postsJSON+ values[1] // => commentsJSON- /**- * Resets ping timeout.- *- * @api private- */+ return values;+ });+ ```- Socket.prototype.onHeartbeat = function (timeout) {- clearTimeout(this.pingTimeoutTimer);- var self = this;- self.pingTimeoutTimer = setTimeout(function () {- if ('closed' == self.readyState) return;- self.onClose('ping timeout');- }, timeout || (self.pingInterval + self.pingTimeout));- };+ @class Promise+ @param {function} resolver+ Useful for tooling.+ @constructor+ */+ function lib$es6$promise$promise$$Promise(resolver) {+ this._id = lib$es6$promise$promise$$counter++;+ this._state = undefined;+ this._result = undefined;+ this._subscribers = [];- /**- * Pings server every `this.pingInterval` and expects response- * within `this.pingTimeout` or closes connection.- *- * @api private- */+ if (lib$es6$promise$$internal$$noop !== resolver) {+ if (!lib$es6$promise$utils$$isFunction(resolver)) {+ lib$es6$promise$promise$$needsResolver();+ }- Socket.prototype.setPing = function () {- var self = this;- clearTimeout(self.pingIntervalTimer);- self.pingIntervalTimer = setTimeout(function () {- debug('writing ping packet - expecting pong within %sms', self.pingTimeout);- self.ping();- self.onHeartbeat(self.pingTimeout);- }, self.pingInterval);- };+ if (!(this instanceof lib$es6$promise$promise$$Promise)) {+ lib$es6$promise$promise$$needsNew();+ }- /**- * Sends a ping packet.- *- * @api public- */+ lib$es6$promise$$internal$$initializePromise(this, resolver);+ }+ }- Socket.prototype.ping = function () {- this.sendPacket('ping');- };+ lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;+ lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;+ lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;+ lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;+ lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;+ lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;+ lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;- /**- * Called on `drain` event- *- * @api private- */+ lib$es6$promise$promise$$Promise.prototype = {+ constructor: lib$es6$promise$promise$$Promise,- Socket.prototype.onDrain = function() {- for (var i = 0; i < this.prevBufferLen; i++) {- if (this.callbackBuffer[i]) {- this.callbackBuffer[i]();- }- }+ /**+ The primary way of interacting with a promise is through its `then` method,+ which registers callbacks to receive either a promise's eventual value or the+ reason why the promise cannot be fulfilled.- this.writeBuffer.splice(0, this.prevBufferLen);- this.callbackBuffer.splice(0, this.prevBufferLen);+ ```js+ findUser().then(function(user){+ // user is available+ }, function(reason){+ // user is unavailable, and you are given the reason why+ });+ ```- // setting prevBufferLen = 0 is very important- // for example, when upgrading, upgrade packet is sent over,- // and a nonzero prevBufferLen could cause problems on `drain`- this.prevBufferLen = 0;+ Chaining+ --------- if (this.writeBuffer.length == 0) {- this.emit('drain');- } else {- this.flush();- }- };+ The return value of `then` is itself a promise. This second, 'downstream'+ promise is resolved with the return value of the first promise's fulfillment+ or rejection handler, or rejected if the handler throws an exception.- /**- * Flush write buffers.- *- * @api private- */+ ```js+ findUser().then(function (user) {+ return user.name;+ }, function (reason) {+ return 'default name';+ }).then(function (userName) {+ // If `findUser` fulfilled, `userName` will be the user's name, otherwise it+ // will be `'default name'`+ });- Socket.prototype.flush = function () {- if ('closed' != this.readyState && this.transport.writable &&- !this.upgrading && this.writeBuffer.length) {- debug('flushing %d packets in socket', this.writeBuffer.length);- this.transport.send(this.writeBuffer);- // keep track of current length of writeBuffer- // splice writeBuffer and callbackBuffer on `drain`- this.prevBufferLen = this.writeBuffer.length;- this.emit('flush');- }- };+ findUser().then(function (user) {+ throw new Error('Found user, but still unhappy');+ }, function (reason) {+ throw new Error('`findUser` rejected and we're unhappy');+ }).then(function (value) {+ // never reached+ }, function (reason) {+ // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.+ // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.+ });+ ```+ If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.- /**- * Sends a message.- *- * @param {String} message.- * @param {Function} callback function.- * @return {Socket} for chaining.- * @api public- */+ ```js+ findUser().then(function (user) {+ throw new PedagogicalException('Upstream error');+ }).then(function (value) {+ // never reached+ }).then(function (value) {+ // never reached+ }, function (reason) {+ // The `PedgagocialException` is propagated all the way down to here+ });+ ```- Socket.prototype.write =- Socket.prototype.send = function (msg, fn) {- this.sendPacket('message', msg, fn);- return this;- };+ Assimilation+ ------------- /**- * Sends a packet.- *- * @param {String} packet type.- * @param {String} data.- * @param {Function} callback function.- * @api private- */+ Sometimes the value you want to propagate to a downstream promise can only be+ retrieved asynchronously. This can be achieved by returning a promise in the+ fulfillment or rejection handler. The downstream promise will then be pending+ until the returned promise is settled. This is called *assimilation*.- Socket.prototype.sendPacket = function (type, data, fn) {- if ('closing' == this.readyState || 'closed' == this.readyState) {- return;- }+ ```js+ findUser().then(function (user) {+ return findCommentsByAuthor(user);+ }).then(function (comments) {+ // The user's comments are now available+ });+ ```- var packet = { type: type, data: data };- this.emit('packetCreate', packet);- this.writeBuffer.push(packet);- this.callbackBuffer.push(fn);- this.flush();- };+ If the assimliated promise rejects, then the downstream promise will also reject.- /**- * Closes the connection.- *- * @api private- */+ ```js+ findUser().then(function (user) {+ return findCommentsByAuthor(user);+ }).then(function (comments) {+ // If `findCommentsByAuthor` fulfills, we'll have the value here+ }, function (reason) {+ // If `findCommentsByAuthor` rejects, we'll have the reason here+ });+ ```- Socket.prototype.close = function () {- if ('opening' == this.readyState || 'open' == this.readyState) {- this.readyState = 'closing';+ Simple Example+ --------------- var self = this;+ Synchronous Example- function close() {- self.onClose('forced close');- debug('socket closing - telling transport to close');- self.transport.close();- }+ ```javascript+ var result;- function cleanupAndClose() {- self.removeListener('upgrade', cleanupAndClose);- self.removeListener('upgradeError', cleanupAndClose);- close();- }+ try {+ result = findResult();+ // success+ } catch(reason) {+ // failure+ }+ ```- function waitForUpgrade() {- // wait for upgrade to finish since we can't send packets while pausing a transport- self.once('upgrade', cleanupAndClose);- self.once('upgradeError', cleanupAndClose);- }+ Errback Example- if (this.writeBuffer.length) {- this.once('drain', function() {- if (this.upgrading) {- waitForUpgrade();+ ```js+ findResult(function(result, err){+ if (err) {+ // failure} else {- close();+ // success}});- } else if (this.upgrading) {- waitForUpgrade();- } else {- close();- }- }+ ```- return this;- };+ Promise Example;- /**- * Called upon transport error- *- * @api private- */+ ```javascript+ findResult().then(function(result){+ // success+ }, function(reason){+ // failure+ });+ ```- Socket.prototype.onError = function (err) {- debug('socket error %j', err);- Socket.priorWebsocketSuccess = false;- this.emit('error', err);- this.onClose('transport error', err);- };+ Advanced Example+ --------------- /**- * Called upon transport close.- *- * @api private- */+ Synchronous Example- Socket.prototype.onClose = function (reason, desc) {- if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {- debug('socket close with reason: "%s"', reason);- var self = this;+ ```javascript+ var author, books;- // clear timers- clearTimeout(this.pingIntervalTimer);- clearTimeout(this.pingTimeoutTimer);+ try {+ author = findAuthor();+ books = findBooksByAuthor(author);+ // success+ } catch(reason) {+ // failure+ }+ ```- // clean buffers in next tick, so developers can still- // grab the buffers on `close` event- setTimeout(function() {- self.writeBuffer = [];- self.callbackBuffer = [];- self.prevBufferLen = 0;- }, 0);+ Errback Example- // stop event from firing again for transport- this.transport.removeAllListeners('close');+ ```js- // ensure transport won't stay open- this.transport.close();+ function foundBooks(books) {- // ignore further transport communication- this.transport.removeAllListeners();+ }- // set ready state- this.readyState = 'closed';+ function failure(reason) {- // clear session id- this.id = null;+ }- // emit close event- this.emit('close', reason, desc);- }- };+ findAuthor(function(author, err){+ if (err) {+ failure(err);+ // failure+ } else {+ try {+ findBoooksByAuthor(author, function(books, err) {+ if (err) {+ failure(err);+ } else {+ try {+ foundBooks(books);+ } catch(reason) {+ failure(reason);+ }+ }+ });+ } catch(error) {+ failure(err);+ }+ // success+ }+ });+ ```- /**- * Filters upgrades, returning only those matching client transports.- *- * @param {Array} server upgrades- * @api private- *- */+ Promise Example;- Socket.prototype.filterUpgrades = function (upgrades) {- var filteredUpgrades = [];- for (var i = 0, j = upgrades.length; i<j; i++) {- if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);- }- return filteredUpgrades;- };+ ```javascript+ findAuthor().+ then(findBooksByAuthor).+ then(function(books){+ // found books+ }).catch(function(reason){+ // something went wrong+ });+ ```- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"./transport":59,"./transports":60,"component-emitter":53,"debug":66,"engine.io-parser":69,"indexof":76,"parsejson":100,"parseqs":101,"parseuri":68}],59:[function(require,module,exports){- /**- * Module dependencies.- */+ @method then+ @param {Function} onFulfilled+ @param {Function} onRejected+ Useful for tooling.+ @return {Promise}+ */+ then: function(onFulfillment, onRejection) {+ var parent = this;+ var state = parent._state;- var parser = require('engine.io-parser');- var Emitter = require('component-emitter');+ if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {+ return this;+ }- /**- * Module exports.- */+ var child = new this.constructor(lib$es6$promise$$internal$$noop);+ var result = parent._result;- module.exports = Transport;+ if (state) {+ var callback = arguments[state - 1];+ lib$es6$promise$asap$$asap(function(){+ lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);+ });+ } else {+ lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);+ }- /**- * Transport abstract constructor.- *- * @param {Object} options.- * @api private- */+ return child;+ },- function Transport (opts) {- this.path = opts.path;- this.hostname = opts.hostname;- this.port = opts.port;- this.secure = opts.secure;- this.query = opts.query;- this.timestampParam = opts.timestampParam;- this.timestampRequests = opts.timestampRequests;- this.readyState = '';- this.agent = opts.agent || false;- this.socket = opts.socket;- this.enablesXDR = opts.enablesXDR;+ /**+ `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same+ as the catch block of a try/catch statement.- // SSL options for Node.js client- this.pfx = opts.pfx;- this.key = opts.key;- this.passphrase = opts.passphrase;- this.cert = opts.cert;- this.ca = opts.ca;- this.ciphers = opts.ciphers;- this.rejectUnauthorized = opts.rejectUnauthorized;- }+ ```js+ function findAuthor(){+ throw new Error('couldn't find that author');+ }- /**- * Mix in `Emitter`.- */+ // synchronous+ try {+ findAuthor();+ } catch(reason) {+ // something went wrong+ }- Emitter(Transport.prototype);+ // async with promises+ findAuthor().catch(function(reason){+ // something went wrong+ });+ ```- /**- * A counter used to prevent collisions in the timestamps used- * for cache busting.- */+ @method catch+ @param {Function} onRejection+ Useful for tooling.+ @return {Promise}+ */+ 'catch': function(onRejection) {+ return this.then(null, onRejection);+ }+ };+ function lib$es6$promise$polyfill$$polyfill() {+ var local;- Transport.timestamps = 0;+ if (typeof global !== 'undefined') {+ local = global;+ } else if (typeof self !== 'undefined') {+ local = self;+ } else {+ try {+ local = Function('return this')();+ } catch (e) {+ throw new Error('polyfill failed because global object is unavailable in this environment');+ }+ }- /**- * Emits an error.- *- * @param {String} str- * @return {Transport} for chaining- * @api public- */+ var P = local.Promise;- Transport.prototype.onError = function (msg, desc) {- var err = new Error(msg);- err.type = 'TransportError';- err.description = desc;- this.emit('error', err);- return this;- };+ if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {+ return;+ }- /**- * Opens the transport.- *- * @api public- */+ local.Promise = lib$es6$promise$promise$$default;+ }+ var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;- Transport.prototype.open = function () {- if ('closed' == this.readyState || '' == this.readyState) {- this.readyState = 'opening';- this.doOpen();- }+ var lib$es6$promise$umd$$ES6Promise = {+ 'Promise': lib$es6$promise$promise$$default,+ 'polyfill': lib$es6$promise$polyfill$$default+ };- return this;- };+ /* global define:true module:true window: true */+ if (typeof define === 'function' && define['amd']) {+ define(function() { return lib$es6$promise$umd$$ES6Promise; });+ } else if (typeof module !== 'undefined' && module['exports']) {+ module['exports'] = lib$es6$promise$umd$$ES6Promise;+ } else if (typeof this !== 'undefined') {+ this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;+ }- /**- * Closes the transport.- *- * @api private- */+ lib$es6$promise$polyfill$$default();+ }).call(this);- Transport.prototype.close = function () {- if ('opening' == this.readyState || 'open' == this.readyState) {- this.doClose();- this.onClose();- }- return this;- };+ }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"_process":46}],48:[function(require,module,exports){++},{"_process":47}],49:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ *//**- * Sends multiple packets.- *- * @param {Array} packets- * @api private- */-- Transport.prototype.send = function(packets){- if ('open' == this.readyState) {- this.write(packets);- } else {- throw new Error('Transport not open');- }- };-- /**- * Called upon open- *- * @api private- */-- Transport.prototype.onOpen = function () {- this.readyState = 'open';- this.writable = true;- this.emit('open');- };-- /**- * Called with data.- *- * @param {String} data- * @api private- */-- Transport.prototype.onData = function(data){- var packet = parser.decodePacket(data, this.socket.binaryType);- this.onPacket(packet);- };-- /**- * Called with a decoded packet.- */-- Transport.prototype.onPacket = function (packet) {- this.emit('packet', packet);- };-- /**- * Called upon close.- *- * @api private+ * Ordered log levels.*/-- Transport.prototype.onClose = function () {- this.readyState = 'closed';- this.emit('close');+ var levels = {+ "trace": 0,+ "debug": 1,+ "info": 2,+ "log": 3,+ "warn": 4,+ "error": 5};- },{"component-emitter":53,"engine.io-parser":69}],60:[function(require,module,exports){- (function (global){/**- * Module dependencies+ * Parses Error's object stack trace and extracts information about the last+ * caller before the log method was called.+ * @returns JS object with info about the caller - method name, file location,+ * line and column.*/+ function getCallerInfo() {+ var callerInfo = {+ methodName: "",+ fileLocation: "",+ line: null,+ column: null+ };+ //gets the part of the stack without the logger wrappers+ var error = new Error();+ var stack = error.stack? error.stack.split("\n") : [];+ if(!stack || stack.length < 1) {+ return callerInfo;+ }+ var m = null;+ if(stack[3]) {+ m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);+ }+ if(!m || m.length <= 4) {+ //Firefox && Safari+ if(stack[2].indexOf("log@") === 0){+ //Safari+ callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));+ } else {+ //Firefox+ callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));+ }+ return callerInfo;+ }- var XMLHttpRequest = require('xmlhttprequest');- var XHR = require('./polling-xhr');- var JSONP = require('./polling-jsonp');- var websocket = require('./websocket');+ callerInfo.methodName = m[1];+ callerInfo.fileLocation = m[2];+ callerInfo.line = m[3];+ callerInfo.column = m[4];+ return callerInfo;+ }/**- * Export transports.+ * Logs messages using the transports and level from the logger.+ * @param logger a logger instance.+ * @param level the log level of the message. See the levels variable.+ * @param arguments array with arguments that will be logged.*/+ function log() {+ var logger = arguments[0], level = arguments[1],+ args = Array.prototype.slice.call(arguments, 2);+ if(levels[level] <= logger.level) {+ return;+ }- exports.polling = polling;- exports.websocket = websocket;+ var callerInfo = getCallerInfo();+ for(var i = 0; i < logger.transports.length; i++) {+ var t = logger.transports[i];+ var l = t[level];+ if(l && typeof(l) === "function") {+ l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")+ .apply(t, args);+ }+ }+ }/**- * Polling transport polymorphic constructor.- * Decides on xhr vs jsonp based on feature detection.*- * @api private+ * Constructs new logger object.+ * @param level the logging level for the new logger+ * @param id optional identifier for the logger instance.+ * @param transports optional list of handlers(objects) for the logs.+ * The handlers must support - log, warn, error, debug, info, trace.+ * @param format optional (NOT implemented) string.*/-- function polling(opts){- var xhr;- var xd = false;- var xs = false;- var jsonp = false !== opts.jsonp;-- if (global.location) {- var isSSL = 'https:' == location.protocol;- var port = location.port;-- // some user agents have empty `location.port`- if (!port) {- port = isSSL ? 443 : 80;+ function Logger(level, id, transports, format) {+ this.id = id;+ this.format = format;+ if(!this.transports) {+ this.transports = [];+ this.transports.push(Logger.consoleTransport);+ }+ this.level = levels[level];+ var methods = Object.keys(levels);+ for(var i = 0; i < methods.length; i++){+ this[methods[i]] =+ log.bind(null, this, methods[i]);}-- xd = opts.hostname != location.hostname || port != opts.port;- xs = opts.secure != isSSL;- }-- opts.xdomain = xd;- opts.xscheme = xs;- xhr = new XMLHttpRequest(opts);-- if ('open' in xhr && !opts.forceJSONP) {- return new XHR(opts);- } else {- if (!jsonp) throw new Error('JSONP disabled');- return new JSONP(opts);- }}- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"./polling-jsonp":61,"./polling-xhr":62,"./websocket":64,"xmlhttprequest":65}],61:[function(require,module,exports){- (function (global){-/**- * Module requirements.+ * Sets the log level for the logger.+ * @param level the new log level.*/-- var Polling = require('./polling');- var inherit = require('component-inherit');+ Logger.prototype.setLevel = function (level) {+ this.level = levels[level];+ };+ module.exports = Logger;/**- * Module exports.+ * The default transport - console*/-- module.exports = JSONPPolling;+ Logger.consoleTransport = console;/**- * Cached regular expressions.+ * Enum for the supported log levels.*/+ Logger.levels = {+ TRACE: "trace",+ DEBUG: "debug",+ INFO: "info",+ LOG: "log",+ WARN: "warn",+ ERROR: "error"+ };- var rNewline = /\n/g;- var rEscapedNewline = /\\n/g;-- /**- * Global JSONP callbacks.-},{}],49:[function(require,module,exports){++},{}],50:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.*/-- var callbacks;+ var Logger = require("./Logger");/**- * Callbacks count.+ * Map with the created loggers with ID.*/-- var index = 0;+ var idLoggers = {};/**- * Noop.+ * Array with the loggers without id.*/-- function empty () { }+ var loggers = [];/**- * JSONP Polling constructor.- *- * @param {Object} opts.- * @api public+ * Log level for the lbrary.*/+ var curLevel = Logger.levels.TRACE;- function JSONPPolling (opts) {- Polling.call(this, opts);-- this.query = this.query || {};- // define global callbacks array if not present- // we do this here (lazily) to avoid unneeded global pollution- if (!callbacks) {- // we need to consider multiple engines in the same page- if (!global.___eio) global.___eio = [];- callbacks = global.___eio;- }+ module.exports = {+ /**+ * Creates new logger.+ * @arguments the same as Logger constructor+ */+ getLogger: function(id, transports, format) {+ var logger = new Logger(curLevel, id, transports, format);+ if(id) {+ idLoggers[id] = idLoggers[id] || [];+ idLoggers[id].push(logger);+ } else {+ loggers.push(logger);+ }+ return logger;+ },+ /**+ * Changes the log level for the existing loggers by id.+ * @param level the new log level.+ * @param id if specified the level will be changed only for loggers with the+ * same id. Otherwise the operation will affect all loggers that don't+ * have id.+ */+ setLogLevelById: function(level, id) {+ var l = id? (idLoggers[id] || []) : loggers;+ for(var i = 0; i < l.length; i++) {+ l[i].setLevel(level);+ }+ },+ /**+ * Changes the log level for all existing loggers.+ * @param level the new log level.+ */+ setLogLevel: function (level) {+ curLevel = level;+ var i = 0;+ for(; i < loggers.length; i++) {+ loggers[i].setLevel(level);+ }- // callback identifier- this.index = callbacks.length;+ for(var id in idLoggers) {+ var l = idLoggers[id] || [];+ for(i = 0; i < l.length; i++) {+ l[i].setLevel(level);+ }+ }+ },+ /**+ * The supported log levels.+ */+ levels: Logger.levels+ };- // add callback to jsonp global- var self = this;- callbacks.push(function (msg) {- self.onData(msg);- });-},{"./Logger":48}],50:[function(require,module,exports){++},{"./Logger":49}],51:[function(require,module,exports){+ /*+ A JavaScript implementation of the SHA family of hashes, as+ defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation+ as defined in FIPS PUB 198a- // append to query string- this.query.j = this.index;+ Copyright Brian Turek 2008-2013+ Distributed under the BSD License+ See http://caligatio.github.com/jsSHA/ for more information- // prevent spurious errors from being emitted when the window is unloaded- if (global.document && global.addEventListener) {- global.addEventListener('beforeunload', function () {- if (self.script) self.script.onerror = empty;- }, false);- }- }+ Several functions taken from Paul Johnston+ */+ (function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==+ typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";+ return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===+ b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|+ (g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,+ binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,+ c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=+ {outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):+ new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,+ 34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>+ 16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>+ 16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>+ 16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-+ 14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,+ 1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,+ 2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],+ 3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),+ new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),+ new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,+ 3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,+ d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?+ new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,+ d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);- /**- * Inherits from Polling.- */-},{}],51:[function(require,module,exports){++},{}],52:[function(require,module,exports){+ // Top level file is just a mixin of submodules & constants+ 'use strict';- inherit(JSONPPolling, Polling);+ var assign = require('./lib/utils/common').assign;- /*- * JSONP only supports binary as base64 encoded strings- */+ var deflate = require('./lib/deflate');+ var inflate = require('./lib/inflate');+ var constants = require('./lib/zlib/constants');- JSONPPolling.prototype.supportsBinary = false;+ var pako = {};- /**- * Closes the socket.- *- * @api private- */+ assign(pako, deflate, inflate, constants);- JSONPPolling.prototype.doClose = function () {- if (this.script) {- this.script.parentNode.removeChild(this.script);- this.script = null;- }+ module.exports = pako;- if (this.form) {- this.form.parentNode.removeChild(this.form);- this.form = null;- this.iframe = null;- }-},{"./lib/deflate":52,"./lib/inflate":53,"./lib/utils/common":54,"./lib/zlib/constants":57}],52:[function(require,module,exports){++},{"./lib/deflate":53,"./lib/inflate":54,"./lib/utils/common":55,"./lib/zlib/constants":58}],53:[function(require,module,exports){+ 'use strict';- Polling.prototype.doClose.call(this);- };- /**- * Starts a poll cycle.- *- * @api private- */+ var zlib_deflate = require('./zlib/deflate.js');+ var utils = require('./utils/common');+ var strings = require('./utils/strings');+ var msg = require('./zlib/messages');+ var zstream = require('./zlib/zstream');- JSONPPolling.prototype.doPoll = function () {- var self = this;- var script = document.createElement('script');+ var toString = Object.prototype.toString;- if (this.script) {- this.script.parentNode.removeChild(this.script);- this.script = null;- }+ /* Public constants ==========================================================*/+ /* ===========================================================================*/- script.async = true;- script.src = this.uri();- script.onerror = function(e){- self.onError('jsonp poll error',e);- };+ var Z_NO_FLUSH = 0;+ var Z_FINISH = 4;- var insertAt = document.getElementsByTagName('script')[0];- insertAt.parentNode.insertBefore(script, insertAt);- this.script = script;+ var Z_OK = 0;+ var Z_STREAM_END = 1;+ var Z_SYNC_FLUSH = 2;- var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);-- if (isUAgecko) {- setTimeout(function () {- var iframe = document.createElement('iframe');- document.body.appendChild(iframe);- document.body.removeChild(iframe);- }, 100);- }- };+ var Z_DEFAULT_COMPRESSION = -1;- /**- * Writes with a hidden iframe.- *- * @param {String} data to send- * @param {Function} called upon flush.- * @api private- */+ var Z_DEFAULT_STRATEGY = 0;- JSONPPolling.prototype.doWrite = function (data, fn) {- var self = this;+ var Z_DEFLATED = 8;- if (!this.form) {- var form = document.createElement('form');- var area = document.createElement('textarea');- var id = this.iframeId = 'eio_iframe_' + this.index;- var iframe;+ /* ===========================================================================*/- form.className = 'socketio';- form.style.position = 'absolute';- form.style.top = '-1000px';- form.style.left = '-1000px';- form.target = id;- form.method = 'POST';- form.setAttribute('accept-charset', 'utf-8');- area.name = 'd';- form.appendChild(area);- document.body.appendChild(form);- this.form = form;- this.area = area;- }+ /**+ * class Deflate+ *+ * Generic JS-style wrapper for zlib calls. If you don't need+ * streaming behaviour - use more simple functions: [[deflate]],+ * [[deflateRaw]] and [[gzip]].+ **/- this.form.action = this.uri();+ /* internal+ * Deflate.chunks -> Array+ *+ * Chunks of output data, if [[Deflate#onData]] not overriden.+ **/- function complete () {- initIframe();- fn();- }+ /**+ * Deflate.result -> Uint8Array|Array+ *+ * Compressed result, generated by default [[Deflate#onData]]+ * and [[Deflate#onEnd]] handlers. Filled after you push last chunk+ * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you+ * push a chunk with explicit flush (call [[Deflate#push]] with+ * `Z_SYNC_FLUSH` param).+ **/- function initIframe () {- if (self.iframe) {- try {- self.form.removeChild(self.iframe);- } catch (e) {- self.onError('jsonp polling iframe removal error', e);- }- }+ /**+ * Deflate.err -> Number+ *+ * Error code after deflate finished. 0 (Z_OK) on success.+ * You will not need it in real life, because deflate errors+ * are possible only on wrong options or bad `onData` / `onEnd`+ * custom handlers.+ **/- try {- // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)- var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';- iframe = document.createElement(html);- } catch (e) {- iframe = document.createElement('iframe');- iframe.name = self.iframeId;- iframe.src = 'javascript:0';- }-- iframe.id = self.iframeId;+ /**+ * Deflate.msg -> String+ *+ * Error message, if [[Deflate.err]] != 0+ **/- self.form.appendChild(iframe);- self.iframe = iframe;- }- initIframe();+ /**+ * new Deflate(options)+ * - options (Object): zlib deflate options.+ *+ * Creates new deflator instance with specified params. Throws exception+ * on bad params. Supported options:+ *+ * - `level`+ * - `windowBits`+ * - `memLevel`+ * - `strategy`+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information on these.+ *+ * Additional options, for internal needs:+ *+ * - `chunkSize` - size of generated data chunks (16K by default)+ * - `raw` (Boolean) - do raw deflate+ * - `gzip` (Boolean) - create gzip wrapper+ * - `to` (String) - if equal to 'string', then result will be "binary string"+ * (each char code [0..255])+ * - `header` (Object) - custom header for gzip+ * - `text` (Boolean) - true if compressed data believed to be text+ * - `time` (Number) - modification time, unix timestamp+ * - `os` (Number) - operation system code+ * - `extra` (Array) - array of bytes with extra data (max 65536)+ * - `name` (String) - file name (binary string)+ * - `comment` (String) - comment (binary string)+ * - `hcrc` (Boolean) - true if header crc should be added+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])+ * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);+ *+ * var deflate = new pako.Deflate({ level: 3});+ *+ * deflate.push(chunk1, false);+ * deflate.push(chunk2, true); // true -> last chunk+ *+ * if (deflate.err) { throw new Error(deflate.err); }+ *+ * console.log(deflate.result);+ * ```+ **/+ var Deflate = function(options) {- // escape \n to prevent it from being converted into \r\n by some UAs- // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side- data = data.replace(rEscapedNewline, '\\\n');- this.area.value = data.replace(rNewline, '\\n');+ this.options = utils.assign({+ level: Z_DEFAULT_COMPRESSION,+ method: Z_DEFLATED,+ chunkSize: 16384,+ windowBits: 15,+ memLevel: 8,+ strategy: Z_DEFAULT_STRATEGY,+ to: ''+ }, options || {});- try {- this.form.submit();- } catch(e) {}+ var opt = this.options;- if (this.iframe.attachEvent) {- this.iframe.onreadystatechange = function(){- if (self.iframe.readyState == 'complete') {- complete();- }- };- } else {- this.iframe.onload = complete;+ if (opt.raw && (opt.windowBits > 0)) {+ opt.windowBits = -opt.windowBits;}- };- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"./polling":63,"component-inherit":54}],62:[function(require,module,exports){- (function (global){- /**- * Module requirements.- */+ else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {+ opt.windowBits += 16;+ }- var XMLHttpRequest = require('xmlhttprequest');- var Polling = require('./polling');- var Emitter = require('component-emitter');- var inherit = require('component-inherit');- var debug = require('debug')('engine.io-client:polling-xhr');+ this.err = 0; // error code, if happens (0 = Z_OK)+ this.msg = ''; // error message+ this.ended = false; // used to avoid multiple onEnd() calls+ this.chunks = []; // chunks of compressed data- /**- * Module exports.- */+ this.strm = new zstream();+ this.strm.avail_out = 0;- module.exports = XHR;- module.exports.Request = Request;+ var status = zlib_deflate.deflateInit2(+ this.strm,+ opt.level,+ opt.method,+ opt.windowBits,+ opt.memLevel,+ opt.strategy+ );- /**- * Empty function- */+ if (status !== Z_OK) {+ throw new Error(msg[status]);+ }- function empty(){}+ if (opt.header) {+ zlib_deflate.deflateSetHeader(this.strm, opt.header);+ }+ };/**- * XHR Polling constructor.+ * Deflate#push(data[, mode]) -> Boolean+ * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be+ * converted to utf8 byte sequence.+ * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.+ * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.*- * @param {Object} opts- * @api public- */+ * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with+ * new compressed chunks. Returns `true` on success. The last data block must have+ * mode Z_FINISH (or `true`). That will flush internal pending buffers and call+ * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you+ * can use mode Z_SYNC_FLUSH, keeping the compression context.+ *+ * On fail call [[Deflate#onEnd]] with error code and return false.+ *+ * We strongly recommend to use `Uint8Array` on input for best speed (output+ * array format is detected automatically). Also, don't skip last param and always+ * use the same type in your code (boolean or number). That will improve JS speed.+ *+ * For regular `Array`-s make sure all elements are [0..255].+ *+ * ##### Example+ *+ * ```javascript+ * push(chunk, false); // push one of data chunks+ * ...+ * push(chunk, true); // push last chunk+ * ```+ **/+ Deflate.prototype.push = function(data, mode) {+ var strm = this.strm;+ var chunkSize = this.options.chunkSize;+ var status, _mode;- function XHR(opts){- Polling.call(this, opts);+ if (this.ended) { return false; }- if (global.location) {- var isSSL = 'https:' == location.protocol;- var port = location.port;+ _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);- // some user agents have empty `location.port`- if (!port) {- port = isSSL ? 443 : 80;+ // Convert data if needed+ if (typeof data === 'string') {+ // If we need to compress text, change encoding to utf8.+ strm.input = strings.string2buf(data);+ } else if (toString.call(data) === '[object ArrayBuffer]') {+ strm.input = new Uint8Array(data);+ } else {+ strm.input = data;+ }++ strm.next_in = 0;+ strm.avail_in = strm.input.length;++ do {+ if (strm.avail_out === 0) {+ strm.output = new utils.Buf8(chunkSize);+ strm.next_out = 0;+ strm.avail_out = chunkSize;}+ status = zlib_deflate.deflate(strm, _mode); /* no bad return value */- this.xd = opts.hostname != global.location.hostname ||- port != opts.port;- this.xs = opts.secure != isSSL;+ if (status !== Z_STREAM_END && status !== Z_OK) {+ this.onEnd(status);+ this.ended = true;+ return false;+ }+ if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {+ if (this.options.to === 'string') {+ this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));+ } else {+ this.onData(utils.shrinkBuf(strm.output, strm.next_out));+ }+ }+ } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);++ // Finalize on the last chunk.+ if (_mode === Z_FINISH) {+ status = zlib_deflate.deflateEnd(this.strm);+ this.onEnd(status);+ this.ended = true;+ return status === Z_OK;}- }- /**- * Inherits from Polling.- */+ // callback interim results if Z_SYNC_FLUSH.+ if (_mode === Z_SYNC_FLUSH) {+ this.onEnd(Z_OK);+ strm.avail_out = 0;+ return true;+ }++ return true;+ };- inherit(XHR, Polling);/**- * XHR supports binary- */+ * Deflate#onData(chunk) -> Void+ * - chunk (Uint8Array|Array|String): ouput data. Type of array depends+ * on js engine support. When string output requested, each chunk+ * will be string.+ *+ * By default, stores data blocks in `chunks[]` property and glue+ * those in `onEnd`. Override this handler, if you need another behaviour.+ **/+ Deflate.prototype.onData = function(chunk) {+ this.chunks.push(chunk);+ };- XHR.prototype.supportsBinary = true;/**- * Creates a request.+ * Deflate#onEnd(status) -> Void+ * - status (Number): deflate status. 0 (Z_OK) on success,+ * other if not.*- * @param {String} method- * @api private- */-- XHR.prototype.request = function(opts){- opts = opts || {};- opts.uri = this.uri();- opts.xd = this.xd;- opts.xs = this.xs;- opts.agent = this.agent || false;- opts.supportsBinary = this.supportsBinary;- opts.enablesXDR = this.enablesXDR;-- // SSL options for Node.js client- opts.pfx = this.pfx;- opts.key = this.key;- opts.passphrase = this.passphrase;- opts.cert = this.cert;- opts.ca = this.ca;- opts.ciphers = this.ciphers;- opts.rejectUnauthorized = this.rejectUnauthorized;-- return new Request(opts);+ * Called once after you tell deflate that the input stream is+ * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)+ * or if an error happened. By default - join collected chunks,+ * free memory and fill `results` / `err` properties.+ **/+ Deflate.prototype.onEnd = function(status) {+ // On success - join+ if (status === Z_OK) {+ if (this.options.to === 'string') {+ this.result = this.chunks.join('');+ } else {+ this.result = utils.flattenChunks(this.chunks);+ }+ }+ this.chunks = [];+ this.err = status;+ this.msg = this.strm.msg;};+/**- * Sends data.+ * deflate(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to compress.+ * - options (Object): zlib deflate options.*- * @param {String} data to send.- * @param {Function} called upon flush.- * @api private- */+ * Compress `data` with deflate alrorythm and `options`.+ *+ * Supported options are:+ *+ * - level+ * - windowBits+ * - memLevel+ * - strategy+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information on these.+ *+ * Sugar (options):+ *+ * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify+ * negative windowBits implicitly.+ * - `to` (String) - if equal to 'string', then result will be "binary string"+ * (each char code [0..255])+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);+ *+ * console.log(pako.deflate(data));+ * ```+ **/+ function deflate(input, options) {+ var deflator = new Deflate(options);++ deflator.push(input, true);++ // That will never happens, if you don't cheat with options :)+ if (deflator.err) { throw deflator.msg; }++ return deflator.result;+ }- XHR.prototype.doWrite = function(data, fn){- var isBinary = typeof data !== 'string' && data !== undefined;- var req = this.request({ method: 'POST', data: data, isBinary: isBinary });- var self = this;- req.on('success', fn);- req.on('error', function(err){- self.onError('xhr post error', err);- });- this.sendXhr = req;- };/**- * Starts a poll cycle.+ * deflateRaw(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to compress.+ * - options (Object): zlib deflate options.*- * @api private- */+ * The same as [[deflate]], but creates raw data, without wrapper+ * (header and adler32 crc).+ **/+ function deflateRaw(input, options) {+ options = options || {};+ options.raw = true;+ return deflate(input, options);+ }- XHR.prototype.doPoll = function(){- debug('xhr poll');- var req = this.request();- var self = this;- req.on('data', function(data){- self.onData(data);- });- req.on('error', function(err){- self.onError('xhr poll error', err);- });- this.pollXhr = req;- };/**- * Request constructor+ * gzip(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to compress.+ * - options (Object): zlib deflate options.*- * @param {Object} options- * @api public- */+ * The same as [[deflate]], but create gzip wrapper instead of+ * deflate one.+ **/+ function gzip(input, options) {+ options = options || {};+ options.gzip = true;+ return deflate(input, options);+ }- function Request(opts){- this.method = opts.method || 'GET';- this.uri = opts.uri;- this.xd = !!opts.xd;- this.xs = !!opts.xs;- this.async = false !== opts.async;- this.data = undefined != opts.data ? opts.data : null;- this.agent = opts.agent;- this.isBinary = opts.isBinary;- this.supportsBinary = opts.supportsBinary;- this.enablesXDR = opts.enablesXDR;- // SSL options for Node.js client- this.pfx = opts.pfx;- this.key = opts.key;- this.passphrase = opts.passphrase;- this.cert = opts.cert;- this.ca = opts.ca;- this.ciphers = opts.ciphers;- this.rejectUnauthorized = opts.rejectUnauthorized;+ exports.Deflate = Deflate;+ exports.deflate = deflate;+ exports.deflateRaw = deflateRaw;+ exports.gzip = gzip;- this.create();- }-},{"./utils/common":54,"./utils/strings":55,"./zlib/deflate.js":59,"./zlib/messages":64,"./zlib/zstream":66}],53:[function(require,module,exports){++},{"./utils/common":55,"./utils/strings":56,"./zlib/deflate.js":60,"./zlib/messages":65,"./zlib/zstream":67}],54:[function(require,module,exports){+ 'use strict';- /**- * Mix in `Emitter`.- */- Emitter(Request.prototype);+ var zlib_inflate = require('./zlib/inflate.js');+ var utils = require('./utils/common');+ var strings = require('./utils/strings');+ var c = require('./zlib/constants');+ var msg = require('./zlib/messages');+ var zstream = require('./zlib/zstream');+ var gzheader = require('./zlib/gzheader');++ var toString = Object.prototype.toString;/**- * Creates the XHR object and sends the request.+ * class Inflate*- * @api private- */-- Request.prototype.create = function(){- var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };+ * Generic JS-style wrapper for zlib calls. If you don't need+ * streaming behaviour - use more simple functions: [[inflate]]+ * and [[inflateRaw]].+ **/- // SSL options for Node.js client- opts.pfx = this.pfx;- opts.key = this.key;- opts.passphrase = this.passphrase;- opts.cert = this.cert;- opts.ca = this.ca;- opts.ciphers = this.ciphers;- opts.rejectUnauthorized = this.rejectUnauthorized;+ /* internal+ * inflate.chunks -> Array+ *+ * Chunks of output data, if [[Inflate#onData]] not overriden.+ **/- var xhr = this.xhr = new XMLHttpRequest(opts);- var self = this;+ /**+ * Inflate.result -> Uint8Array|Array|String+ *+ * Uncompressed result, generated by default [[Inflate#onData]]+ * and [[Inflate#onEnd]] handlers. Filled after you push last chunk+ * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you+ * push a chunk with explicit flush (call [[Inflate#push]] with+ * `Z_SYNC_FLUSH` param).+ **/- try {- debug('xhr open %s: %s', this.method, this.uri);- xhr.open(this.method, this.uri, this.async);- if (this.supportsBinary) {- // This has to be done after open because Firefox is stupid- // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension- xhr.responseType = 'arraybuffer';- }+ /**+ * Inflate.err -> Number+ *+ * Error code after inflate finished. 0 (Z_OK) on success.+ * Should be checked if broken data possible.+ **/- if ('POST' == this.method) {- try {- if (this.isBinary) {- xhr.setRequestHeader('Content-type', 'application/octet-stream');- } else {- xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');- }- } catch (e) {}- }+ /**+ * Inflate.msg -> String+ *+ * Error message, if [[Inflate.err]] != 0+ **/- // ie6 check- if ('withCredentials' in xhr) {- xhr.withCredentials = true;- }-- if (this.hasXDR()) {- xhr.onload = function(){- self.onLoad();- };- xhr.onerror = function(){- self.onError(xhr.responseText);- };- } else {- xhr.onreadystatechange = function(){- if (4 != xhr.readyState) return;- if (200 == xhr.status || 1223 == xhr.status) {- self.onLoad();- } else {- // make sure the `error` event handler that's user-set- // does not throw in the same tick and gets caught here- setTimeout(function(){- self.onError(xhr.status);- }, 0);- }- };- }-- debug('xhr data %s', this.data);- xhr.send(this.data);- } catch (e) {- // Need to defer since .create() is called directly fhrom the constructor- // and thus the 'error' event can only be only bound *after* this exception- // occurs. Therefore, also, we cannot throw here at all.- setTimeout(function() {- self.onError(e);- }, 0);- return;- }-- if (global.document) {- this.index = Request.requestsCount++;- Request.requests[this.index] = this;- }- };/**- * Called upon successful response.+ * new Inflate(options)+ * - options (Object): zlib inflate options.*- * @api private- */-- Request.prototype.onSuccess = function(){- this.emit('success');- this.cleanup();- };-- /**- * Called if we have data.+ * Creates new inflator instance with specified params. Throws exception+ * on bad params. Supported options:*- * @api private- */-- Request.prototype.onData = function(data){- this.emit('data', data);- this.onSuccess();- };-- /**- * Called upon error.+ * - `windowBits`*- * @api private- */+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information on these.+ *+ * Additional options, for internal needs:+ *+ * - `chunkSize` - size of generated data chunks (16K by default)+ * - `raw` (Boolean) - do raw inflate+ * - `to` (String) - if equal to 'string', then result will be converted+ * from utf8 to utf16 (javascript) string. When string output requested,+ * chunk length can differ from `chunkSize`, depending on content.+ *+ * By default, when no options set, autodetect deflate/gzip data format via+ * wrapper header.+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])+ * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);+ *+ * var inflate = new pako.Inflate({ level: 3});+ *+ * inflate.push(chunk1, false);+ * inflate.push(chunk2, true); // true -> last chunk+ *+ * if (inflate.err) { throw new Error(inflate.err); }+ *+ * console.log(inflate.result);+ * ```+ **/+ var Inflate = function(options) {- Request.prototype.onError = function(err){- this.emit('error', err);- this.cleanup(true);- };+ this.options = utils.assign({+ chunkSize: 16384,+ windowBits: 0,+ to: ''+ }, options || {});- /**- * Cleans up house.- *- * @api private- */+ var opt = this.options;- Request.prototype.cleanup = function(fromError){- if ('undefined' == typeof this.xhr || null === this.xhr) {- return;- }- // xmlhttprequest- if (this.hasXDR()) {- this.xhr.onload = this.xhr.onerror = empty;- } else {- this.xhr.onreadystatechange = empty;+ // Force window size for `raw` data, if not set directly,+ // because we have no header for autodetect.+ if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {+ opt.windowBits = -opt.windowBits;+ if (opt.windowBits === 0) { opt.windowBits = -15; }}- if (fromError) {- try {- this.xhr.abort();- } catch(e) {}+ // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate+ if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&+ !(options && options.windowBits)) {+ opt.windowBits += 32;}- if (global.document) {- delete Request.requests[this.index];+ // Gzip header has no info about windows size, we can do autodetect only+ // for deflate. So, if window size not set, force it to max when gzip possible+ if ((opt.windowBits > 15) && (opt.windowBits < 48)) {+ // bit 3 (16) -> gzipped data+ // bit 4 (32) -> autodetect gzip/deflate+ if ((opt.windowBits & 15) === 0) {+ opt.windowBits |= 15;+ }}- this.xhr = null;- };+ this.err = 0; // error code, if happens (0 = Z_OK)+ this.msg = ''; // error message+ this.ended = false; // used to avoid multiple onEnd() calls+ this.chunks = []; // chunks of compressed data- /**- * Called upon load.- *- * @api private- */+ this.strm = new zstream();+ this.strm.avail_out = 0;- Request.prototype.onLoad = function(){- var data;- try {- var contentType;- try {- contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];- } catch (e) {}- if (contentType === 'application/octet-stream') {- data = this.xhr.response;- } else {- if (!this.supportsBinary) {- data = this.xhr.responseText;- } else {- data = 'ok';- }- }- } catch (e) {- this.onError(e);- }- if (null != data) {- this.onData(data);+ var status = zlib_inflate.inflateInit2(+ this.strm,+ opt.windowBits+ );++ if (status !== c.Z_OK) {+ throw new Error(msg[status]);}- };- /**- * Check if it has XDomainRequest.- *- * @api private- */+ this.header = new gzheader();- Request.prototype.hasXDR = function(){- return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;+ zlib_inflate.inflateGetHeader(this.strm, this.header);};/**- * Aborts the request.+ * Inflate#push(data[, mode]) -> Boolean+ * - data (Uint8Array|Array|ArrayBuffer|String): input data+ * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.+ * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.*- * @api public- */+ * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with+ * new output chunks. Returns `true` on success. The last data block must have+ * mode Z_FINISH (or `true`). That will flush internal pending buffers and call+ * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you+ * can use mode Z_SYNC_FLUSH, keeping the decompression context.+ *+ * On fail call [[Inflate#onEnd]] with error code and return false.+ *+ * We strongly recommend to use `Uint8Array` on input for best speed (output+ * format is detected automatically). Also, don't skip last param and always+ * use the same type in your code (boolean or number). That will improve JS speed.+ *+ * For regular `Array`-s make sure all elements are [0..255].+ *+ * ##### Example+ *+ * ```javascript+ * push(chunk, false); // push one of data chunks+ * ...+ * push(chunk, true); // push last chunk+ * ```+ **/+ Inflate.prototype.push = function(data, mode) {+ var strm = this.strm;+ var chunkSize = this.options.chunkSize;+ var status, _mode;+ var next_out_utf8, tail, utf8str;- Request.prototype.abort = function(){- this.cleanup();- };+ // Flag to properly process Z_BUF_ERROR on testing inflate call+ // when we check that all output data was flushed.+ var allowBufError = false;- /**- * Aborts pending requests when unloading the window. This is needed to prevent- * memory leaks (e.g. when using IE) and to ensure that no spurious error is- * emitted.- */+ if (this.ended) { return false; }+ _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);- if (global.document) {- Request.requestsCount = 0;- Request.requests = {};- if (global.attachEvent) {- global.attachEvent('onunload', unloadHandler);- } else if (global.addEventListener) {- global.addEventListener('beforeunload', unloadHandler, false);+ // Convert data if needed+ if (typeof data === 'string') {+ // Only binary strings can be decompressed on practice+ strm.input = strings.binstring2buf(data);+ } else if (toString.call(data) === '[object ArrayBuffer]') {+ strm.input = new Uint8Array(data);+ } else {+ strm.input = data;}- }- function unloadHandler() {- for (var i in Request.requests) {- if (Request.requests.hasOwnProperty(i)) {- Request.requests[i].abort();- }- }- }+ strm.next_in = 0;+ strm.avail_in = strm.input.length;- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"./polling":63,"component-emitter":53,"component-inherit":54,"debug":66,"xmlhttprequest":65}],63:[function(require,module,exports){- /**- * Module dependencies.- */-- var Transport = require('../transport');- var parseqs = require('parseqs');- var parser = require('engine.io-parser');- var inherit = require('component-inherit');- var debug = require('debug')('engine.io-client:polling');-- /**- * Module exports.- */-- module.exports = Polling;-- /**- * Is XHR2 supported?- */+ do {+ if (strm.avail_out === 0) {+ strm.output = new utils.Buf8(chunkSize);+ strm.next_out = 0;+ strm.avail_out = chunkSize;+ }- var hasXHR2 = (function() {- var XMLHttpRequest = require('xmlhttprequest');- var xhr = new XMLHttpRequest({ xdomain: false });- return null != xhr.responseType;- })();+ status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */- /**- * Polling interface.- *- * @param {Object} opts- * @api private- */+ if (status === c.Z_BUF_ERROR && allowBufError === true) {+ status = c.Z_OK;+ allowBufError = false;+ }- function Polling(opts){- var forceBase64 = (opts && opts.forceBase64);- if (!hasXHR2 || forceBase64) {- this.supportsBinary = false;- }- Transport.call(this, opts);- }+ if (status !== c.Z_STREAM_END && status !== c.Z_OK) {+ this.onEnd(status);+ this.ended = true;+ return false;+ }- /**- * Inherits from Transport.- */+ if (strm.next_out) {+ if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {- inherit(Polling, Transport);+ if (this.options.to === 'string') {- /**- * Transport name.- */+ next_out_utf8 = strings.utf8border(strm.output, strm.next_out);- Polling.prototype.name = 'polling';+ tail = strm.next_out - next_out_utf8;+ utf8str = strings.buf2string(strm.output, next_out_utf8);- /**- * Opens the socket (triggers polling). We write a PING message to determine- * when the transport is open.- *- * @api private- */+ // move tail+ strm.next_out = tail;+ strm.avail_out = chunkSize - tail;+ if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }- Polling.prototype.doOpen = function(){- this.poll();- };+ this.onData(utf8str);- /**- * Pauses polling.- *- * @param {Function} callback upon buffers are flushed and transport is paused- * @api private- */+ } else {+ this.onData(utils.shrinkBuf(strm.output, strm.next_out));+ }+ }+ }- Polling.prototype.pause = function(onPause){- var pending = 0;- var self = this;+ // When no more input data, we should check that internal inflate buffers+ // are flushed. The only way to do it when avail_out = 0 - run one more+ // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.+ // Here we set flag to process this error properly.+ //+ // NOTE. Deflate does not return error in this case and does not needs such+ // logic.+ if (strm.avail_in === 0 && strm.avail_out === 0) {+ allowBufError = true;+ }- this.readyState = 'pausing';+ } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);- function pause(){- debug('paused');- self.readyState = 'paused';- onPause();+ if (status === c.Z_STREAM_END) {+ _mode = c.Z_FINISH;}- if (this.polling || !this.writable) {- var total = 0;-- if (this.polling) {- debug('we are currently polling - waiting to pause');- total++;- this.once('pollComplete', function(){- debug('pre-pause polling complete');- --total || pause();- });- }+ // Finalize on the last chunk.+ if (_mode === c.Z_FINISH) {+ status = zlib_inflate.inflateEnd(this.strm);+ this.onEnd(status);+ this.ended = true;+ return status === c.Z_OK;+ }- if (!this.writable) {- debug('we are currently writing - waiting to pause');- total++;- this.once('drain', function(){- debug('pre-pause writing complete');- --total || pause();- });- }- } else {- pause();+ // callback interim results if Z_SYNC_FLUSH.+ if (_mode === c.Z_SYNC_FLUSH) {+ this.onEnd(c.Z_OK);+ strm.avail_out = 0;+ return true;}++ return true;};+/**- * Starts polling cycle.+ * Inflate#onData(chunk) -> Void+ * - chunk (Uint8Array|Array|String): ouput data. Type of array depends+ * on js engine support. When string output requested, each chunk+ * will be string.*- * @api public- */-- Polling.prototype.poll = function(){- debug('polling');- this.polling = true;- this.doPoll();- this.emit('poll');+ * By default, stores data blocks in `chunks[]` property and glue+ * those in `onEnd`. Override this handler, if you need another behaviour.+ **/+ Inflate.prototype.onData = function(chunk) {+ this.chunks.push(chunk);};+/**- * Overloads onData to detect payloads.+ * Inflate#onEnd(status) -> Void+ * - status (Number): inflate status. 0 (Z_OK) on success,+ * other if not.*- * @api private- */-- Polling.prototype.onData = function(data){- var self = this;- debug('polling got data %s', data);- var callback = function(packet, index, total) {- // if its the first message we consider the transport open- if ('opening' == self.readyState) {- self.onOpen();- }-- // if its a close packet, we close the ongoing requests- if ('close' == packet.type) {- self.onClose();- return false;- }-- // otherwise bypass onData and handle the message- self.onPacket(packet);- };-- // decode payload- parser.decodePayload(data, this.socket.binaryType, callback);-- // if an event did not trigger closing- if ('closed' != this.readyState) {- // if we got data we're not polling- this.polling = false;- this.emit('pollComplete');-- if ('open' == this.readyState) {- this.poll();+ * Called either after you tell inflate that the input stream is+ * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)+ * or if an error happened. By default - join collected chunks,+ * free memory and fill `results` / `err` properties.+ **/+ Inflate.prototype.onEnd = function(status) {+ // On success - join+ if (status === c.Z_OK) {+ if (this.options.to === 'string') {+ // Glue & convert here, until we teach pako to send+ // utf8 alligned strings to onData+ this.result = this.chunks.join('');} else {- debug('ignoring poll - transport state "%s"', this.readyState);+ this.result = utils.flattenChunks(this.chunks);}}+ this.chunks = [];+ this.err = status;+ this.msg = this.strm.msg;};- /**- * For polling, send a close packet.- *- * @api private- */-- Polling.prototype.doClose = function(){- var self = this;-- function close(){- debug('writing close packet');- self.write([{ type: 'close' }]);- }-- if ('open' == this.readyState) {- debug('transport open - closing');- close();- } else {- // in case we're trying to close while- // handshaking is in progress (GH-164)- debug('transport not open - deferring close');- this.once('open', close);- }- };/**- * Writes a packets payload.+ * inflate(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to decompress.+ * - options (Object): zlib inflate options.*- * @param {Array} data packets- * @param {Function} drain callback- * @api private- */-- Polling.prototype.write = function(packets){- var self = this;- this.writable = false;- var callbackfn = function() {- self.writable = true;- self.emit('drain');- };-- var self = this;- parser.encodePayload(packets, this.supportsBinary, function(data) {- self.doWrite(data, callbackfn);- });- };-- /**- * Generates uri for connection.+ * Decompress `data` with inflate/ungzip and `options`. Autodetect+ * format via wrapper header by default. That's why we don't provide+ * separate `ungzip` method.*- * @api private- */-- Polling.prototype.uri = function(){- var query = this.query || {};- var schema = this.secure ? 'https' : 'http';- var port = '';-- // cache busting is forced- if (false !== this.timestampRequests) {- query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;- }-- if (!this.supportsBinary && !query.sid) {- query.b64 = 1;- }+ * Supported options are:+ *+ * - windowBits+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information.+ *+ * Sugar (options):+ *+ * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify+ * negative windowBits implicitly.+ * - `to` (String) - if equal to 'string', then result will be converted+ * from utf8 to utf16 (javascript) string. When string output requested,+ * chunk length can differ from `chunkSize`, depending on content.+ *+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , input = pako.deflate([1,2,3,4,5,6,7,8,9])+ * , output;+ *+ * try {+ * output = pako.inflate(input);+ * } catch (err)+ * console.log(err);+ * }+ * ```+ **/+ function inflate(input, options) {+ var inflator = new Inflate(options);- query = parseqs.encode(query);+ inflator.push(input, true);- // avoid port if default for schema- if (this.port && (('https' == schema && this.port != 443) ||- ('http' == schema && this.port != 80))) {- port = ':' + this.port;- }+ // That will never happens, if you don't cheat with options :)+ if (inflator.err) { throw inflator.msg; }- // prepend ? to query- if (query.length) {- query = '?' + query;- }+ return inflator.result;+ }- return schema + '://' + this.hostname + port + this.path + query;- };- },{"../transport":59,"component-inherit":54,"debug":66,"engine.io-parser":69,"parseqs":101,"xmlhttprequest":65}],64:[function(require,module,exports){/**- * Module dependencies.- */+ * inflateRaw(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to decompress.+ * - options (Object): zlib inflate options.+ *+ * The same as [[inflate]], but creates raw data, without wrapper+ * (header and adler32 crc).+ **/+ function inflateRaw(input, options) {+ options = options || {};+ options.raw = true;+ return inflate(input, options);+ }- var Transport = require('../transport');- var parser = require('engine.io-parser');- var parseqs = require('parseqs');- var inherit = require('component-inherit');- var debug = require('debug')('engine.io-client:websocket');/**- * `ws` exposes a WebSocket-compatible interface in- * Node, or the `WebSocket` or `MozWebSocket` globals- * in the browser.- */+ * ungzip(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to decompress.+ * - options (Object): zlib inflate options.+ *+ * Just shortcut to [[inflate]], because it autodetects format+ * by header.content. Done for convenience.+ **/- var WebSocket = require('ws');- /**- * Module exports.- */+ exports.Inflate = Inflate;+ exports.inflate = inflate;+ exports.inflateRaw = inflateRaw;+ exports.ungzip = inflate;- module.exports = WS;-},{"./utils/common":54,"./utils/strings":55,"./zlib/constants":57,"./zlib/gzheader":60,"./zlib/inflate.js":62,"./zlib/messages":64,"./zlib/zstream":66}],54:[function(require,module,exports){++},{"./utils/common":55,"./utils/strings":56,"./zlib/constants":58,"./zlib/gzheader":61,"./zlib/inflate.js":63,"./zlib/messages":65,"./zlib/zstream":67}],55:[function(require,module,exports){+ 'use strict';- /**- * WebSocket transport constructor.- *- * @api {Object} connection options- * @api public- */- function WS(opts){- var forceBase64 = (opts && opts.forceBase64);- if (forceBase64) {- this.supportsBinary = false;- }- Transport.call(this, opts);- }+ var TYPED_OK = (typeof Uint8Array !== 'undefined') &&+ (typeof Uint16Array !== 'undefined') &&+ (typeof Int32Array !== 'undefined');- /**- * Inherits from Transport.- */- inherit(WS, Transport);+ exports.assign = function (obj /*from1, from2, from3, ...*/) {+ var sources = Array.prototype.slice.call(arguments, 1);+ while (sources.length) {+ var source = sources.shift();+ if (!source) { continue; }- /**- * Transport name.- *- * @api public- */+ if (typeof source !== 'object') {+ throw new TypeError(source + 'must be non-object');+ }- WS.prototype.name = 'websocket';+ for (var p in source) {+ if (source.hasOwnProperty(p)) {+ obj[p] = source[p];+ }+ }+ }- /*- * WebSockets support binary- */+ return obj;+ };- WS.prototype.supportsBinary = true;- /**- * Opens socket.- *- * @api private- */+ // reduce buffer size, avoiding mem copy+ exports.shrinkBuf = function (buf, size) {+ if (buf.length === size) { return buf; }+ if (buf.subarray) { return buf.subarray(0, size); }+ buf.length = size;+ return buf;+ };- WS.prototype.doOpen = function(){- if (!this.check()) {- // let probe timeout- return;- }- var self = this;- var uri = this.uri();- var protocols = void(0);- var opts = { agent: this.agent };+ var fnTyped = {+ arraySet: function (dest, src, src_offs, len, dest_offs) {+ if (src.subarray && dest.subarray) {+ dest.set(src.subarray(src_offs, src_offs+len), dest_offs);+ return;+ }+ // Fallback to ordinary array+ for (var i=0; i<len; i++) {+ dest[dest_offs + i] = src[src_offs + i];+ }+ },+ // Join array of chunks to single array.+ flattenChunks: function(chunks) {+ var i, l, len, pos, chunk, result;- // SSL options for Node.js client- opts.pfx = this.pfx;- opts.key = this.key;- opts.passphrase = this.passphrase;- opts.cert = this.cert;- opts.ca = this.ca;- opts.ciphers = this.ciphers;- opts.rejectUnauthorized = this.rejectUnauthorized;+ // calculate data length+ len = 0;+ for (i=0, l=chunks.length; i<l; i++) {+ len += chunks[i].length;+ }- this.ws = new WebSocket(uri, protocols, opts);+ // join chunks+ result = new Uint8Array(len);+ pos = 0;+ for (i=0, l=chunks.length; i<l; i++) {+ chunk = chunks[i];+ result.set(chunk, pos);+ pos += chunk.length;+ }- if (this.ws.binaryType === undefined) {- this.supportsBinary = false;+ return result;}-- this.ws.binaryType = 'arraybuffer';- this.addEventListeners();};- /**- * Adds event listeners to the socket- *- * @api private- */+ var fnUntyped = {+ arraySet: function (dest, src, src_offs, len, dest_offs) {+ for (var i=0; i<len; i++) {+ dest[dest_offs + i] = src[src_offs + i];+ }+ },+ // Join array of chunks to single array.+ flattenChunks: function(chunks) {+ return [].concat.apply([], chunks);+ }+ };- WS.prototype.addEventListeners = function(){- var self = this;- this.ws.onopen = function(){- self.onOpen();- };- this.ws.onclose = function(){- self.onClose();- };- this.ws.onmessage = function(ev){- self.onData(ev.data);- };- this.ws.onerror = function(e){- self.onError('websocket error', e);- };+ // Enable/Disable typed arrays use, for testing+ //+ exports.setTyped = function (on) {+ if (on) {+ exports.Buf8 = Uint8Array;+ exports.Buf16 = Uint16Array;+ exports.Buf32 = Int32Array;+ exports.assign(exports, fnTyped);+ } else {+ exports.Buf8 = Array;+ exports.Buf16 = Array;+ exports.Buf32 = Array;+ exports.assign(exports, fnUntyped);+ }};- /**- * Override `onData` to use a timer on iOS.- * See: https://gist.github.com/mloughran/2052006- *- * @api private- */+ exports.setTyped(TYPED_OK);- if ('undefined' != typeof navigator- && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {- WS.prototype.onData = function(data){- var self = this;- setTimeout(function(){- Transport.prototype.onData.call(self, data);- }, 0);- };- }-},{}],55:[function(require,module,exports){++},{}],56:[function(require,module,exports){+ // String encode/decode helpers+ 'use strict';- /**- * Writes data to socket.- *- * @param {Array} array of packets.- * @api private- */- WS.prototype.write = function(packets){- var self = this;- this.writable = false;- // encodePacket efficient as it uses WS framing- // no need for encodePayload- for (var i = 0, l = packets.length; i < l; i++) {- parser.encodePacket(packets[i], this.supportsBinary, function(data) {- //Sometimes the websocket has already been closed but the browser didn't- //have a chance of informing us about it yet, in that case send will- //throw an error- try {- self.ws.send(data);- } catch (e){- debug('websocket closed before onclose event');- }- });- }+ var utils = require('./common');- function ondrain() {- self.writable = true;- self.emit('drain');- }- // fake drain- // defer to next tick to allow Socket to clear writeBuffer- setTimeout(ondrain, 0);- };- /**- * Called upon close- *- * @api private- */+ // Quick check if we can use fast array to bin string conversion+ //+ // - apply(Array) can fail on Android 2.2+ // - apply(Uint8Array) can fail on iOS 5.1 Safary+ //+ var STR_APPLY_OK = true;+ var STR_APPLY_UIA_OK = true;- WS.prototype.onClose = function(){- Transport.prototype.onClose.call(this);- };+ try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }+ try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }- /**- * Closes socket.- *- * @api private- */- WS.prototype.doClose = function(){- if (typeof this.ws !== 'undefined') {- this.ws.close();- }- };+ // Table with utf8 lengths (calculated by first byte of sequence)+ // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,+ // because max possible codepoint is 0x10ffff+ var _utf8len = new utils.Buf8(256);+ for (var q=0; q<256; q++) {+ _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);+ }+ _utf8len[254]=_utf8len[254]=1; // Invalid sequence start- /**- * Generates uri for connection.- *- * @api private- */- WS.prototype.uri = function(){- var query = this.query || {};- var schema = this.secure ? 'wss' : 'ws';- var port = '';+ // convert string to array (typed, when possible)+ exports.string2buf = function (str) {+ var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;- // avoid port if default for schema- if (this.port && (('wss' == schema && this.port != 443)- || ('ws' == schema && this.port != 80))) {- port = ':' + this.port;+ // count binary size+ for (m_pos = 0; m_pos < str_len; m_pos++) {+ c = str.charCodeAt(m_pos);+ if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {+ c2 = str.charCodeAt(m_pos+1);+ if ((c2 & 0xfc00) === 0xdc00) {+ c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);+ m_pos++;+ }+ }+ buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;}- // append timestamp to URI- if (this.timestampRequests) {- query[this.timestampParam] = +new Date;- }+ // allocate buffer+ buf = new utils.Buf8(buf_len);- // communicate binary support capabilities- if (!this.supportsBinary) {- query.b64 = 1;+ // convert+ for (i=0, m_pos = 0; i < buf_len; m_pos++) {+ c = str.charCodeAt(m_pos);+ if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {+ c2 = str.charCodeAt(m_pos+1);+ if ((c2 & 0xfc00) === 0xdc00) {+ c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);+ m_pos++;+ }+ }+ if (c < 0x80) {+ /* one byte */+ buf[i++] = c;+ } else if (c < 0x800) {+ /* two bytes */+ buf[i++] = 0xC0 | (c >>> 6);+ buf[i++] = 0x80 | (c & 0x3f);+ } else if (c < 0x10000) {+ /* three bytes */+ buf[i++] = 0xE0 | (c >>> 12);+ buf[i++] = 0x80 | (c >>> 6 & 0x3f);+ buf[i++] = 0x80 | (c & 0x3f);+ } else {+ /* four bytes */+ buf[i++] = 0xf0 | (c >>> 18);+ buf[i++] = 0x80 | (c >>> 12 & 0x3f);+ buf[i++] = 0x80 | (c >>> 6 & 0x3f);+ buf[i++] = 0x80 | (c & 0x3f);+ }}- query = parseqs.encode(query);+ return buf;+ };- // prepend ? to query- if (query.length) {- query = '?' + query;+ // Helper (used in 2 places)+ function buf2binstring(buf, len) {+ // use fallback for big arrays to avoid stack overflow+ if (len < 65537) {+ if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {+ return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));+ }}- return schema + '://' + this.hostname + port + this.path + query;+ var result = '';+ for (var i=0; i < len; i++) {+ result += String.fromCharCode(buf[i]);+ }+ return result;+ }+++ // Convert byte array to binary string+ exports.buf2binstring = function(buf) {+ return buf2binstring(buf, buf.length);};- /**- * Feature detection for WebSocket.- *- * @return {Boolean} whether this transport is available.- * @api public- */- WS.prototype.check = function(){- return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);+ // Convert binary string (typed, when possible)+ exports.binstring2buf = function(str) {+ var buf = new utils.Buf8(str.length);+ for (var i=0, len=buf.length; i < len; i++) {+ buf[i] = str.charCodeAt(i);+ }+ return buf;};- },{"../transport":59,"component-inherit":54,"debug":66,"engine.io-parser":69,"parseqs":101,"ws":129}],65:[function(require,module,exports){- // browser shim for xmlhttprequest module- var hasCORS = require('has-cors');- module.exports = function(opts) {- var xdomain = opts.xdomain;+ // convert array to string+ exports.buf2string = function (buf, max) {+ var i, out, c, c_len;+ var len = max || buf.length;- // scheme must be same when usign XDomainRequest- // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx- var xscheme = opts.xscheme;+ // Reserve max possible length (2 words per char)+ // NB: by unknown reasons, Array is significantly faster for+ // String.fromCharCode.apply than Uint16Array.+ var utf16buf = new Array(len*2);- // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.- // https://github.com/Automattic/engine.io-client/pull/217- var enablesXDR = opts.enablesXDR;+ for (out=0, i=0; i<len;) {+ c = buf[i++];+ // quick process ascii+ if (c < 0x80) { utf16buf[out++] = c; continue; }- // XMLHttpRequest can be disabled on IE- try {- if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {- return new XMLHttpRequest();- }- } catch (e) { }+ c_len = _utf8len[c];+ // skip 5 & 6 byte codes+ if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }- // Use XDomainRequest for IE8 if enablesXDR is true- // because loading bar keeps flashing when using jsonp-polling- // https://github.com/yujiosaka/socke.io-ie8-loading-example- try {- if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {- return new XDomainRequest();+ // apply mask on first byte+ c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;+ // join the rest+ while (c_len > 1 && i < len) {+ c = (c << 6) | (buf[i++] & 0x3f);+ c_len--;}- } catch (e) { }- if (!xdomain) {- try {- return new ActiveXObject('Microsoft.XMLHTTP');- } catch(e) { }- }- }+ // terminated by end of string?+ if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }- },{"has-cors":75}],66:[function(require,module,exports){+ if (c < 0x10000) {+ utf16buf[out++] = c;+ } else {+ c -= 0x10000;+ utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);+ utf16buf[out++] = 0xdc00 | (c & 0x3ff);+ }+ }- /**- * This is the web browser implementation of `debug()`.- *- * Expose `debug()` as the module.- */+ return buf2binstring(utf16buf, out);+ };- exports = module.exports = require('./debug');- exports.log = log;- exports.formatArgs = formatArgs;- exports.save = save;- exports.load = load;- exports.useColors = useColors;- /**- * Colors.- */+ // Calculate max possible position in utf8 buffer,+ // that will not break sequence. If that's not possible+ // - (very small limits) return max size as is.+ //+ // buf[] - utf8 bytes array+ // max - length limit (mandatory);+ exports.utf8border = function(buf, max) {+ var pos;- exports.colors = [- 'lightseagreen',- 'forestgreen',- 'goldenrod',- 'dodgerblue',- 'darkorchid',- 'crimson'- ];+ max = max || buf.length;+ if (max > buf.length) { max = buf.length; }- /**- * Currently only WebKit-based Web Inspectors, Firefox >= v31,- * and the Firebug extension (any Firefox version) are known- * to support "%c" CSS customizations.- *- * TODO: add a `localStorage` variable to explicitly enable/disable colors- */+ // go back from last position, until start of sequence found+ pos = max-1;+ while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }- function useColors() {- // is webkit? http://stackoverflow.com/a/16459606/376773- return ('WebkitAppearance' in document.documentElement.style) ||- // is firebug? http://stackoverflow.com/a/398120/376773- (window.console && (console.firebug || (console.exception && console.table))) ||- // is firefox >= v31?- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages- (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);- }+ // Fuckup - very small and broken sequence,+ // return max, because we should return something anyway.+ if (pos < 0) { return max; }- /**- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.- */+ // If we came to start of buffer - that means vuffer is too small,+ // return max too.+ if (pos === 0) { return max; }- exports.formatters.j = function(v) {- return JSON.stringify(v);+ return (pos + _utf8len[buf[pos]] > max) ? pos : max;};-},{"./common":54}],56:[function(require,module,exports){++},{"./common":55}],57:[function(require,module,exports){+ 'use strict';- /**- * Colorize log arguments if enabled.- *- * @api public- */-- function formatArgs() {- var args = arguments;- var useColors = this.useColors;+ // Note: adler32 takes 12% for level 0 and 2% for level 6.+ // It doesn't worth to make additional optimizationa as in original.+ // Small size is preferable.- args[0] = (useColors ? '%c' : '')- + this.namespace- + (useColors ? ' %c' : ' ')- + args[0]- + (useColors ? '%c ' : ' ')- + '+' + exports.humanize(this.diff);+ function adler32(adler, buf, len, pos) {+ var s1 = (adler & 0xffff) |0,+ s2 = ((adler >>> 16) & 0xffff) |0,+ n = 0;- if (!useColors) return args;+ while (len !== 0) {+ // Set limit ~ twice less than 5552, to keep+ // s2 in 31-bits, because we force signed ints.+ // in other case %= will fail.+ n = len > 2000 ? 2000 : len;+ len -= n;- var c = 'color: ' + this.color;- args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));+ do {+ s1 = (s1 + buf[pos++]) |0;+ s2 = (s2 + s1) |0;+ } while (--n);- // the final "%c" is somewhat tricky, because there could be other- // arguments passed either before or after the %c, so we need to- // figure out the correct index to insert the CSS into- var index = 0;- var lastC = 0;- args[0].replace(/%[a-z%]/g, function(match) {- if ('%%' === match) return;- index++;- if ('%c' === match) {- // we only are interested in the *last* %c- // (the user may have provided their own)- lastC = index;- }- });+ s1 %= 65521;+ s2 %= 65521;+ }- args.splice(lastC, 0, c);- return args;+ return (s1 | (s2 << 16)) |0;}- /**- * Invokes `console.log()` when available.- * No-op when `console.log` is not a "function".- *- * @api public- */-- function log() {- // This hackery is required for IE8,- // where the `console.log` function doesn't have 'apply'- return 'object' == typeof console- && 'function' == typeof console.log- && Function.prototype.apply.call(console.log, console, arguments);- }- /**- * Save `namespaces`.- *- * @param {String} namespaces- * @api private- */+ module.exports = adler32;- function save(namespaces) {- try {- if (null == namespaces) {- localStorage.removeItem('debug');- } else {- localStorage.debug = namespaces;- }- } catch(e) {}- }-},{}],57:[function(require,module,exports){++},{}],58:[function(require,module,exports){+ module.exports = {- /**- * Load `namespaces`.- *- * @return {String} returns the previously persisted debug modes- * @api private- */+ /* Allowed flush values; see deflate() and inflate() below for details */+ Z_NO_FLUSH: 0,+ Z_PARTIAL_FLUSH: 1,+ Z_SYNC_FLUSH: 2,+ Z_FULL_FLUSH: 3,+ Z_FINISH: 4,+ Z_BLOCK: 5,+ Z_TREES: 6,- function load() {- var r;- try {- r = localStorage.debug;- } catch(e) {}- return r;- }+ /* Return codes for the compression/decompression functions. Negative values+ * are errors, positive values are used for special but normal events.+ */+ Z_OK: 0,+ Z_STREAM_END: 1,+ Z_NEED_DICT: 2,+ Z_ERRNO: -1,+ Z_STREAM_ERROR: -2,+ Z_DATA_ERROR: -3,+ //Z_MEM_ERROR: -4,+ Z_BUF_ERROR: -5,+ //Z_VERSION_ERROR: -6,- /**- * Enable namespaces listed in `localStorage.debug` initially.- */+ /* compression levels */+ Z_NO_COMPRESSION: 0,+ Z_BEST_SPEED: 1,+ Z_BEST_COMPRESSION: 9,+ Z_DEFAULT_COMPRESSION: -1,- exports.enable(load());- },{"./debug":67}],67:[function(require,module,exports){+ Z_FILTERED: 1,+ Z_HUFFMAN_ONLY: 2,+ Z_RLE: 3,+ Z_FIXED: 4,+ Z_DEFAULT_STRATEGY: 0,- /**- * This is the common logic for both the Node.js and web browser- * implementations of `debug()`.- *- * Expose `debug()` as the module.- */+ /* Possible values of the data_type field (though see inflate()) */+ Z_BINARY: 0,+ Z_TEXT: 1,+ //Z_ASCII: 1, // = Z_TEXT (deprecated)+ Z_UNKNOWN: 2,- exports = module.exports = debug;- exports.coerce = coerce;- exports.disable = disable;- exports.enable = enable;- exports.enabled = enabled;- exports.humanize = require('ms');+ /* The deflate compression method */+ Z_DEFLATED: 8+ //Z_NULL: null // Use -1 or null inline, depending on var type+ };- /**- * The currently active debug mode names, and names to skip.- */-},{}],58:[function(require,module,exports){++},{}],59:[function(require,module,exports){+ 'use strict';- exports.names = [];- exports.skips = [];+ // Note: we can't get significant speed boost here.+ // So write code to minimize size - no pregenerated tables+ // and array tools dependencies.- /**- * Map of special "%n" handling functions, for the debug "format" argument.- *- * Valid key names are a single, lowercased letter, i.e. "n".- */- exports.formatters = {};+ // Use ordinary array, since untyped makes no boost here+ function makeTable() {+ var c, table = [];- /**- * Previously assigned color.- */+ for (var n =0; n < 256; n++) {+ c = n;+ for (var k =0; k < 8; k++) {+ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));+ }+ table[n] = c;+ }- var prevColor = 0;+ return table;+ }- /**- * Previous log timestamp.- */+ // Create table on load. Just 255 signed longs. Not a problem.+ var crcTable = makeTable();- var prevTime;- /**- * Select a color.- *- * @return {Number}- * @api private- */+ function crc32(crc, buf, len, pos) {+ var t = crcTable,+ end = pos + len;- function selectColor() {- return exports.colors[prevColor++ % exports.colors.length];+ crc = crc ^ (-1);++ for (var i = pos; i < end; i++) {+ crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];+ }++ return (crc ^ (-1)); // >>> 0;}- /**- * Create a debugger with the given `namespace`.- *- * @param {String} namespace- * @return {Function}- * @api public- */- function debug(namespace) {+ module.exports = crc32;- // define the `disabled` version- function disabled() {- }- disabled.enabled = false;-},{}],59:[function(require,module,exports){++},{}],60:[function(require,module,exports){+ 'use strict';- // define the `enabled` version- function enabled() {+ var utils = require('../utils/common');+ var trees = require('./trees');+ var adler32 = require('./adler32');+ var crc32 = require('./crc32');+ var msg = require('./messages');- var self = enabled;+ /* Public constants ==========================================================*/+ /* ===========================================================================*/- // set `diff` timestamp- var curr = +new Date();- var ms = curr - (prevTime || curr);- self.diff = ms;- self.prev = prevTime;- self.curr = curr;- prevTime = curr;- // add the `color` if not set- if (null == self.useColors) self.useColors = exports.useColors();- if (null == self.color && self.useColors) self.color = selectColor();+ /* Allowed flush values; see deflate() and inflate() below for details */+ var Z_NO_FLUSH = 0;+ var Z_PARTIAL_FLUSH = 1;+ //var Z_SYNC_FLUSH = 2;+ var Z_FULL_FLUSH = 3;+ var Z_FINISH = 4;+ var Z_BLOCK = 5;+ //var Z_TREES = 6;- var args = Array.prototype.slice.call(arguments);- args[0] = exports.coerce(args[0]);+ /* Return codes for the compression/decompression functions. Negative values+ * are errors, positive values are used for special but normal events.+ */+ var Z_OK = 0;+ var Z_STREAM_END = 1;+ //var Z_NEED_DICT = 2;+ //var Z_ERRNO = -1;+ var Z_STREAM_ERROR = -2;+ var Z_DATA_ERROR = -3;+ //var Z_MEM_ERROR = -4;+ var Z_BUF_ERROR = -5;+ //var Z_VERSION_ERROR = -6;- if ('string' !== typeof args[0]) {- // anything else let's inspect with %o- args = ['%o'].concat(args);- }- // apply any `formatters` transformations- var index = 0;- args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {- // if we encounter an escaped % then don't increase the array index- if (match === '%%') return match;- index++;- var formatter = exports.formatters[format];- if ('function' === typeof formatter) {- var val = args[index];- match = formatter.call(self, val);+ /* compression levels */+ //var Z_NO_COMPRESSION = 0;+ //var Z_BEST_SPEED = 1;+ //var Z_BEST_COMPRESSION = 9;+ var Z_DEFAULT_COMPRESSION = -1;- // now we need to remove `args[index]` since it's inlined in the `format`- args.splice(index, 1);- index--;- }- return match;- });- if ('function' === typeof exports.formatArgs) {- args = exports.formatArgs.apply(self, args);- }- var logFn = enabled.log || exports.log || console.log.bind(console);- logFn.apply(self, args);- }- enabled.enabled = true;+ var Z_FILTERED = 1;+ var Z_HUFFMAN_ONLY = 2;+ var Z_RLE = 3;+ var Z_FIXED = 4;+ var Z_DEFAULT_STRATEGY = 0;- var fn = exports.enabled(namespace) ? enabled : disabled;+ /* Possible values of the data_type field (though see inflate()) */+ //var Z_BINARY = 0;+ //var Z_TEXT = 1;+ //var Z_ASCII = 1; // = Z_TEXT+ var Z_UNKNOWN = 2;- fn.namespace = namespace;- return fn;- }+ /* The deflate compression method */+ var Z_DEFLATED = 8;- /**- * Enables a debug mode by namespaces. This can include modes- * separated by a colon and wildcards.- *- * @param {String} namespaces- * @api public- */+ /*============================================================================*/- function enable(namespaces) {- exports.save(namespaces);- var split = (namespaces || '').split(/[\s,]+/);- var len = split.length;+ var MAX_MEM_LEVEL = 9;+ /* Maximum value for memLevel in deflateInit2 */+ var MAX_WBITS = 15;+ /* 32K LZ77 window */+ var DEF_MEM_LEVEL = 8;- for (var i = 0; i < len; i++) {- if (!split[i]) continue; // ignore empty strings- namespaces = split[i].replace(/\*/g, '.*?');- if (namespaces[0] === '-') {- exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));- } else {- exports.names.push(new RegExp('^' + namespaces + '$'));- }- }- }- /**- * Disable debug output.- *- * @api public- */+ var LENGTH_CODES = 29;+ /* number of length codes, not counting the special END_BLOCK code */+ var LITERALS = 256;+ /* number of literal bytes 0..255 */+ var L_CODES = LITERALS + 1 + LENGTH_CODES;+ /* number of Literal or Length codes, including the END_BLOCK code */+ var D_CODES = 30;+ /* number of distance codes */+ var BL_CODES = 19;+ /* number of codes used to transfer the bit lengths */+ var HEAP_SIZE = 2*L_CODES + 1;+ /* maximum heap size */+ var MAX_BITS = 15;+ /* All codes must not exceed MAX_BITS bits */- function disable() {- exports.enable('');- }+ var MIN_MATCH = 3;+ var MAX_MATCH = 258;+ var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);- /**- * Returns true if the given mode name is enabled, false otherwise.- *- * @param {String} name- * @return {Boolean}- * @api public- */+ var PRESET_DICT = 0x20;- function enabled(name) {- var i, len;- for (i = 0, len = exports.skips.length; i < len; i++) {- if (exports.skips[i].test(name)) {- return false;- }- }- for (i = 0, len = exports.names.length; i < len; i++) {- if (exports.names[i].test(name)) {- return true;- }- }- return false;- }+ var INIT_STATE = 42;+ var EXTRA_STATE = 69;+ var NAME_STATE = 73;+ var COMMENT_STATE = 91;+ var HCRC_STATE = 103;+ var BUSY_STATE = 113;+ var FINISH_STATE = 666;- /**- * Coerce `val`.- *- * @param {Mixed} val- * @return {Mixed}- * @api private- */+ var BS_NEED_MORE = 1; /* block not completed, need more input or more output */+ var BS_BLOCK_DONE = 2; /* block flush performed */+ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */+ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */- function coerce(val) {- if (val instanceof Error) return val.stack || val.message;- return val;+ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.++ function err(strm, errorCode) {+ strm.msg = msg[errorCode];+ return errorCode;}- },{"ms":82}],68:[function(require,module,exports){- /**- * Parses an URI- *- * @author Steven Levithan <stevenlevithan.com> (MIT license)- * @api private- */+ function rank(f) {+ return ((f) << 1) - ((f) > 4 ? 9 : 0);+ }- var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;+ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }- var parts = [- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'- ];- module.exports = function parseuri(str) {- var src = str,- b = str.indexOf('['),- e = str.indexOf(']');+ /* =========================================================================+ * Flush as much pending output as possible. All deflate() output goes+ * through this function so some applications may wish to modify it+ * to avoid allocating a large strm->output buffer and copying into it.+ * (See also read_buf()).+ */+ function flush_pending(strm) {+ var s = strm.state;- if (b != -1 && e != -1) {- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);- }+ //_tr_flush_bits(s);+ var len = s.pending;+ if (len > strm.avail_out) {+ len = strm.avail_out;+ }+ if (len === 0) { return; }- var m = re.exec(str || ''),- uri = {},- i = 14;+ utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);+ strm.next_out += len;+ s.pending_out += len;+ strm.total_out += len;+ strm.avail_out -= len;+ s.pending -= len;+ if (s.pending === 0) {+ s.pending_out = 0;+ }+ }- while (i--) {- uri[parts[i]] = m[i] || '';- }- if (b != -1 && e != -1) {- uri.source = src;- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');- uri.ipv6uri = true;- }+ function flush_block_only (s, last) {+ trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);+ s.block_start = s.strstart;+ flush_pending(s.strm);+ }- return uri;- };- },{}],69:[function(require,module,exports){- (function (global){- /**- * Module dependencies.- */+ function put_byte(s, b) {+ s.pending_buf[s.pending++] = b;+ }- var keys = require('./keys');- var hasBinary = require('has-binary');- var sliceBuffer = require('arraybuffer.slice');- var base64encoder = require('base64-arraybuffer');- var after = require('after');- var utf8 = require('utf8');- /**- * Check if we are running an android browser. That requires us to use- * ArrayBuffer with polling transports...- *- * http://ghinda.net/jpeg-blob-ajax-android/+ /* =========================================================================+ * Put a short in the pending buffer. The 16-bit value is put in MSB order.+ * IN assertion: the stream state is correct and there is enough room in+ * pending_buf.*/+ function putShortMSB(s, b) {+ // put_byte(s, (Byte)(b >> 8));+ // put_byte(s, (Byte)(b & 0xff));+ s.pending_buf[s.pending++] = (b >>> 8) & 0xff;+ s.pending_buf[s.pending++] = b & 0xff;+ }- var isAndroid = navigator.userAgent.match(/Android/i);-- /**- * Check if we are running in PhantomJS.- * Uploading a Blob with PhantomJS does not work correctly, as reported here:- * https://github.com/ariya/phantomjs/issues/11395- * @type boolean- */- var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);- /**- * When true, avoids using Blobs to encode payloads.- * @type boolean+ /* ===========================================================================+ * Read a new buffer from the current input stream, update the adler32+ * and total number of bytes read. All deflate() input goes through+ * this function so some applications may wish to modify it to avoid+ * allocating a large strm->input buffer and copying from it.+ * (See also flush_pending()).*/- var dontSendBlobs = isAndroid || isPhantomJS;+ function read_buf(strm, buf, start, size) {+ var len = strm.avail_in;- /**- * Current protocol version.- */+ if (len > size) { len = size; }+ if (len === 0) { return 0; }- exports.protocol = 3;+ strm.avail_in -= len;- /**- * Packet types.- */+ utils.arraySet(buf, strm.input, strm.next_in, len, start);+ if (strm.state.wrap === 1) {+ strm.adler = adler32(strm.adler, buf, len, start);+ }- var packets = exports.packets = {- open: 0 // non-ws- , close: 1 // non-ws- , ping: 2- , pong: 3- , message: 4- , upgrade: 5- , noop: 6- };+ else if (strm.state.wrap === 2) {+ strm.adler = crc32(strm.adler, buf, len, start);+ }- var packetslist = keys(packets);+ strm.next_in += len;+ strm.total_in += len;- /**- * Premade error packet.- */+ return len;+ }- var err = { type: 'error', data: 'parser error' };- /**- * Create a blob api even for blob builder when vendor prefixes exist+ /* ===========================================================================+ * Set match_start to the longest match starting at the given string and+ * return its length. Matches shorter or equal to prev_length are discarded,+ * in which case the result is equal to prev_length and match_start is+ * garbage.+ * IN assertions: cur_match is the head of the hash chain for the current+ * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1+ * OUT assertion: the match length is not greater than s->lookahead.*/+ function longest_match(s, cur_match) {+ var chain_length = s.max_chain_length; /* max hash chain length */+ var scan = s.strstart; /* current string */+ var match; /* matched string */+ var len; /* length of current match */+ var best_len = s.prev_length; /* best match length so far */+ var nice_match = s.nice_match; /* stop if match long enough */+ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?+ s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;- var Blob = require('blob');+ var _win = s.window; // shortcut- /**- * Encodes a packet.- *- * <packet type id> [ <data> ]- *- * Example:- *- * 5hello world- * 3- * 4- *- * Binary is encoded in an identical principle- *- * @api private- */+ var wmask = s.w_mask;+ var prev = s.prev;- exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {- if ('function' == typeof supportsBinary) {- callback = supportsBinary;- supportsBinary = false;- }+ /* Stop when cur_match becomes <= limit. To simplify the code,+ * we prevent matches with the string of window index 0.+ */- if ('function' == typeof utf8encode) {- callback = utf8encode;- utf8encode = null;- }+ var strend = s.strstart + MAX_MATCH;+ var scan_end1 = _win[scan + best_len - 1];+ var scan_end = _win[scan + best_len];- var data = (packet.data === undefined)- ? undefined- : packet.data.buffer || packet.data;+ /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.+ * It is easy to get rid of this optimization if necessary.+ */+ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");- if (global.ArrayBuffer && data instanceof ArrayBuffer) {- return encodeArrayBuffer(packet, supportsBinary, callback);- } else if (Blob && data instanceof global.Blob) {- return encodeBlob(packet, supportsBinary, callback);+ /* Do not waste too much time if we already have a good match: */+ if (s.prev_length >= s.good_match) {+ chain_length >>= 2;}+ /* Do not look for matches beyond the end of the input. This is necessary+ * to make deflate deterministic.+ */+ if (nice_match > s.lookahead) { nice_match = s.lookahead; }- // might be an object with { base64: true, data: dataAsBase64String }- if (data && data.base64) {- return encodeBase64Object(packet, callback);- }+ // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");- // Sending data as a utf-8 string- var encoded = packets[packet.type];+ do {+ // Assert(cur_match < s->strstart, "no future");+ match = cur_match;- // data fragment is optional- if (undefined !== packet.data) {- encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);- }+ /* Skip to next match if the match length cannot increase+ * or if the match length is less than 2. Note that the checks below+ * for insufficient lookahead only occur occasionally for performance+ * reasons. Therefore uninitialized memory will be accessed, and+ * conditional jumps will be made that depend on those values.+ * However the length of the match is limited to the lookahead, so+ * the output of deflate is not affected by the uninitialized values.+ */- return callback('' + encoded);+ if (_win[match + best_len] !== scan_end ||+ _win[match + best_len - 1] !== scan_end1 ||+ _win[match] !== _win[scan] ||+ _win[++match] !== _win[scan + 1]) {+ continue;+ }- };+ /* The check at best_len-1 can be removed because it will be made+ * again later. (This heuristic is not always a win.)+ * It is not necessary to compare scan[2] and match[2] since they+ * are always equal when the other bytes match, given that+ * the hash keys are equal and that HASH_BITS >= 8.+ */+ scan += 2;+ match++;+ // Assert(*scan == *match, "match[2]?");- function encodeBase64Object(packet, callback) {- // packet data is an object { base64: true, data: dataAsBase64String }- var message = 'b' + exports.packets[packet.type] + packet.data.data;- return callback(message);- }+ /* We check for insufficient lookahead only every 8th comparison;+ * the 256th check will be made at strstart+258.+ */+ do {+ /*jshint noempty:false*/+ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ scan < strend);- /**- * Encode packet helpers for binary types- */+ // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");- function encodeArrayBuffer(packet, supportsBinary, callback) {- if (!supportsBinary) {- return exports.encodeBase64Packet(packet, callback);- }+ len = MAX_MATCH - (strend - scan);+ scan = strend - MAX_MATCH;- var data = packet.data;- var contentArray = new Uint8Array(data);- var resultBuffer = new Uint8Array(1 + data.byteLength);+ if (len > best_len) {+ s.match_start = cur_match;+ best_len = len;+ if (len >= nice_match) {+ break;+ }+ scan_end1 = _win[scan + best_len - 1];+ scan_end = _win[scan + best_len];+ }+ } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);- resultBuffer[0] = packets[packet.type];- for (var i = 0; i < contentArray.length; i++) {- resultBuffer[i+1] = contentArray[i];+ if (best_len <= s.lookahead) {+ return best_len;}-- return callback(resultBuffer.buffer);+ return s.lookahead;}- function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {- if (!supportsBinary) {- return exports.encodeBase64Packet(packet, callback);- }-- var fr = new FileReader();- fr.onload = function() {- packet.data = fr.result;- exports.encodePacket(packet, supportsBinary, true, callback);- };- return fr.readAsArrayBuffer(packet.data);- }- function encodeBlob(packet, supportsBinary, callback) {- if (!supportsBinary) {- return exports.encodeBase64Packet(packet, callback);- }+ /* ===========================================================================+ * Fill the window when the lookahead becomes insufficient.+ * Updates strstart and lookahead.+ *+ * IN assertion: lookahead < MIN_LOOKAHEAD+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD+ * At least one byte has been read, or avail_in == 0; reads are+ * performed for at least two bytes (required for the zip translate_eol+ * option -- not supported here).+ */+ function fill_window(s) {+ var _w_size = s.w_size;+ var p, n, m, more, str;- if (dontSendBlobs) {- return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);- }+ //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");- var length = new Uint8Array(1);- length[0] = packets[packet.type];- var blob = new Blob([length.buffer, packet.data]);+ do {+ more = s.window_size - s.lookahead - s.strstart;- return callback(blob);- }+ // JS ints have 32 bit, block below not needed+ /* Deal with !@#$% 64K limit: */+ //if (sizeof(int) <= 2) {+ // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {+ // more = wsize;+ //+ // } else if (more == (unsigned)(-1)) {+ // /* Very unlikely, but possible on 16 bit machine if+ // * strstart == 0 && lookahead == 1 (input done a byte at time)+ // */+ // more--;+ // }+ //}- /**- * Encodes a packet with binary data in a base64 string- *- * @param {Object} packet, has `type` and `data`- * @return {String} base64 encoded message- */- exports.encodeBase64Packet = function(packet, callback) {- var message = 'b' + exports.packets[packet.type];- if (Blob && packet.data instanceof Blob) {- var fr = new FileReader();- fr.onload = function() {- var b64 = fr.result.split(',')[1];- callback(message + b64);- };- return fr.readAsDataURL(packet.data);- }+ /* If the window is almost full and there is insufficient lookahead,+ * move the upper half to the lower one to make room in the upper half.+ */+ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {- var b64data;- try {- b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));- } catch (e) {- // iPhone Safari doesn't let you apply with typed arrays- var typed = new Uint8Array(packet.data);- var basic = new Array(typed.length);- for (var i = 0; i < typed.length; i++) {- basic[i] = typed[i];- }- b64data = String.fromCharCode.apply(null, basic);- }- message += global.btoa(b64data);- return callback(message);- };+ utils.arraySet(s.window, s.window, _w_size, _w_size, 0);+ s.match_start -= _w_size;+ s.strstart -= _w_size;+ /* we now have strstart >= MAX_DIST */+ s.block_start -= _w_size;- /**- * Decodes a packet. Changes format to Blob if requested.- *- * @return {Object} with `type` and `data` (if any)- * @api private- */+ /* Slide the hash table (could be avoided with 32 bit values+ at the expense of memory usage). We slide even when level == 0+ to keep the hash table consistent if we switch back to level > 0+ later. (Using level 0 permanently is not an optimal usage of+ zlib, so we don't care about this pathological case.)+ */- exports.decodePacket = function (data, binaryType, utf8decode) {- // String data- if (typeof data == 'string' || data === undefined) {- if (data.charAt(0) == 'b') {- return exports.decodeBase64Packet(data.substr(1), binaryType);- }+ n = s.hash_size;+ p = n;+ do {+ m = s.head[--p];+ s.head[p] = (m >= _w_size ? m - _w_size : 0);+ } while (--n);- if (utf8decode) {- try {- data = utf8.decode(data);- } catch (e) {- return err;- }- }- var type = data.charAt(0);+ n = _w_size;+ p = n;+ do {+ m = s.prev[--p];+ s.prev[p] = (m >= _w_size ? m - _w_size : 0);+ /* If n is not on any hash chain, prev[n] is garbage but+ * its value will never be used.+ */+ } while (--n);- if (Number(type) != type || !packetslist[type]) {- return err;+ more += _w_size;}-- if (data.length > 1) {- return { type: packetslist[type], data: data.substring(1) };- } else {- return { type: packetslist[type] };+ if (s.strm.avail_in === 0) {+ break;}- }- var asArray = new Uint8Array(data);- var type = asArray[0];- var rest = sliceBuffer(data, 1);- if (Blob && binaryType === 'blob') {- rest = new Blob([rest]);- }- return { type: packetslist[type], data: rest };- };-- /**- * Decodes a packet encoded in a base64 string- *- * @param {String} base64 encoded message- * @return {Object} with `type` and `data` (if any)- */+ /* If there was no sliding:+ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&+ * more == window_size - lookahead - strstart+ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)+ * => more >= window_size - 2*WSIZE + 2+ * In the BIG_MEM or MMAP case (not yet supported),+ * window_size == input_size + MIN_LOOKAHEAD &&+ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.+ * Otherwise, window_size == 2*WSIZE so more >= 2.+ * If there was sliding, more >= WSIZE. So in all cases, more >= 2.+ */+ //Assert(more >= 2, "more < 2");+ n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);+ s.lookahead += n;- exports.decodeBase64Packet = function(msg, binaryType) {- var type = packetslist[msg.charAt(0)];- if (!global.ArrayBuffer) {- return { type: type, data: { base64: true, data: msg.substr(1) } };- }+ /* Initialize the hash value now that we have some input: */+ if (s.lookahead + s.insert >= MIN_MATCH) {+ str = s.strstart - s.insert;+ s.ins_h = s.window[str];- var data = base64encoder.decode(msg.substr(1));+ /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;+ //#if MIN_MATCH != 3+ // Call update_hash() MIN_MATCH-3 more times+ //#endif+ while (s.insert) {+ /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;- if (binaryType === 'blob' && Blob) {- data = new Blob([data]);- }+ s.prev[str & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = str;+ str++;+ s.insert--;+ if (s.lookahead + s.insert < MIN_MATCH) {+ break;+ }+ }+ }+ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,+ * but this is not important since only literal bytes will be emitted.+ */- return { type: type, data: data };- };+ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);- /**- * Encodes multiple messages (payload).- *- * <length>:data- *- * Example:- *- * 11:hello world2:hi- *- * If any contents are binary, they will be encoded as base64 strings. Base64- * encoded strings are marked with a b before the length specifier- *- * @param {Array} packets- * @api private- */-- exports.encodePayload = function (packets, supportsBinary, callback) {- if (typeof supportsBinary == 'function') {- callback = supportsBinary;- supportsBinary = null;- }-- var isBinary = hasBinary(packets);-- if (supportsBinary && isBinary) {- if (Blob && !dontSendBlobs) {- return exports.encodePayloadAsBlob(packets, callback);- }+ /* If the WIN_INIT bytes after the end of the current data have never been+ * written, then zero those bytes in order to avoid memory check reports of+ * the use of uninitialized (or uninitialised as Julian writes) bytes by+ * the longest match routines. Update the high water mark for the next+ * time through here. WIN_INIT is set to MAX_MATCH since the longest match+ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.+ */+ // if (s.high_water < s.window_size) {+ // var curr = s.strstart + s.lookahead;+ // var init = 0;+ //+ // if (s.high_water < curr) {+ // /* Previous high water mark below current data -- zero WIN_INIT+ // * bytes or up to end of window, whichever is less.+ // */+ // init = s.window_size - curr;+ // if (init > WIN_INIT)+ // init = WIN_INIT;+ // zmemzero(s->window + curr, (unsigned)init);+ // s->high_water = curr + init;+ // }+ // else if (s->high_water < (ulg)curr + WIN_INIT) {+ // /* High water mark at or above current data, but below current data+ // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up+ // * to end of window, whichever is less.+ // */+ // init = (ulg)curr + WIN_INIT - s->high_water;+ // if (init > s->window_size - s->high_water)+ // init = s->window_size - s->high_water;+ // zmemzero(s->window + s->high_water, (unsigned)init);+ // s->high_water += init;+ // }+ // }+ //+ // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,+ // "not enough room for search");+ }- return exports.encodePayloadAsArrayBuffer(packets, callback);- }+ /* ===========================================================================+ * Copy without compression as much as possible from the input stream, return+ * the current block state.+ * This function does not insert new strings in the dictionary since+ * uncompressible data is probably not useful. This function is used+ * only for the level=0 compression option.+ * NOTE: this function should be optimized to avoid extra copying from+ * window to pending_buf.+ */+ function deflate_stored(s, flush) {+ /* Stored blocks are limited to 0xffff bytes, pending_buf is limited+ * to pending_buf_size, and each stored block has a 5 byte header:+ */+ var max_block_size = 0xffff;- if (!packets.length) {- return callback('0:');+ if (max_block_size > s.pending_buf_size - 5) {+ max_block_size = s.pending_buf_size - 5;}- function setLengthHeader(message) {- return message.length + ':' + message;- }+ /* Copy as much as possible from input to output: */+ for (;;) {+ /* Fill the window as much as possible: */+ if (s.lookahead <= 1) {- function encodeOne(packet, doneCallback) {- exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {- doneCallback(null, setLengthHeader(message));- });- }+ //Assert(s->strstart < s->w_size+MAX_DIST(s) ||+ // s->block_start >= (long)s->w_size, "slide too late");+ // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||+ // s.block_start >= s.w_size)) {+ // throw new Error("slide too late");+ // }- map(packets, encodeOne, function(err, results) {- return callback(results.join(''));- });- };+ fill_window(s);+ if (s.lookahead === 0 && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;+ }- /**- * Async array map using after- */+ if (s.lookahead === 0) {+ break;+ }+ /* flush the current block */+ }+ //Assert(s->block_start >= 0L, "block gone");+ // if (s.block_start < 0) throw new Error("block gone");- function map(ary, each, done) {- var result = new Array(ary.length);- var next = after(ary.length, done);+ s.strstart += s.lookahead;+ s.lookahead = 0;- var eachWithIndex = function(i, el, cb) {- each(el, function(error, msg) {- result[i] = msg;- cb(error, result);- });- };+ /* Emit a stored block if pending_buf will be full: */+ var max_start = s.block_start + max_block_size;- for (var i = 0; i < ary.length; i++) {- eachWithIndex(i, ary[i], next);- }- }+ if (s.strstart === 0 || s.strstart >= max_start) {+ /* strstart == 0 is possible when wraparound on 16-bit machine */+ s.lookahead = s.strstart - max_start;+ s.strstart = max_start;+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/- /*- * Decodes data when a payload is maybe expected. Possible binary contents are- * decoded from their base64 representation- *- * @param {String} data, callback method- * @api public- */- exports.decodePayload = function (data, binaryType, callback) {- if (typeof data != 'string') {- return exports.decodePayloadAsBinary(data, binaryType, callback);+ }+ /* Flush if we may have to slide, otherwise block_start may become+ * negative and the data will be gone:+ */+ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }}- if (typeof binaryType === 'function') {- callback = binaryType;- binaryType = null;+ s.insert = 0;++ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;}- var packet;- if (data == '') {- // parser error - ignoring payload- return callback(err, 0, 1);+ if (s.strstart > s.block_start) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/}- var length = ''- , n, msg;+ return BS_NEED_MORE;+ }- for (var i = 0, l = data.length; i < l; i++) {- var chr = data.charAt(i);+ /* ===========================================================================+ * Compress as much as possible from the input stream, return the current+ * block state.+ * This function does not perform lazy evaluation of matches and inserts+ * new strings in the dictionary only for unmatched strings or for short+ * matches. It is used only for the fast compression options.+ */+ function deflate_fast(s, flush) {+ var hash_head; /* head of the hash chain */+ var bflush; /* set if current block must be flushed */- if (':' != chr) {- length += chr;- } else {- if ('' == length || (length != (n = Number(length)))) {- // parser error - ignoring payload- return callback(err, 0, 1);+ for (;;) {+ /* Make sure that we always have enough lookahead, except+ * at the end of the input file. We need MAX_MATCH bytes+ * for the next match, plus MIN_MATCH bytes to insert the+ * string following the next match.+ */+ if (s.lookahead < MIN_LOOKAHEAD) {+ fill_window(s);+ if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;}-- msg = data.substr(i + 1, n);-- if (length != msg.length) {- // parser error - ignoring payload- return callback(err, 0, 1);+ if (s.lookahead === 0) {+ break; /* flush the current block */}+ }- if (msg.length) {- packet = exports.decodePacket(msg, binaryType, true);+ /* Insert the string window[strstart .. strstart+2] in the+ * dictionary, and set hash_head to the head of the hash chain:+ */+ hash_head = 0/*NIL*/;+ if (s.lookahead >= MIN_MATCH) {+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ }- if (err.type == packet.type && err.data == packet.data) {- // parser error in individual packet - ignoring payload- return callback(err, 0, 1);- }+ /* Find the longest match, discarding those <= prev_length.+ * At this point we have always match_length < MIN_MATCH+ */+ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {+ /* To simplify the code, we prevent matches with the string+ * of window index 0 (in particular we have to avoid a match+ * of the string with itself at the start of the input file).+ */+ s.match_length = longest_match(s, hash_head);+ /* longest_match() sets match_start */+ }+ if (s.match_length >= MIN_MATCH) {+ // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only- var ret = callback(packet, i + n, l);- if (false === ret) return;- }+ /*** _tr_tally_dist(s, s.strstart - s.match_start,+ s.match_length - MIN_MATCH, bflush); ***/+ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);- // advance cursor- i += n;- length = '';+ s.lookahead -= s.match_length;++ /* Insert new strings in the hash table only if the match length+ * is not too large. This saves time but degrades compression.+ */+ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {+ s.match_length--; /* string at strstart already in table */+ do {+ s.strstart++;+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ /* strstart never exceeds WSIZE-MAX_MATCH, so there are+ * always MIN_MATCH bytes ahead.+ */+ } while (--s.match_length !== 0);+ s.strstart++;+ } else+ {+ s.strstart += s.match_length;+ s.match_length = 0;+ s.ins_h = s.window[s.strstart];+ /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;++ //#if MIN_MATCH != 3+ // Call UPDATE_HASH() MIN_MATCH-3 more times+ //#endif+ /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not+ * matter since it will be recomputed at next deflate call.+ */+ }+ } else {+ /* No match, output a literal byte */+ //Tracevv((stderr,"%c", s.window[s.strstart]));+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);++ s.lookahead--;+ s.strstart++;+ }+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/}}-- if (length != '') {- // parser error - ignoring payload- return callback(err, 0, 1);+ s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;}+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ return BS_BLOCK_DONE;+ }- };-- /**- * Encodes multiple messages (payload) as binary.- *- * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number- * 255><data>- *- * Example:- * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers- *- * @param {Array} packets- * @return {ArrayBuffer} encoded payload- * @api private+ /* ===========================================================================+ * Same as above, but achieves better compression. We use a lazy+ * evaluation for matches: a match is finally adopted only if there is+ * no better match at the next window position.*/+ function deflate_slow(s, flush) {+ var hash_head; /* head of hash chain */+ var bflush; /* set if current block must be flushed */- exports.encodePayloadAsArrayBuffer = function(packets, callback) {- if (!packets.length) {- return callback(new ArrayBuffer(0));- }-- function encodeOne(packet, doneCallback) {- exports.encodePacket(packet, true, true, function(data) {- return doneCallback(null, data);- });- }+ var max_insert;- map(packets, encodeOne, function(err, encodedPackets) {- var totalLength = encodedPackets.reduce(function(acc, p) {- var len;- if (typeof p === 'string'){- len = p.length;- } else {- len = p.byteLength;+ /* Process the input block. */+ for (;;) {+ /* Make sure that we always have enough lookahead, except+ * at the end of the input file. We need MAX_MATCH bytes+ * for the next match, plus MIN_MATCH bytes to insert the+ * string following the next match.+ */+ if (s.lookahead < MIN_LOOKAHEAD) {+ fill_window(s);+ if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;}- return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2- }, 0);+ if (s.lookahead === 0) { break; } /* flush the current block */+ }- var resultArray = new Uint8Array(totalLength);+ /* Insert the string window[strstart .. strstart+2] in the+ * dictionary, and set hash_head to the head of the hash chain:+ */+ hash_head = 0/*NIL*/;+ if (s.lookahead >= MIN_MATCH) {+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ }- var bufferIndex = 0;- encodedPackets.forEach(function(p) {- var isString = typeof p === 'string';- var ab = p;- if (isString) {- var view = new Uint8Array(p.length);- for (var i = 0; i < p.length; i++) {- view[i] = p.charCodeAt(i);- }- ab = view.buffer;- }+ /* Find the longest match, discarding those <= prev_length.+ */+ s.prev_length = s.match_length;+ s.prev_match = s.match_start;+ s.match_length = MIN_MATCH-1;- if (isString) { // not true binary- resultArray[bufferIndex++] = 0;- } else { // true binary- resultArray[bufferIndex++] = 1;- }+ if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&+ s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {+ /* To simplify the code, we prevent matches with the string+ * of window index 0 (in particular we have to avoid a match+ * of the string with itself at the start of the input file).+ */+ s.match_length = longest_match(s, hash_head);+ /* longest_match() sets match_start */- var lenStr = ab.byteLength.toString();- for (var i = 0; i < lenStr.length; i++) {- resultArray[bufferIndex++] = parseInt(lenStr[i]);- }- resultArray[bufferIndex++] = 255;+ if (s.match_length <= 5 &&+ (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {- var view = new Uint8Array(ab);- for (var i = 0; i < view.length; i++) {- resultArray[bufferIndex++] = view[i];+ /* If prev_match is also MIN_MATCH, match_start is garbage+ * but we will ignore the current match anyway.+ */+ s.match_length = MIN_MATCH-1;}- });+ }+ /* If there was a match at the previous step and the current+ * match is not better, output the previous match:+ */+ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {+ max_insert = s.strstart + s.lookahead - MIN_MATCH;+ /* Do not insert strings in hash table beyond this. */- return callback(resultArray.buffer);- });- };+ //check_match(s, s.strstart-1, s.prev_match, s.prev_length);- /**- * Encode as Blob- */+ /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,+ s.prev_length - MIN_MATCH, bflush);***/+ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);+ /* Insert in hash table all strings up to the end of the match.+ * strstart-1 and strstart are already inserted. If there is not+ * enough lookahead, the last two strings are not inserted in+ * the hash table.+ */+ s.lookahead -= s.prev_length-1;+ s.prev_length -= 2;+ do {+ if (++s.strstart <= max_insert) {+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ }+ } while (--s.prev_length !== 0);+ s.match_available = 0;+ s.match_length = MIN_MATCH-1;+ s.strstart++;- exports.encodePayloadAsBlob = function(packets, callback) {- function encodeOne(packet, doneCallback) {- exports.encodePacket(packet, true, true, function(encoded) {- var binaryIdentifier = new Uint8Array(1);- binaryIdentifier[0] = 1;- if (typeof encoded === 'string') {- var view = new Uint8Array(encoded.length);- for (var i = 0; i < encoded.length; i++) {- view[i] = encoded.charCodeAt(i);+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;}- encoded = view.buffer;- binaryIdentifier[0] = 0;+ /***/}- var len = (encoded instanceof ArrayBuffer)- ? encoded.byteLength- : encoded.size;+ } else if (s.match_available) {+ /* If there was no match at the previous position, output a+ * single literal. If there was a match but the current match+ * is longer, truncate the previous match to a single literal.+ */+ //Tracevv((stderr,"%c", s->window[s->strstart-1]));+ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);- var lenStr = len.toString();- var lengthAry = new Uint8Array(lenStr.length + 1);- for (var i = 0; i < lenStr.length; i++) {- lengthAry[i] = parseInt(lenStr[i]);- }- lengthAry[lenStr.length] = 255;-- if (Blob) {- var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);- doneCallback(null, blob);+ if (bflush) {+ /*** FLUSH_BLOCK_ONLY(s, 0) ***/+ flush_block_only(s, false);+ /***/}- });- }-- map(packets, encodeOne, function(err, results) {- return callback(new Blob(results));- });- };-- /*- * Decodes data when a payload is maybe expected. Strings are decoded by- * interpreting each byte as a key code for entries marked to start with 0. See- * description of encodePayloadAsBinary- *- * @param {ArrayBuffer} data, callback method- * @api public- */-- exports.decodePayloadAsBinary = function (data, binaryType, callback) {- if (typeof binaryType === 'function') {- callback = binaryType;- binaryType = null;- }-- var bufferTail = data;- var buffers = [];-- var numberTooLong = false;- while (bufferTail.byteLength > 0) {- var tailArray = new Uint8Array(bufferTail);- var isString = tailArray[0] === 0;- var msgLength = '';-- for (var i = 1; ; i++) {- if (tailArray[i] == 255) break;-- if (msgLength.length > 310) {- numberTooLong = true;- break;+ s.strstart++;+ s.lookahead--;+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;}-- msgLength += tailArray[i];+ } else {+ /* There is no previous match to compare with, wait for+ * the next step to decide.+ */+ s.match_available = 1;+ s.strstart++;+ s.lookahead--;}+ }+ //Assert (flush != Z_NO_FLUSH, "no flush?");+ if (s.match_available) {+ //Tracevv((stderr,"%c", s->window[s->strstart-1]));+ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);- if(numberTooLong) return callback(err, 0, 1);-- bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);- msgLength = parseInt(msgLength);-- var msg = sliceBuffer(bufferTail, 0, msgLength);- if (isString) {- try {- msg = String.fromCharCode.apply(null, new Uint8Array(msg));- } catch (e) {- // iPhone Safari doesn't let you apply to typed arrays- var typed = new Uint8Array(msg);- msg = '';- for (var i = 0; i < typed.length; i++) {- msg += String.fromCharCode(typed[i]);- }- }+ s.match_available = 0;+ }+ s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;}-- buffers.push(msg);- bufferTail = sliceBuffer(bufferTail, msgLength);+ /***/+ return BS_FINISH_DONE;}-- var total = buffers.length;- buffers.forEach(function(buffer, i) {- callback(exports.decodePacket(buffer, binaryType, true), i, total);- });- };-- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"./keys":70,"after":45,"arraybuffer.slice":46,"base64-arraybuffer":49,"blob":50,"has-binary":71,"utf8":128}],70:[function(require,module,exports){-- /**- * Gets the keys for an object.- *- * @return {Array} keys- * @api private- */-- module.exports = Object.keys || function keys (obj){- var arr = [];- var has = Object.prototype.hasOwnProperty;-- for (var i in obj) {- if (has.call(obj, i)) {- arr.push(i);+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;}+ /***/}- return arr;- };-- },{}],71:[function(require,module,exports){- (function (global){- /*- * Module requirements.- */-- var isArray = require('isarray');-- /**- * Module exports.- */+ return BS_BLOCK_DONE;+ }- module.exports = hasBinary;- /**- * Checks for binary data.- *- * Right now only Buffer and ArrayBuffer are supported..- *- * @param {Object} anything- * @api public+ /* ===========================================================================+ * For Z_RLE, simply look for runs of bytes, generate matches only of distance+ * one. Do not maintain a hash table. (It will be regenerated if this run of+ * deflate switches away from Z_RLE.)*/+ function deflate_rle(s, flush) {+ var bflush; /* set if current block must be flushed */+ var prev; /* byte at distance one to match */+ var scan, strend; /* scan goes up to strend for length of run */- function hasBinary(data) {-- function _hasBinary(obj) {- if (!obj) return false;-- if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||- (global.ArrayBuffer && obj instanceof ArrayBuffer) ||- (global.Blob && obj instanceof Blob) ||- (global.File && obj instanceof File)- ) {- return true;- }+ var _win = s.window;- if (isArray(obj)) {- for (var i = 0; i < obj.length; i++) {- if (_hasBinary(obj[i])) {- return true;- }- }- } else if (obj && 'object' == typeof obj) {- if (obj.toJSON) {- obj = obj.toJSON();+ for (;;) {+ /* Make sure that we always have enough lookahead, except+ * at the end of the input file. We need MAX_MATCH bytes+ * for the longest run, plus one for the unrolled loop.+ */+ if (s.lookahead <= MAX_MATCH) {+ fill_window(s);+ if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;}+ if (s.lookahead === 0) { break; } /* flush the current block */+ }- for (var key in obj) {- if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {- return true;+ /* See how many times the previous byte repeats */+ s.match_length = 0;+ if (s.lookahead >= MIN_MATCH && s.strstart > 0) {+ scan = s.strstart - 1;+ prev = _win[scan];+ if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {+ strend = s.strstart + MAX_MATCH;+ do {+ /*jshint noempty:false*/+ } while (prev === _win[++scan] && prev === _win[++scan] &&+ prev === _win[++scan] && prev === _win[++scan] &&+ prev === _win[++scan] && prev === _win[++scan] &&+ prev === _win[++scan] && prev === _win[++scan] &&+ scan < strend);+ s.match_length = MAX_MATCH - (strend - scan);+ if (s.match_length > s.lookahead) {+ s.match_length = s.lookahead;}}+ //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");}- return false;- }-- return _hasBinary(data);- }+ /* Emit match if have run of MIN_MATCH or longer, else emit literal */+ if (s.match_length >= MIN_MATCH) {+ //check_match(s, s.strstart, s.strstart - 1, s.match_length);- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"isarray":77}],72:[function(require,module,exports){- (function (process,global){- /*!- * @overview es6-promise - a tiny implementation of Promises/A+.- * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)- * @license Licensed under MIT license- * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE- * @version 3.0.2- */+ /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/+ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);- (function() {- "use strict";- function lib$es6$promise$utils$$objectOrFunction(x) {- return typeof x === 'function' || (typeof x === 'object' && x !== null);- }+ s.lookahead -= s.match_length;+ s.strstart += s.match_length;+ s.match_length = 0;+ } else {+ /* No match, output a literal byte */+ //Tracevv((stderr,"%c", s->window[s->strstart]));+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);- function lib$es6$promise$utils$$isFunction(x) {- return typeof x === 'function';+ s.lookahead--;+ s.strstart++;}-- function lib$es6$promise$utils$$isMaybeThenable(x) {- return typeof x === 'object' && x !== null;+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/}-- var lib$es6$promise$utils$$_isArray;- if (!Array.isArray) {- lib$es6$promise$utils$$_isArray = function (x) {- return Object.prototype.toString.call(x) === '[object Array]';- };- } else {- lib$es6$promise$utils$$_isArray = Array.isArray;+ }+ s.insert = 0;+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;+ }+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;}+ /***/+ }+ return BS_BLOCK_DONE;+ }- var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;- var lib$es6$promise$asap$$len = 0;- var lib$es6$promise$asap$$toString = {}.toString;- var lib$es6$promise$asap$$vertxNext;- var lib$es6$promise$asap$$customSchedulerFn;+ /* ===========================================================================+ * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.+ * (It will be regenerated if this run of deflate switches away from Huffman.)+ */+ function deflate_huff(s, flush) {+ var bflush; /* set if current block must be flushed */- var lib$es6$promise$asap$$asap = function asap(callback, arg) {- lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;- lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;- lib$es6$promise$asap$$len += 2;- if (lib$es6$promise$asap$$len === 2) {- // If len is 2, that means that we need to schedule an async flush.- // If additional callbacks are queued before the queue is flushed, they- // will be processed by this flush that we are scheduling.- if (lib$es6$promise$asap$$customSchedulerFn) {- lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);- } else {- lib$es6$promise$asap$$scheduleFlush();+ for (;;) {+ /* Make sure that we have a literal to write. */+ if (s.lookahead === 0) {+ fill_window(s);+ if (s.lookahead === 0) {+ if (flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;}+ break; /* flush the current block */}}- function lib$es6$promise$asap$$setScheduler(scheduleFn) {- lib$es6$promise$asap$$customSchedulerFn = scheduleFn;+ /* Output a literal byte */+ s.match_length = 0;+ //Tracevv((stderr,"%c", s->window[s->strstart]));+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);+ s.lookahead--;+ s.strstart++;+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/}-- function lib$es6$promise$asap$$setAsap(asapFn) {- lib$es6$promise$asap$$asap = asapFn;+ }+ s.insert = 0;+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;}-- var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;- var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};- var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;- var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';-- // test for web worker but not in IE10- var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&- typeof importScripts !== 'undefined' &&- typeof MessageChannel !== 'undefined';-- // node- function lib$es6$promise$asap$$useNextTick() {- // node version 0.10.x displays a deprecation warning when nextTick is used recursively- // see https://github.com/cujojs/when/issues/410 for details- return function() {- process.nextTick(lib$es6$promise$asap$$flush);- };+ /***/+ return BS_FINISH_DONE;+ }+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;}+ /***/+ }+ return BS_BLOCK_DONE;+ }- // vertx- function lib$es6$promise$asap$$useVertxTimer() {- return function() {- lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);- };- }+ /* Values for max_lazy_match, good_match and max_chain_length, depending on+ * the desired pack level (0..9). The values given below have been tuned to+ * exclude worst case performance for pathological files. Better values may be+ * found for specific files.+ */+ var Config = function (good_length, max_lazy, nice_length, max_chain, func) {+ this.good_length = good_length;+ this.max_lazy = max_lazy;+ this.nice_length = nice_length;+ this.max_chain = max_chain;+ this.func = func;+ };- function lib$es6$promise$asap$$useMutationObserver() {- var iterations = 0;- var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);- var node = document.createTextNode('');- observer.observe(node, { characterData: true });+ var configuration_table;- return function() {- node.data = (iterations = ++iterations % 2);- };- }+ configuration_table = [+ /* good lazy nice chain */+ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */+ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */+ new Config(4, 5, 16, 8, deflate_fast), /* 2 */+ new Config(4, 6, 32, 32, deflate_fast), /* 3 */- // web worker- function lib$es6$promise$asap$$useMessageChannel() {- var channel = new MessageChannel();- channel.port1.onmessage = lib$es6$promise$asap$$flush;- return function () {- channel.port2.postMessage(0);- };- }+ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */+ new Config(8, 16, 32, 32, deflate_slow), /* 5 */+ new Config(8, 16, 128, 128, deflate_slow), /* 6 */+ new Config(8, 32, 128, 256, deflate_slow), /* 7 */+ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */+ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */+ ];- function lib$es6$promise$asap$$useSetTimeout() {- return function() {- setTimeout(lib$es6$promise$asap$$flush, 1);- };- }- var lib$es6$promise$asap$$queue = new Array(1000);- function lib$es6$promise$asap$$flush() {- for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {- var callback = lib$es6$promise$asap$$queue[i];- var arg = lib$es6$promise$asap$$queue[i+1];+ /* ===========================================================================+ * Initialize the "longest match" routines for a new zlib stream+ */+ function lm_init(s) {+ s.window_size = 2 * s.w_size;- callback(arg);+ /*** CLEAR_HASH(s); ***/+ zero(s.head); // Fill with NIL (= 0);- lib$es6$promise$asap$$queue[i] = undefined;- lib$es6$promise$asap$$queue[i+1] = undefined;- }+ /* Set the default configuration parameters:+ */+ s.max_lazy_match = configuration_table[s.level].max_lazy;+ s.good_match = configuration_table[s.level].good_length;+ s.nice_match = configuration_table[s.level].nice_length;+ s.max_chain_length = configuration_table[s.level].max_chain;- lib$es6$promise$asap$$len = 0;- }+ s.strstart = 0;+ s.block_start = 0;+ s.lookahead = 0;+ s.insert = 0;+ s.match_length = s.prev_length = MIN_MATCH - 1;+ s.match_available = 0;+ s.ins_h = 0;+ }- function lib$es6$promise$asap$$attemptVertx() {- try {- var r = require;- var vertx = r('vertx');- lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;- return lib$es6$promise$asap$$useVertxTimer();- } catch(e) {- return lib$es6$promise$asap$$useSetTimeout();- }- }- var lib$es6$promise$asap$$scheduleFlush;- // Decide what async method to use to triggering processing of queued callbacks:- if (lib$es6$promise$asap$$isNode) {- lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();- } else if (lib$es6$promise$asap$$BrowserMutationObserver) {- lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();- } else if (lib$es6$promise$asap$$isWorker) {- lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();- } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {- lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();- } else {- lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();- }+ function DeflateState() {+ this.strm = null; /* pointer back to this zlib stream */+ this.status = 0; /* as the name implies */+ this.pending_buf = null; /* output still pending */+ this.pending_buf_size = 0; /* size of pending_buf */+ this.pending_out = 0; /* next pending byte to output to the stream */+ this.pending = 0; /* nb of bytes in the pending buffer */+ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */+ this.gzhead = null; /* gzip header information to write */+ this.gzindex = 0; /* where in extra, name, or comment */+ this.method = Z_DEFLATED; /* can only be DEFLATED */+ this.last_flush = -1; /* value of flush param for previous deflate call */- function lib$es6$promise$$internal$$noop() {}+ this.w_size = 0; /* LZ77 window size (32K by default) */+ this.w_bits = 0; /* log2(w_size) (8..16) */+ this.w_mask = 0; /* w_size - 1 */- var lib$es6$promise$$internal$$PENDING = void 0;- var lib$es6$promise$$internal$$FULFILLED = 1;- var lib$es6$promise$$internal$$REJECTED = 2;+ this.window = null;+ /* Sliding window. Input bytes are read into the second half of the window,+ * and move to the first half later to keep a dictionary of at least wSize+ * bytes. With this organization, matches are limited to a distance of+ * wSize-MAX_MATCH bytes, but this ensures that IO is always+ * performed with a length multiple of the block size.+ */- var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();+ this.window_size = 0;+ /* Actual size of window: 2*wSize, except when the user input buffer+ * is directly used as sliding window.+ */- function lib$es6$promise$$internal$$selfFulfillment() {- return new TypeError("You cannot resolve a promise with itself");- }-- function lib$es6$promise$$internal$$cannotReturnOwn() {- return new TypeError('A promises callback cannot return that same promise.');- }-- function lib$es6$promise$$internal$$getThen(promise) {- try {- return promise.then;- } catch(error) {- lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;- return lib$es6$promise$$internal$$GET_THEN_ERROR;- }- }+ this.prev = null;+ /* Link to older string with same hash index. To limit the size of this+ * array to 64K, this link is maintained only for the last 32K strings.+ * An index in this array is thus a window index modulo 32K.+ */- function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {- try {- then.call(value, fulfillmentHandler, rejectionHandler);- } catch(e) {- return e;- }- }+ this.head = null; /* Heads of the hash chains or NIL. */- function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {- lib$es6$promise$asap$$asap(function(promise) {- var sealed = false;- var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {- if (sealed) { return; }- sealed = true;- if (thenable !== value) {- lib$es6$promise$$internal$$resolve(promise, value);- } else {- lib$es6$promise$$internal$$fulfill(promise, value);- }- }, function(reason) {- if (sealed) { return; }- sealed = true;+ this.ins_h = 0; /* hash index of string to be inserted */+ this.hash_size = 0; /* number of elements in hash table */+ this.hash_bits = 0; /* log2(hash_size) */+ this.hash_mask = 0; /* hash_size-1 */- lib$es6$promise$$internal$$reject(promise, reason);- }, 'Settle: ' + (promise._label || ' unknown promise'));+ this.hash_shift = 0;+ /* Number of bits by which ins_h must be shifted at each input+ * step. It must be such that after MIN_MATCH steps, the oldest+ * byte no longer takes part in the hash key, that is:+ * hash_shift * MIN_MATCH >= hash_bits+ */- if (!sealed && error) {- sealed = true;- lib$es6$promise$$internal$$reject(promise, error);- }- }, promise);- }+ this.block_start = 0;+ /* Window position at the beginning of the current output block. Gets+ * negative when the window is moved backwards.+ */- function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {- if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {- lib$es6$promise$$internal$$fulfill(promise, thenable._result);- } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {- lib$es6$promise$$internal$$reject(promise, thenable._result);- } else {- lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {- lib$es6$promise$$internal$$resolve(promise, value);- }, function(reason) {- lib$es6$promise$$internal$$reject(promise, reason);- });- }- }+ this.match_length = 0; /* length of best match */+ this.prev_match = 0; /* previous match */+ this.match_available = 0; /* set if previous match exists */+ this.strstart = 0; /* start of string to insert */+ this.match_start = 0; /* start of matching string */+ this.lookahead = 0; /* number of valid bytes ahead in window */- function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {- if (maybeThenable.constructor === promise.constructor) {- lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);- } else {- var then = lib$es6$promise$$internal$$getThen(maybeThenable);+ this.prev_length = 0;+ /* Length of the best match at previous step. Matches not greater than this+ * are discarded. This is used in the lazy match evaluation.+ */- if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {- lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);- } else if (then === undefined) {- lib$es6$promise$$internal$$fulfill(promise, maybeThenable);- } else if (lib$es6$promise$utils$$isFunction(then)) {- lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);- } else {- lib$es6$promise$$internal$$fulfill(promise, maybeThenable);- }- }- }+ this.max_chain_length = 0;+ /* To speed up deflation, hash chains are never searched beyond this+ * length. A higher limit improves compression ratio but degrades the+ * speed.+ */- function lib$es6$promise$$internal$$resolve(promise, value) {- if (promise === value) {- lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());- } else if (lib$es6$promise$utils$$objectOrFunction(value)) {- lib$es6$promise$$internal$$handleMaybeThenable(promise, value);- } else {- lib$es6$promise$$internal$$fulfill(promise, value);- }- }+ this.max_lazy_match = 0;+ /* Attempt to find a better match only when the current match is strictly+ * smaller than this value. This mechanism is used only for compression+ * levels >= 4.+ */+ // That's alias to max_lazy_match, don't use directly+ //this.max_insert_length = 0;+ /* Insert new strings in the hash table only if the match length is not+ * greater than this length. This saves time but degrades compression.+ * max_insert_length is used only for compression levels <= 3.+ */- function lib$es6$promise$$internal$$publishRejection(promise) {- if (promise._onerror) {- promise._onerror(promise._result);- }+ this.level = 0; /* compression level (1..9) */+ this.strategy = 0; /* favor or force Huffman coding*/- lib$es6$promise$$internal$$publish(promise);- }+ this.good_match = 0;+ /* Use a faster search when the previous match is longer than this */- function lib$es6$promise$$internal$$fulfill(promise, value) {- if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }+ this.nice_match = 0; /* Stop searching when current match exceeds this */- promise._result = value;- promise._state = lib$es6$promise$$internal$$FULFILLED;+ /* used by trees.c: */- if (promise._subscribers.length !== 0) {- lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);- }- }+ /* Didn't use ct_data typedef below to suppress compiler warning */- function lib$es6$promise$$internal$$reject(promise, reason) {- if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }- promise._state = lib$es6$promise$$internal$$REJECTED;- promise._result = reason;+ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */+ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */+ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */- lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);- }+ // Use flat array of DOUBLE size, with interleaved fata,+ // because JS does not support effective+ this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);+ this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);+ this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);+ zero(this.dyn_ltree);+ zero(this.dyn_dtree);+ zero(this.bl_tree);- function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {- var subscribers = parent._subscribers;- var length = subscribers.length;+ this.l_desc = null; /* desc. for literal tree */+ this.d_desc = null; /* desc. for distance tree */+ this.bl_desc = null; /* desc. for bit length tree */- parent._onerror = null;+ //ush bl_count[MAX_BITS+1];+ this.bl_count = new utils.Buf16(MAX_BITS+1);+ /* number of codes at each bit length for an optimal tree */- subscribers[length] = child;- subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;- subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;+ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */+ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */+ zero(this.heap);- if (length === 0 && parent._state) {- lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);- }- }+ this.heap_len = 0; /* number of elements in the heap */+ this.heap_max = 0; /* element of largest frequency */+ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.+ * The same heap array is used to build all trees.+ */- function lib$es6$promise$$internal$$publish(promise) {- var subscribers = promise._subscribers;- var settled = promise._state;+ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];+ zero(this.depth);+ /* Depth of each subtree used as tie breaker for trees of equal frequency+ */- if (subscribers.length === 0) { return; }+ this.l_buf = 0; /* buffer index for literals or lengths */- var child, callback, detail = promise._result;+ this.lit_bufsize = 0;+ /* Size of match buffer for literals/lengths. There are 4 reasons for+ * limiting lit_bufsize to 64K:+ * - frequencies can be kept in 16 bit counters+ * - if compression is not successful for the first block, all input+ * data is still in the window so we can still emit a stored block even+ * when input comes from standard input. (This can also be done for+ * all blocks if lit_bufsize is not greater than 32K.)+ * - if compression is not successful for a file smaller than 64K, we can+ * even emit a stored file instead of a stored block (saving 5 bytes).+ * This is applicable only for zip (not gzip or zlib).+ * - creating new Huffman trees less frequently may not provide fast+ * adaptation to changes in the input data statistics. (Take for+ * example a binary file with poorly compressible code followed by+ * a highly compressible string table.) Smaller buffer sizes give+ * fast adaptation but have of course the overhead of transmitting+ * trees more frequently.+ * - I can't count above 4+ */- for (var i = 0; i < subscribers.length; i += 3) {- child = subscribers[i];- callback = subscribers[i + settled];+ this.last_lit = 0; /* running index in l_buf */- if (child) {- lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);- } else {- callback(detail);- }- }+ this.d_buf = 0;+ /* Buffer index for distances. To simplify the code, d_buf and l_buf have+ * the same number of elements. To use different lengths, an extra flag+ * array would be necessary.+ */- promise._subscribers.length = 0;- }+ this.opt_len = 0; /* bit length of current block with optimal trees */+ this.static_len = 0; /* bit length of current block with static trees */+ this.matches = 0; /* number of string matches in current block */+ this.insert = 0; /* bytes at end of window left to insert */- function lib$es6$promise$$internal$$ErrorObject() {- this.error = null;- }- var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();+ this.bi_buf = 0;+ /* Output buffer. bits are inserted starting at the bottom (least+ * significant bits).+ */+ this.bi_valid = 0;+ /* Number of valid bits in bi_buf. All bits above the last valid bit+ * are always zero.+ */- function lib$es6$promise$$internal$$tryCatch(callback, detail) {- try {- return callback(detail);- } catch(e) {- lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;- return lib$es6$promise$$internal$$TRY_CATCH_ERROR;- }- }+ // Used for window memory init. We safely ignore it for JS. That makes+ // sense only for pointers and memory check tools.+ //this.high_water = 0;+ /* High water mark offset in window for initialized bytes -- bytes above+ * this are set to zero in order to avoid memory check warnings when+ * longest match routines access bytes past the input. This is then+ * updated to the new high water mark.+ */+ }- function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {- var hasCallback = lib$es6$promise$utils$$isFunction(callback),- value, error, succeeded, failed;- if (hasCallback) {- value = lib$es6$promise$$internal$$tryCatch(callback, detail);+ function deflateResetKeep(strm) {+ var s;- if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {- failed = true;- error = value.error;- value = null;- } else {- succeeded = true;- }+ if (!strm || !strm.state) {+ return err(strm, Z_STREAM_ERROR);+ }- if (promise === value) {- lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());- return;- }+ strm.total_in = strm.total_out = 0;+ strm.data_type = Z_UNKNOWN;- } else {- value = detail;- succeeded = true;- }+ s = strm.state;+ s.pending = 0;+ s.pending_out = 0;- if (promise._state !== lib$es6$promise$$internal$$PENDING) {- // noop- } else if (hasCallback && succeeded) {- lib$es6$promise$$internal$$resolve(promise, value);- } else if (failed) {- lib$es6$promise$$internal$$reject(promise, error);- } else if (settled === lib$es6$promise$$internal$$FULFILLED) {- lib$es6$promise$$internal$$fulfill(promise, value);- } else if (settled === lib$es6$promise$$internal$$REJECTED) {- lib$es6$promise$$internal$$reject(promise, value);- }- }+ if (s.wrap < 0) {+ s.wrap = -s.wrap;+ /* was made negative by deflate(..., Z_FINISH); */+ }+ s.status = (s.wrap ? INIT_STATE : BUSY_STATE);+ strm.adler = (s.wrap === 2) ?+ 0 // crc32(0, Z_NULL, 0)+ :+ 1; // adler32(0, Z_NULL, 0)+ s.last_flush = Z_NO_FLUSH;+ trees._tr_init(s);+ return Z_OK;+ }- function lib$es6$promise$$internal$$initializePromise(promise, resolver) {- try {- resolver(function resolvePromise(value){- lib$es6$promise$$internal$$resolve(promise, value);- }, function rejectPromise(reason) {- lib$es6$promise$$internal$$reject(promise, reason);- });- } catch(e) {- lib$es6$promise$$internal$$reject(promise, e);- }- }- function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {- var enumerator = this;+ function deflateReset(strm) {+ var ret = deflateResetKeep(strm);+ if (ret === Z_OK) {+ lm_init(strm.state);+ }+ return ret;+ }- enumerator._instanceConstructor = Constructor;- enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);- if (enumerator._validateInput(input)) {- enumerator._input = input;- enumerator.length = input.length;- enumerator._remaining = input.length;+ function deflateSetHeader(strm, head) {+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }+ strm.state.gzhead = head;+ return Z_OK;+ }- enumerator._init();- if (enumerator.length === 0) {- lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);- } else {- enumerator.length = enumerator.length || 0;- enumerator._enumerate();- if (enumerator._remaining === 0) {- lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);- }- }- } else {- lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());- }- }+ function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {+ if (!strm) { // === Z_NULL+ return Z_STREAM_ERROR;+ }+ var wrap = 1;- lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {- return lib$es6$promise$utils$$isArray(input);- };+ if (level === Z_DEFAULT_COMPRESSION) {+ level = 6;+ }- lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {- return new Error('Array Methods must be provided an Array');- };+ if (windowBits < 0) { /* suppress zlib wrapper */+ wrap = 0;+ windowBits = -windowBits;+ }- lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {- this._result = new Array(this.length);- };+ else if (windowBits > 15) {+ wrap = 2; /* write gzip wrapper instead */+ windowBits -= 16;+ }- var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;- lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {- var enumerator = this;+ if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||+ windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||+ strategy < 0 || strategy > Z_FIXED) {+ return err(strm, Z_STREAM_ERROR);+ }- var length = enumerator.length;- var promise = enumerator.promise;- var input = enumerator._input;- for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {- enumerator._eachEntry(input[i], i);- }- };+ if (windowBits === 8) {+ windowBits = 9;+ }+ /* until 256-byte window bug fixed */- lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {- var enumerator = this;- var c = enumerator._instanceConstructor;+ var s = new DeflateState();- if (lib$es6$promise$utils$$isMaybeThenable(entry)) {- if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {- entry._onerror = null;- enumerator._settledAt(entry._state, i, entry._result);- } else {- enumerator._willSettleAt(c.resolve(entry), i);- }- } else {- enumerator._remaining--;- enumerator._result[i] = entry;- }- };+ strm.state = s;+ s.strm = strm;- lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {- var enumerator = this;- var promise = enumerator.promise;+ s.wrap = wrap;+ s.gzhead = null;+ s.w_bits = windowBits;+ s.w_size = 1 << s.w_bits;+ s.w_mask = s.w_size - 1;- if (promise._state === lib$es6$promise$$internal$$PENDING) {- enumerator._remaining--;+ s.hash_bits = memLevel + 7;+ s.hash_size = 1 << s.hash_bits;+ s.hash_mask = s.hash_size - 1;+ s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);- if (state === lib$es6$promise$$internal$$REJECTED) {- lib$es6$promise$$internal$$reject(promise, value);- } else {- enumerator._result[i] = value;- }- }+ s.window = new utils.Buf8(s.w_size * 2);+ s.head = new utils.Buf16(s.hash_size);+ s.prev = new utils.Buf16(s.w_size);- if (enumerator._remaining === 0) {- lib$es6$promise$$internal$$fulfill(promise, enumerator._result);- }- };+ // Don't need mem init magic for JS.+ //s.high_water = 0; /* nothing written to s->window yet */- lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {- var enumerator = this;+ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */- lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {- enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);- }, function(reason) {- enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);- });- };- function lib$es6$promise$promise$all$$all(entries) {- return new lib$es6$promise$enumerator$$default(this, entries).promise;- }- var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;- function lib$es6$promise$promise$race$$race(entries) {- /*jshint validthis:true */- var Constructor = this;+ s.pending_buf_size = s.lit_bufsize * 4;+ s.pending_buf = new utils.Buf8(s.pending_buf_size);- var promise = new Constructor(lib$es6$promise$$internal$$noop);+ s.d_buf = s.lit_bufsize >> 1;+ s.l_buf = (1 + 2) * s.lit_bufsize;- if (!lib$es6$promise$utils$$isArray(entries)) {- lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));- return promise;- }+ s.level = level;+ s.strategy = strategy;+ s.method = method;- var length = entries.length;+ return deflateReset(strm);+ }- function onFulfillment(value) {- lib$es6$promise$$internal$$resolve(promise, value);- }+ function deflateInit(strm, level) {+ return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);+ }- function onRejection(reason) {- lib$es6$promise$$internal$$reject(promise, reason);- }- for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {- lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);- }+ function deflate(strm, flush) {+ var old_flush, s;+ var beg, val; // for gzip header write only- return promise;- }- var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;- function lib$es6$promise$promise$resolve$$resolve(object) {- /*jshint validthis:true */- var Constructor = this;+ if (!strm || !strm.state ||+ flush > Z_BLOCK || flush < 0) {+ return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;+ }- if (object && typeof object === 'object' && object.constructor === Constructor) {- return object;- }+ s = strm.state;- var promise = new Constructor(lib$es6$promise$$internal$$noop);- lib$es6$promise$$internal$$resolve(promise, object);- return promise;- }- var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;- function lib$es6$promise$promise$reject$$reject(reason) {- /*jshint validthis:true */- var Constructor = this;- var promise = new Constructor(lib$es6$promise$$internal$$noop);- lib$es6$promise$$internal$$reject(promise, reason);- return promise;- }- var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;+ if (!strm.output ||+ (!strm.input && strm.avail_in !== 0) ||+ (s.status === FINISH_STATE && flush !== Z_FINISH)) {+ return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);+ }- var lib$es6$promise$promise$$counter = 0;+ s.strm = strm; /* just in case */+ old_flush = s.last_flush;+ s.last_flush = flush;- function lib$es6$promise$promise$$needsResolver() {- throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');- }+ /* Write the header */+ if (s.status === INIT_STATE) {- function lib$es6$promise$promise$$needsNew() {- throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");+ if (s.wrap === 2) { // GZIP header+ strm.adler = 0; //crc32(0L, Z_NULL, 0);+ put_byte(s, 31);+ put_byte(s, 139);+ put_byte(s, 8);+ if (!s.gzhead) { // s->gzhead == Z_NULL+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, s.level === 9 ? 2 :+ (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?+ 4 : 0));+ put_byte(s, OS_CODE);+ s.status = BUSY_STATE;+ }+ else {+ put_byte(s, (s.gzhead.text ? 1 : 0) ++ (s.gzhead.hcrc ? 2 : 0) ++ (!s.gzhead.extra ? 0 : 4) ++ (!s.gzhead.name ? 0 : 8) ++ (!s.gzhead.comment ? 0 : 16)+ );+ put_byte(s, s.gzhead.time & 0xff);+ put_byte(s, (s.gzhead.time >> 8) & 0xff);+ put_byte(s, (s.gzhead.time >> 16) & 0xff);+ put_byte(s, (s.gzhead.time >> 24) & 0xff);+ put_byte(s, s.level === 9 ? 2 :+ (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?+ 4 : 0));+ put_byte(s, s.gzhead.os & 0xff);+ if (s.gzhead.extra && s.gzhead.extra.length) {+ put_byte(s, s.gzhead.extra.length & 0xff);+ put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);+ }+ if (s.gzhead.hcrc) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);+ }+ s.gzindex = 0;+ s.status = EXTRA_STATE;+ }}+ else // DEFLATE header+ {+ var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;+ var level_flags = -1;- var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;- /**- Promise objects represent the eventual result of an asynchronous operation. The- primary way of interacting with a promise is through its `then` method, which- registers callbacks to receive either a promise's eventual value or the reason- why the promise cannot be fulfilled.-- Terminology- ------------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification.- - `thenable` is an object or function that defines a `then` method.- - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).- - `exception` is a value that is thrown using the throw statement.- - `reason` is a value that indicates why a promise was rejected.- - `settled` the final resting state of a promise, fulfilled or rejected.-- A promise can be in one of three states: pending, fulfilled, or rejected.-- Promises that are fulfilled have a fulfillment value and are in the fulfilled- state. Promises that are rejected have a rejection reason and are in the- rejected state. A fulfillment value is never a thenable.-- Promises can also be said to *resolve* a value. If this value is also a- promise, then the original promise's settled state will match the value's- settled state. So a promise that *resolves* a promise that rejects will- itself reject, and a promise that *resolves* a promise that fulfills will- itself fulfill.--- Basic Usage:- -------------- ```js- var promise = new Promise(function(resolve, reject) {- // on success- resolve(value);-- // on failure- reject(reason);- });-- promise.then(function(value) {- // on fulfillment- }, function(reason) {- // on rejection- });- ```-- Advanced Usage:- ----------------- Promises shine when abstracting away asynchronous interactions such as- `XMLHttpRequest`s.-- ```js- function getJSON(url) {- return new Promise(function(resolve, reject){- var xhr = new XMLHttpRequest();-- xhr.open('GET', url);- xhr.onreadystatechange = handler;- xhr.responseType = 'json';- xhr.setRequestHeader('Accept', 'application/json');- xhr.send();-- function handler() {- if (this.readyState === this.DONE) {- if (this.status === 200) {- resolve(this.response);- } else {- reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));- }- }- };- });+ if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {+ level_flags = 0;+ } else if (s.level < 6) {+ level_flags = 1;+ } else if (s.level === 6) {+ level_flags = 2;+ } else {+ level_flags = 3;}+ header |= (level_flags << 6);+ if (s.strstart !== 0) { header |= PRESET_DICT; }+ header += 31 - (header % 31);- getJSON('/posts.json').then(function(json) {- // on fulfillment- }, function(reason) {- // on rejection- });- ```-- Unlike callbacks, promises are great composable primitives.-- ```js- Promise.all([- getJSON('/posts'),- getJSON('/comments')- ]).then(function(values){- values[0] // => postsJSON- values[1] // => commentsJSON-- return values;- });- ```+ s.status = BUSY_STATE;+ putShortMSB(s, header);- @class Promise- @param {function} resolver- Useful for tooling.- @constructor- */- function lib$es6$promise$promise$$Promise(resolver) {- this._id = lib$es6$promise$promise$$counter++;- this._state = undefined;- this._result = undefined;- this._subscribers = [];+ /* Save the adler32 of the preset dictionary: */+ if (s.strstart !== 0) {+ putShortMSB(s, strm.adler >>> 16);+ putShortMSB(s, strm.adler & 0xffff);+ }+ strm.adler = 1; // adler32(0L, Z_NULL, 0);+ }+ }- if (lib$es6$promise$$internal$$noop !== resolver) {- if (!lib$es6$promise$utils$$isFunction(resolver)) {- lib$es6$promise$promise$$needsResolver();- }+ //#ifdef GZIP+ if (s.status === EXTRA_STATE) {+ if (s.gzhead.extra/* != Z_NULL*/) {+ beg = s.pending; /* start of bytes to update crc */- if (!(this instanceof lib$es6$promise$promise$$Promise)) {- lib$es6$promise$promise$$needsNew();+ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {+ if (s.pending === s.pending_buf_size) {+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ flush_pending(strm);+ beg = s.pending;+ if (s.pending === s.pending_buf_size) {+ break;+ }}-- lib$es6$promise$$internal$$initializePromise(this, resolver);+ put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);+ s.gzindex++;+ }+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ if (s.gzindex === s.gzhead.extra.length) {+ s.gzindex = 0;+ s.status = NAME_STATE;}}+ else {+ s.status = NAME_STATE;+ }+ }+ if (s.status === NAME_STATE) {+ if (s.gzhead.name/* != Z_NULL*/) {+ beg = s.pending; /* start of bytes to update crc */+ //int val;- lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;- lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;- lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;- lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;- lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;- lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;- lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;-- lib$es6$promise$promise$$Promise.prototype = {- constructor: lib$es6$promise$promise$$Promise,-- /**- The primary way of interacting with a promise is through its `then` method,- which registers callbacks to receive either a promise's eventual value or the- reason why the promise cannot be fulfilled.-- ```js- findUser().then(function(user){- // user is available- }, function(reason){- // user is unavailable, and you are given the reason why- });- ```-- Chaining- ---------- The return value of `then` is itself a promise. This second, 'downstream'- promise is resolved with the return value of the first promise's fulfillment- or rejection handler, or rejected if the handler throws an exception.-- ```js- findUser().then(function (user) {- return user.name;- }, function (reason) {- return 'default name';- }).then(function (userName) {- // If `findUser` fulfilled, `userName` will be the user's name, otherwise it- // will be `'default name'`- });-- findUser().then(function (user) {- throw new Error('Found user, but still unhappy');- }, function (reason) {- throw new Error('`findUser` rejected and we're unhappy');- }).then(function (value) {- // never reached- }, function (reason) {- // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.- // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.- });- ```- If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.+ do {+ if (s.pending === s.pending_buf_size) {+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ flush_pending(strm);+ beg = s.pending;+ if (s.pending === s.pending_buf_size) {+ val = 1;+ break;+ }+ }+ // JS specific: little magic to add zero terminator to end of string+ if (s.gzindex < s.gzhead.name.length) {+ val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;+ } else {+ val = 0;+ }+ put_byte(s, val);+ } while (val !== 0);- ```js- findUser().then(function (user) {- throw new PedagogicalException('Upstream error');- }).then(function (value) {- // never reached- }).then(function (value) {- // never reached- }, function (reason) {- // The `PedgagocialException` is propagated all the way down to here- });- ```+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ if (val === 0) {+ s.gzindex = 0;+ s.status = COMMENT_STATE;+ }+ }+ else {+ s.status = COMMENT_STATE;+ }+ }+ if (s.status === COMMENT_STATE) {+ if (s.gzhead.comment/* != Z_NULL*/) {+ beg = s.pending; /* start of bytes to update crc */+ //int val;- Assimilation- ------------+ do {+ if (s.pending === s.pending_buf_size) {+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ flush_pending(strm);+ beg = s.pending;+ if (s.pending === s.pending_buf_size) {+ val = 1;+ break;+ }+ }+ // JS specific: little magic to add zero terminator to end of string+ if (s.gzindex < s.gzhead.comment.length) {+ val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;+ } else {+ val = 0;+ }+ put_byte(s, val);+ } while (val !== 0);- Sometimes the value you want to propagate to a downstream promise can only be- retrieved asynchronously. This can be achieved by returning a promise in the- fulfillment or rejection handler. The downstream promise will then be pending- until the returned promise is settled. This is called *assimilation*.+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ if (val === 0) {+ s.status = HCRC_STATE;+ }+ }+ else {+ s.status = HCRC_STATE;+ }+ }+ if (s.status === HCRC_STATE) {+ if (s.gzhead.hcrc) {+ if (s.pending + 2 > s.pending_buf_size) {+ flush_pending(strm);+ }+ if (s.pending + 2 <= s.pending_buf_size) {+ put_byte(s, strm.adler & 0xff);+ put_byte(s, (strm.adler >> 8) & 0xff);+ strm.adler = 0; //crc32(0L, Z_NULL, 0);+ s.status = BUSY_STATE;+ }+ }+ else {+ s.status = BUSY_STATE;+ }+ }+ //#endif- ```js- findUser().then(function (user) {- return findCommentsByAuthor(user);- }).then(function (comments) {- // The user's comments are now available- });- ```+ /* Flush as much pending output as possible */+ if (s.pending !== 0) {+ flush_pending(strm);+ if (strm.avail_out === 0) {+ /* Since avail_out is 0, deflate will be called again with+ * more output space, but possibly with both pending and+ * avail_in equal to zero. There won't be anything to do,+ * but this is not an error situation so make sure we+ * return OK instead of BUF_ERROR at next call of deflate:+ */+ s.last_flush = -1;+ return Z_OK;+ }- If the assimliated promise rejects, then the downstream promise will also reject.+ /* Make sure there is something to do and avoid duplicate consecutive+ * flushes. For repeated and useless calls with Z_FINISH, we keep+ * returning Z_STREAM_END instead of Z_BUF_ERROR.+ */+ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&+ flush !== Z_FINISH) {+ return err(strm, Z_BUF_ERROR);+ }- ```js- findUser().then(function (user) {- return findCommentsByAuthor(user);- }).then(function (comments) {- // If `findCommentsByAuthor` fulfills, we'll have the value here- }, function (reason) {- // If `findCommentsByAuthor` rejects, we'll have the reason here- });- ```+ /* User must not provide more input after the first FINISH: */+ if (s.status === FINISH_STATE && strm.avail_in !== 0) {+ return err(strm, Z_BUF_ERROR);+ }- Simple Example- --------------+ /* Start a new block or continue the current one.+ */+ if (strm.avail_in !== 0 || s.lookahead !== 0 ||+ (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {+ var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :+ (s.strategy === Z_RLE ? deflate_rle(s, flush) :+ configuration_table[s.level].func(s, flush));- Synchronous Example+ if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {+ s.status = FINISH_STATE;+ }+ if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {+ if (strm.avail_out === 0) {+ s.last_flush = -1;+ /* avoid BUF_ERROR next call, see above */+ }+ return Z_OK;+ /* If flush != Z_NO_FLUSH && avail_out == 0, the next call+ * of deflate should use the same flush parameter to make sure+ * that the flush is complete. So we don't have to output an+ * empty block here, this will be done at next call. This also+ * ensures that for a very small output buffer, we emit at most+ * one empty block.+ */+ }+ if (bstate === BS_BLOCK_DONE) {+ if (flush === Z_PARTIAL_FLUSH) {+ trees._tr_align(s);+ }+ else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */- ```javascript- var result;+ trees._tr_stored_block(s, 0, 0, false);+ /* For a full flush, this empty block will be recognized+ * as a special marker by inflate_sync().+ */+ if (flush === Z_FULL_FLUSH) {+ /*** CLEAR_HASH(s); ***/ /* forget history */+ zero(s.head); // Fill with NIL (= 0);- try {- result = findResult();- // success- } catch(reason) {- // failure+ if (s.lookahead === 0) {+ s.strstart = 0;+ s.block_start = 0;+ s.insert = 0;+ }+ }}- ```+ flush_pending(strm);+ if (strm.avail_out === 0) {+ s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */+ return Z_OK;+ }+ }+ }+ //Assert(strm->avail_out > 0, "bug2");+ //if (strm.avail_out <= 0) { throw new Error("bug2");}- Errback Example+ if (flush !== Z_FINISH) { return Z_OK; }+ if (s.wrap <= 0) { return Z_STREAM_END; }- ```js- findResult(function(result, err){- if (err) {- // failure- } else {- // success- }- });- ```-- Promise Example;+ /* Write the trailer */+ if (s.wrap === 2) {+ put_byte(s, strm.adler & 0xff);+ put_byte(s, (strm.adler >> 8) & 0xff);+ put_byte(s, (strm.adler >> 16) & 0xff);+ put_byte(s, (strm.adler >> 24) & 0xff);+ put_byte(s, strm.total_in & 0xff);+ put_byte(s, (strm.total_in >> 8) & 0xff);+ put_byte(s, (strm.total_in >> 16) & 0xff);+ put_byte(s, (strm.total_in >> 24) & 0xff);+ }+ else+ {+ putShortMSB(s, strm.adler >>> 16);+ putShortMSB(s, strm.adler & 0xffff);+ }- ```javascript- findResult().then(function(result){- // success- }, function(reason){- // failure- });- ```+ flush_pending(strm);+ /* If avail_out is zero, the application will call deflate again+ * to flush the rest.+ */+ if (s.wrap > 0) { s.wrap = -s.wrap; }+ /* write the trailer only once! */+ return s.pending !== 0 ? Z_OK : Z_STREAM_END;+ }- Advanced Example- --------------+ function deflateEnd(strm) {+ var status;- Synchronous Example+ if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {+ return Z_STREAM_ERROR;+ }- ```javascript- var author, books;+ status = strm.state.status;+ if (status !== INIT_STATE &&+ status !== EXTRA_STATE &&+ status !== NAME_STATE &&+ status !== COMMENT_STATE &&+ status !== HCRC_STATE &&+ status !== BUSY_STATE &&+ status !== FINISH_STATE+ ) {+ return err(strm, Z_STREAM_ERROR);+ }- try {- author = findAuthor();- books = findBooksByAuthor(author);- // success- } catch(reason) {- // failure- }- ```+ strm.state = null;- Errback Example+ return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;+ }- ```js+ /* =========================================================================+ * Copy the source state to the destination state+ */+ //function deflateCopy(dest, source) {+ //+ //}- function foundBooks(books) {+ exports.deflateInit = deflateInit;+ exports.deflateInit2 = deflateInit2;+ exports.deflateReset = deflateReset;+ exports.deflateResetKeep = deflateResetKeep;+ exports.deflateSetHeader = deflateSetHeader;+ exports.deflate = deflate;+ exports.deflateEnd = deflateEnd;+ exports.deflateInfo = 'pako deflate (from Nodeca project)';- }+ /* Not implemented+ exports.deflateBound = deflateBound;+ exports.deflateCopy = deflateCopy;+ exports.deflateSetDictionary = deflateSetDictionary;+ exports.deflateParams = deflateParams;+ exports.deflatePending = deflatePending;+ exports.deflatePrime = deflatePrime;+ exports.deflateTune = deflateTune;+ */- function failure(reason) {-},{"../utils/common":54,"./adler32":56,"./crc32":58,"./messages":64,"./trees":65}],60:[function(require,module,exports){++},{"../utils/common":55,"./adler32":57,"./crc32":59,"./messages":65,"./trees":66}],61:[function(require,module,exports){+ 'use strict';- }- findAuthor(function(author, err){- if (err) {- failure(err);- // failure- } else {- try {- findBoooksByAuthor(author, function(books, err) {- if (err) {- failure(err);- } else {- try {- foundBooks(books);- } catch(reason) {- failure(reason);- }- }- });- } catch(error) {- failure(err);- }- // success- }- });- ```+ function GZheader() {+ /* true if compressed data believed to be text */+ this.text = 0;+ /* modification time */+ this.time = 0;+ /* extra flags (not used when writing a gzip file) */+ this.xflags = 0;+ /* operating system */+ this.os = 0;+ /* pointer to extra field or Z_NULL if none */+ this.extra = null;+ /* extra field length (valid if extra != Z_NULL) */+ this.extra_len = 0; // Actually, we don't need it in JS,+ // but leave for few code modifications- Promise Example;+ //+ // Setup limits is not necessary because in js we should not preallocate memory+ // for inflate use constant limit in 65536 bytes+ //- ```javascript- findAuthor().- then(findBooksByAuthor).- then(function(books){- // found books- }).catch(function(reason){- // something went wrong- });- ```+ /* space at extra (only when reading header) */+ // this.extra_max = 0;+ /* pointer to zero-terminated file name or Z_NULL */+ this.name = '';+ /* space at name (only when reading header) */+ // this.name_max = 0;+ /* pointer to zero-terminated comment or Z_NULL */+ this.comment = '';+ /* space at comment (only when reading header) */+ // this.comm_max = 0;+ /* true if there was or will be a header crc */+ this.hcrc = 0;+ /* true when done reading gzip header (not used when writing a gzip file) */+ this.done = false;+ }- @method then- @param {Function} onFulfilled- @param {Function} onRejected- Useful for tooling.- @return {Promise}- */- then: function(onFulfillment, onRejection) {- var parent = this;- var state = parent._state;+ module.exports = GZheader;- if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {- return this;- }-},{}],61:[function(require,module,exports){++},{}],62:[function(require,module,exports){+ 'use strict';- var child = new this.constructor(lib$es6$promise$$internal$$noop);- var result = parent._result;+ // See state defs from inflate.js+ var BAD = 30; /* got a data error -- remain here until reset */+ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */- if (state) {- var callback = arguments[state - 1];- lib$es6$promise$asap$$asap(function(){- lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);- });- } else {- lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);- }+ /*+ Decode literal, length, and distance codes and write out the resulting+ literal and match bytes until either not enough input or output is+ available, an end-of-block is encountered, or a data error is encountered.+ When large enough input and output buffers are supplied to inflate(), for+ example, a 16K input buffer and a 64K output buffer, more than 95% of the+ inflate execution time is spent in this routine.- return child;- },+ Entry assumptions:- /**- `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same- as the catch block of a try/catch statement.+ state.mode === LEN+ strm.avail_in >= 6+ strm.avail_out >= 258+ start >= strm.avail_out+ state.bits < 8- ```js- function findAuthor(){- throw new Error('couldn't find that author');- }+ On return, state.mode is one of:- // synchronous- try {- findAuthor();- } catch(reason) {- // something went wrong- }+ LEN -- ran out of enough output space or enough available input+ TYPE -- reached end of block code, inflate() to interpret next block+ BAD -- error in block data- // async with promises- findAuthor().catch(function(reason){- // something went wrong- });- ```+ Notes:- @method catch- @param {Function} onRejection- Useful for tooling.- @return {Promise}- */- 'catch': function(onRejection) {- return this.then(null, onRejection);- }- };- function lib$es6$promise$polyfill$$polyfill() {- var local;+ - The maximum input bits used by a length/distance pair is 15 bits for the+ length code, 5 bits for the length extra, 15 bits for the distance code,+ and 13 bits for the distance extra. This totals 48 bits, or six bytes.+ Therefore if strm.avail_in >= 6, then there is enough input to avoid+ checking for available input while decoding.- if (typeof global !== 'undefined') {- local = global;- } else if (typeof self !== 'undefined') {- local = self;- } else {- try {- local = Function('return this')();- } catch (e) {- throw new Error('polyfill failed because global object is unavailable in this environment');- }- }-- var P = local.Promise;-- if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {- return;- }-- local.Promise = lib$es6$promise$promise$$default;- }- var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;-- var lib$es6$promise$umd$$ES6Promise = {- 'Promise': lib$es6$promise$promise$$default,- 'polyfill': lib$es6$promise$polyfill$$default- };-- /* global define:true module:true window: true */- if (typeof define === 'function' && define['amd']) {- define(function() { return lib$es6$promise$umd$$ES6Promise; });- } else if (typeof module !== 'undefined' && module['exports']) {- module['exports'] = lib$es6$promise$umd$$ES6Promise;- } else if (typeof this !== 'undefined') {- this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;- }-- lib$es6$promise$polyfill$$default();- }).call(this);--- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"_process":103}],73:[function(require,module,exports){-- /**- * Returns `this`. Execute this without a "context" (i.e. without it being- * attached to an object of the left-hand side), and `this` points to the- * "global" scope of the current JS execution.- */-- module.exports = (function () { return this; })();-- },{}],74:[function(require,module,exports){- (function (global){-- /*- * Module requirements.+ - The maximum bytes that a single length/distance pair can output is 258+ bytes, which is the maximum length that can be coded. inflate_fast()+ requires strm.avail_out >= 258 for each loop to avoid checking for+ output space.*/+ module.exports = function inflate_fast(strm, start) {+ var state;+ var _in; /* local strm.input */+ var last; /* have enough input while in < last */+ var _out; /* local strm.output */+ var beg; /* inflate()'s initial strm.output */+ var end; /* while out < end, enough space available */+ //#ifdef INFLATE_STRICT+ var dmax; /* maximum distance from zlib header */+ //#endif+ var wsize; /* window size or zero if not using window */+ var whave; /* valid bytes in the window */+ var wnext; /* window write index */+ // Use `s_window` instead `window`, avoid conflict with instrumentation tools+ var s_window; /* allocated sliding window, if wsize != 0 */+ var hold; /* local strm.hold */+ var bits; /* local strm.bits */+ var lcode; /* local strm.lencode */+ var dcode; /* local strm.distcode */+ var lmask; /* mask for first level of length codes */+ var dmask; /* mask for first level of distance codes */+ var here; /* retrieved table entry */+ var op; /* code bits, operation, extra bits, or */+ /* window position, window bytes to copy */+ var len; /* match length, unused bytes */+ var dist; /* match distance */+ var from; /* where to copy match from */+ var from_source;- var isArray = require('isarray');-- /**- * Module exports.- */- module.exports = hasBinary;+ var input, output; // JS specific, because we have no pointers- /**- * Checks for binary data.- *- * Right now only Buffer and ArrayBuffer are supported..- *- * @param {Object} anything- * @api public- */+ /* copy state to local variables */+ state = strm.state;+ //here = state.here;+ _in = strm.next_in;+ input = strm.input;+ last = _in + (strm.avail_in - 5);+ _out = strm.next_out;+ output = strm.output;+ beg = _out - (start - strm.avail_out);+ end = _out + (strm.avail_out - 257);+ //#ifdef INFLATE_STRICT+ dmax = state.dmax;+ //#endif+ wsize = state.wsize;+ whave = state.whave;+ wnext = state.wnext;+ s_window = state.window;+ hold = state.hold;+ bits = state.bits;+ lcode = state.lencode;+ dcode = state.distcode;+ lmask = (1 << state.lenbits) - 1;+ dmask = (1 << state.distbits) - 1;- function hasBinary(data) {- function _hasBinary(obj) {- if (!obj) return false;+ /* decode literals and length/distances until end-of-block or not enough+ input data or output space */- if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||- (global.ArrayBuffer && obj instanceof ArrayBuffer) ||- (global.Blob && obj instanceof Blob) ||- (global.File && obj instanceof File)- ) {- return true;+ top:+ do {+ if (bits < 15) {+ hold += input[_in++] << bits;+ bits += 8;+ hold += input[_in++] << bits;+ bits += 8;}- if (isArray(obj)) {- for (var i = 0; i < obj.length; i++) {- if (_hasBinary(obj[i])) {- return true;- }- }- } else if (obj && 'object' == typeof obj) {- if (obj.toJSON) {- obj = obj.toJSON();- }+ here = lcode[hold & lmask];- for (var key in obj) {- if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {- return true;- }+ dolen:+ for (;;) { // Goto emulation+ op = here >>> 24/*here.bits*/;+ hold >>>= op;+ bits -= op;+ op = (here >>> 16) & 0xff/*here.op*/;+ if (op === 0) { /* literal */+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?+ // "inflate: literal '%c'\n" :+ // "inflate: literal 0x%02x\n", here.val));+ output[_out++] = here & 0xffff/*here.val*/;}- }-- return false;- }-- return _hasBinary(data);- }-- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"isarray":77}],75:[function(require,module,exports){-- /**- * Module dependencies.- */-- var global = require('global');-- /**- * Module exports.- *- * Logic borrowed from Modernizr:- *- * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js- */-- try {- module.exports = 'XMLHttpRequest' in global &&- 'withCredentials' in new global.XMLHttpRequest();- } catch (err) {- // if XMLHttp support is disabled in IE then it will throw- // when trying to create- module.exports = false;- }+ else if (op & 16) { /* length base */+ len = here & 0xffff/*here.val*/;+ op &= 15; /* number of extra bits */+ if (op) {+ if (bits < op) {+ hold += input[_in++] << bits;+ bits += 8;+ }+ len += hold & ((1 << op) - 1);+ hold >>>= op;+ bits -= op;+ }+ //Tracevv((stderr, "inflate: length %u\n", len));+ if (bits < 15) {+ hold += input[_in++] << bits;+ bits += 8;+ hold += input[_in++] << bits;+ bits += 8;+ }+ here = dcode[hold & dmask];- },{"global":73}],76:[function(require,module,exports){+ dodist:+ for (;;) { // goto emulation+ op = here >>> 24/*here.bits*/;+ hold >>>= op;+ bits -= op;+ op = (here >>> 16) & 0xff/*here.op*/;- var indexOf = [].indexOf;+ if (op & 16) { /* distance base */+ dist = here & 0xffff/*here.val*/;+ op &= 15; /* number of extra bits */+ if (bits < op) {+ hold += input[_in++] << bits;+ bits += 8;+ if (bits < op) {+ hold += input[_in++] << bits;+ bits += 8;+ }+ }+ dist += hold & ((1 << op) - 1);+ //#ifdef INFLATE_STRICT+ if (dist > dmax) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break top;+ }+ //#endif+ hold >>>= op;+ bits -= op;+ //Tracevv((stderr, "inflate: distance %u\n", dist));+ op = _out - beg; /* max distance in output */+ if (dist > op) { /* see if copy from window */+ op = dist - op; /* distance back in window */+ if (op > whave) {+ if (state.sane) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break top;+ }- module.exports = function(arr, obj){- if (indexOf) return arr.indexOf(obj);- for (var i = 0; i < arr.length; ++i) {- if (arr[i] === obj) return i;- }- return -1;- };- },{}],77:[function(require,module,exports){- module.exports = Array.isArray || function (arr) {- return Object.prototype.toString.call(arr) == '[object Array]';- };-- },{}],78:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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.- */-- /**- * Ordered log levels.- */- var levels = {- "trace": 0,- "debug": 1,- "info": 2,- "log": 3,- "warn": 4,- "error": 5- };+ // (!) This block is disabled in zlib defailts,+ // don't enable it for binary compatibility+ //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR+ // if (len <= op - whave) {+ // do {+ // output[_out++] = 0;+ // } while (--len);+ // continue top;+ // }+ // len -= op - whave;+ // do {+ // output[_out++] = 0;+ // } while (--op > whave);+ // if (op === 0) {+ // from = _out - dist;+ // do {+ // output[_out++] = output[from++];+ // } while (--len);+ // continue top;+ // }+ //#endif+ }+ from = 0; // window index+ from_source = s_window;+ if (wnext === 0) { /* very common case */+ from += wsize - op;+ if (op < len) { /* some from window */+ len -= op;+ do {+ output[_out++] = s_window[from++];+ } while (--op);+ from = _out - dist; /* rest from output */+ from_source = output;+ }+ }+ else if (wnext < op) { /* wrap around window */+ from += wsize + wnext - op;+ op -= wnext;+ if (op < len) { /* some from end of window */+ len -= op;+ do {+ output[_out++] = s_window[from++];+ } while (--op);+ from = 0;+ if (wnext < len) { /* some from start of window */+ op = wnext;+ len -= op;+ do {+ output[_out++] = s_window[from++];+ } while (--op);+ from = _out - dist; /* rest from output */+ from_source = output;+ }+ }+ }+ else { /* contiguous in window */+ from += wnext - op;+ if (op < len) { /* some from window */+ len -= op;+ do {+ output[_out++] = s_window[from++];+ } while (--op);+ from = _out - dist; /* rest from output */+ from_source = output;+ }+ }+ while (len > 2) {+ output[_out++] = from_source[from++];+ output[_out++] = from_source[from++];+ output[_out++] = from_source[from++];+ len -= 3;+ }+ if (len) {+ output[_out++] = from_source[from++];+ if (len > 1) {+ output[_out++] = from_source[from++];+ }+ }+ }+ else {+ from = _out - dist; /* copy direct from output */+ do { /* minimum length is three */+ output[_out++] = output[from++];+ output[_out++] = output[from++];+ output[_out++] = output[from++];+ len -= 3;+ } while (len > 2);+ if (len) {+ output[_out++] = output[from++];+ if (len > 1) {+ output[_out++] = output[from++];+ }+ }+ }+ }+ else if ((op & 64) === 0) { /* 2nd level distance code */+ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];+ continue dodist;+ }+ else {+ strm.msg = 'invalid distance code';+ state.mode = BAD;+ break top;+ }- /**- * Parses Error's object stack trace and extracts information about the last- * caller before the log method was called.- * @returns JS object with info about the caller - method name, file location,- * line and column.- */- function getCallerInfo() {- var callerInfo = {- methodName: "",- fileLocation: "",- line: null,- column: null- };- //gets the part of the stack without the logger wrappers- var error = new Error();- var stack = error.stack? error.stack.split("\n") : [];- if(!stack || stack.length < 1) {- return callerInfo;- }- var m = null;- if(stack[3]) {- m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);- }- if(!m || m.length <= 4) {- //Firefox && Safari- if(stack[2].indexOf("log@") === 0){- //Safari- callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));- } else {- //Firefox- callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));+ break; // need to emulate goto via "continue"}- return callerInfo;+ }+ else if ((op & 64) === 0) { /* 2nd level length code */+ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];+ continue dolen;+ }+ else if (op & 32) { /* end-of-block */+ //Tracevv((stderr, "inflate: end of block\n"));+ state.mode = TYPE;+ break top;+ }+ else {+ strm.msg = 'invalid literal/length code';+ state.mode = BAD;+ break top;+ }++ break; // need to emulate goto via "continue"}+ } while (_in < last && _out < end);- callerInfo.methodName = m[1];- callerInfo.fileLocation = m[2];- callerInfo.line = m[3];- callerInfo.column = m[4];- return callerInfo;- }+ /* return unused bytes (on entry, bits < 8, so in won't go too far back) */+ len = bits >> 3;+ _in -= len;+ bits -= len << 3;+ hold &= (1 << bits) - 1;- /**- * Logs messages using the transports and level from the logger.- * @param logger a logger instance.- * @param level the log level of the message. See the levels variable.- * @param arguments array with arguments that will be logged.- */- function log() {- var logger = arguments[0], level = arguments[1],- args = Array.prototype.slice.call(arguments, 2);- if(levels[level] <= logger.level) {- return;- }+ /* update state and return */+ strm.next_in = _in;+ strm.next_out = _out;+ strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));+ strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));+ state.hold = hold;+ state.bits = bits;+ return;+ };- var callerInfo = getCallerInfo();- for(var i = 0; i < logger.transports.length; i++) {- var t = logger.transports[i];- var l = t[level];- if(l && typeof(l) === "function") {- l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")- .apply(t, args);- }- }- }-},{}],62:[function(require,module,exports){++},{}],63:[function(require,module,exports){+ 'use strict';- /**- *- * Constructs new logger object.- * @param level the logging level for the new logger- * @param id optional identifier for the logger instance.- * @param transports optional list of handlers(objects) for the logs.- * The handlers must support - log, warn, error, debug, info, trace.- * @param format optional (NOT implemented) string.- */- function Logger(level, id, transports, format) {- this.id = id;- this.format = format;- if(!this.transports) {- this.transports = [];- this.transports.push(Logger.consoleTransport);- }- this.level = levels[level];- var methods = Object.keys(levels);- for(var i = 0; i < methods.length; i++){- this[methods[i]] =- log.bind(null, this, methods[i]);- }- }- /**- * Sets the log level for the logger.- * @param level the new log level.- */- Logger.prototype.setLevel = function (level) {- this.level = levels[level];- };- module.exports = Logger;+ var utils = require('../utils/common');+ var adler32 = require('./adler32');+ var crc32 = require('./crc32');+ var inflate_fast = require('./inffast');+ var inflate_table = require('./inftrees');- /**- * The default transport - console- */- Logger.consoleTransport = console;+ var CODES = 0;+ var LENS = 1;+ var DISTS = 2;- /**- * Enum for the supported log levels.- */- Logger.levels = {- TRACE: "trace",- DEBUG: "debug",- INFO: "info",- LOG: "log",- WARN: "warn",- ERROR: "error"- };+ /* Public constants ==========================================================*/+ /* ===========================================================================*/- },{}],79:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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.- */- var Logger = require("./Logger");- /**- * Map with the created loggers with ID.- */- var idLoggers = {};+ /* Allowed flush values; see deflate() and inflate() below for details */+ //var Z_NO_FLUSH = 0;+ //var Z_PARTIAL_FLUSH = 1;+ //var Z_SYNC_FLUSH = 2;+ //var Z_FULL_FLUSH = 3;+ var Z_FINISH = 4;+ var Z_BLOCK = 5;+ var Z_TREES = 6;- /**- * Array with the loggers without id.- */- var loggers = [];- /**- * Log level for the lbrary.+ /* Return codes for the compression/decompression functions. Negative values+ * are errors, positive values are used for special but normal events.*/- var curLevel = Logger.levels.TRACE;+ var Z_OK = 0;+ var Z_STREAM_END = 1;+ var Z_NEED_DICT = 2;+ //var Z_ERRNO = -1;+ var Z_STREAM_ERROR = -2;+ var Z_DATA_ERROR = -3;+ var Z_MEM_ERROR = -4;+ var Z_BUF_ERROR = -5;+ //var Z_VERSION_ERROR = -6;+ /* The deflate compression method */+ var Z_DEFLATED = 8;- module.exports = {- /**- * Creates new logger.- * @arguments the same as Logger constructor- */- getLogger: function(id, transports, format) {- var logger = new Logger(curLevel, id, transports, format);- if(id) {- idLoggers[id] = idLoggers[id] || [];- idLoggers[id].push(logger);- } else {- loggers.push(logger);- }- return logger;- },- /**- * Changes the log level for the existing loggers by id.- * @param level the new log level.- * @param id if specified the level will be changed only for loggers with the- * same id. Otherwise the operation will affect all loggers that don't- * have id.- */- setLogLevelById: function(level, id) {- var l = id? (idLoggers[id] || []) : loggers;- for(var i = 0; i < l.length; i++) {- l[i].setLevel(level);- }- },- /**- * Changes the log level for all existing loggers.- * @param level the new log level.- */- setLogLevel: function (level) {- curLevel = level;- var i = 0;- for(; i < loggers.length; i++) {- loggers[i].setLevel(level);- }- for(var id in idLoggers) {- var l = idLoggers[id] || [];- for(i = 0; i < l.length; i++) {- l[i].setLevel(level);- }- }- },- /**- * The supported log levels.- */- levels: Logger.levels- };+ /* STATES ====================================================================*/+ /* ===========================================================================*/- },{"./Logger":78}],80:[function(require,module,exports){- /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */- ;(function (window) {- // Convenience aliases.- var getClass = {}.toString, isProperty, forEach, undef;- // Detect the `define` function exposed by asynchronous module loaders. The- // strict `define` check is necessary for compatibility with `r.js`.- var isLoader = typeof define === "function" && define.amd;+ var HEAD = 1; /* i: waiting for magic header */+ var FLAGS = 2; /* i: waiting for method and flags (gzip) */+ var TIME = 3; /* i: waiting for modification time (gzip) */+ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */+ var EXLEN = 5; /* i: waiting for extra length (gzip) */+ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */+ var NAME = 7; /* i: waiting for end of file name (gzip) */+ var COMMENT = 8; /* i: waiting for end of comment (gzip) */+ var HCRC = 9; /* i: waiting for header crc (gzip) */+ var DICTID = 10; /* i: waiting for dictionary check value */+ var DICT = 11; /* waiting for inflateSetDictionary() call */+ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */+ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */+ var STORED = 14; /* i: waiting for stored size (length and complement) */+ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */+ var COPY = 16; /* i/o: waiting for input or output to copy stored block */+ var TABLE = 17; /* i: waiting for dynamic block table lengths */+ var LENLENS = 18; /* i: waiting for code length code lengths */+ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */+ var LEN_ = 20; /* i: same as LEN below, but only first time in */+ var LEN = 21; /* i: waiting for length/lit/eob code */+ var LENEXT = 22; /* i: waiting for length extra bits */+ var DIST = 23; /* i: waiting for distance code */+ var DISTEXT = 24; /* i: waiting for distance extra bits */+ var MATCH = 25; /* o: waiting for output space to copy string */+ var LIT = 26; /* o: waiting for output space to write literal */+ var CHECK = 27; /* i: waiting for 32-bit check value */+ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */+ var DONE = 29; /* finished check, done -- remain here until reset */+ var BAD = 30; /* got a data error -- remain here until reset */+ var MEM = 31; /* got an inflate() memory error -- remain here until reset */+ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */- // Detect native implementations.- var nativeJSON = typeof JSON == "object" && JSON;+ /* ===========================================================================*/- // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if- // available.- var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;- if (JSON3 && nativeJSON) {- // Explicitly delegate to the native `stringify` and `parse`- // implementations in CommonJS environments.- JSON3.stringify = nativeJSON.stringify;- JSON3.parse = nativeJSON.parse;- } else {- // Export for web browsers, JavaScript engines, and asynchronous module- // loaders, using the global `JSON` object if available.- JSON3 = window.JSON = nativeJSON || {};- }- // Test the `Date#getUTC*` methods. Based on work by @Yaffle.- var isExtended = new Date(-3509827334573292);- try {- // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical- // results for certain dates in Opera >= 10.53.- isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&- // Safari < 2.0.2 stores the internal millisecond time value correctly,- // but clips the values returned by the date methods to the range of- // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).- isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;- } catch (exception) {}+ var ENOUGH_LENS = 852;+ var ENOUGH_DISTS = 592;+ //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);- // Internal: Determines whether the native `JSON.stringify` and `parse`- // implementations are spec-compliant. Based on work by Ken Snyder.- function has(name) {- if (has[name] !== undef) {- // Return cached feature test result.- return has[name];- }+ var MAX_WBITS = 15;+ /* 32K LZ77 window */+ var DEF_WBITS = MAX_WBITS;- var isSupported;- if (name == "bug-string-char-index") {- // IE <= 7 doesn't support accessing string characters using square- // bracket notation. IE 8 only supports this for primitives.- isSupported = "a"[0] != "a";- } else if (name == "json") {- // Indicates whether both `JSON.stringify` and `JSON.parse` are- // supported.- isSupported = has("json-stringify") && has("json-parse");- } else {- var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';- // Test `JSON.stringify`.- if (name == "json-stringify") {- var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;- if (stringifySupported) {- // A test function object with a custom `toJSON` method.- (value = function () {- return 1;- }).toJSON = value;- try {- stringifySupported =- // Firefox 3.1b1 and b2 serialize string, number, and boolean- // primitives as object literals.- stringify(0) === "0" &&- // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object- // literals.- stringify(new Number()) === "0" &&- stringify(new String()) == '""' &&- // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or- // does not define a canonical JSON representation (this applies to- // objects with `toJSON` properties as well, *unless* they are nested- // within an object or array).- stringify(getClass) === undef &&- // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and- // FF 3.1b3 pass this test.- stringify(undef) === undef &&- // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,- // respectively, if the value is omitted entirely.- stringify() === undef &&- // FF 3.1b1, 2 throw an error if the given value is not a number,- // string, array, object, Boolean, or `null` literal. This applies to- // objects with custom `toJSON` methods as well, unless they are nested- // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`- // methods entirely.- stringify(value) === "1" &&- stringify([value]) == "[1]" &&- // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of- // `"[null]"`.- stringify([undef]) == "[null]" &&- // YUI 3.0.0b1 fails to serialize `null` literals.- stringify(null) == "null" &&- // FF 3.1b1, 2 halts serialization if an array contains a function:- // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3- // elides non-JSON values from objects and arrays, unless they- // define custom `toJSON` methods.- stringify([undef, getClass, null]) == "[null,null,null]" &&- // Simple serialization test. FF 3.1b1 uses Unicode escape sequences- // where character escape codes are expected (e.g., `\b` => `\u0008`).- stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&- // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.- stringify(null, value) === "1" &&- stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&- // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly- // serialize extended years.- stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&- // The milliseconds are optional in ES 5, but required in 5.1.- stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&- // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative- // four-digit years instead of six-digit years. Credits: @Yaffle.- stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&- // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond- // values less than 1000. Credits: @Yaffle.- stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';- } catch (exception) {- stringifySupported = false;- }- }- isSupported = stringifySupported;- }- // Test `JSON.parse`.- if (name == "json-parse") {- var parse = JSON3.parse;- if (typeof parse == "function") {- try {- // FF 3.1b1, b2 will throw an exception if a bare literal is provided.- // Conforming implementations should also coerce the initial argument to- // a string prior to parsing.- if (parse("0") === 0 && !parse(false)) {- // Simple parsing test.- value = parse(serialized);- var parseSupported = value["a"].length == 5 && value["a"][0] === 1;- if (parseSupported) {- try {- // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.- parseSupported = !parse('"\t"');- } catch (exception) {}- if (parseSupported) {- try {- // FF 4.0 and 4.0.1 allow leading `+` signs and leading- // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow- // certain octal literals.- parseSupported = parse("01") !== 1;- } catch (exception) {}- }- if (parseSupported) {- try {- // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal- // points. These environments, along with FF 3.1b1 and 2,- // also allow trailing commas in JSON objects and arrays.- parseSupported = parse("1.") !== 1;- } catch (exception) {}- }- }- }- } catch (exception) {- parseSupported = false;- }- }- isSupported = parseSupported;- }- }- return has[name] = !!isSupported;- }- if (!has("json")) {- // Common `[[Class]]` name aliases.- var functionClass = "[object Function]";- var dateClass = "[object Date]";- var numberClass = "[object Number]";- var stringClass = "[object String]";- var arrayClass = "[object Array]";- var booleanClass = "[object Boolean]";+ function ZSWAP32(q) {+ return (((q >>> 24) & 0xff) ++ ((q >>> 8) & 0xff00) ++ ((q & 0xff00) << 8) ++ ((q & 0xff) << 24));+ }- // Detect incomplete support for accessing string characters by index.- var charIndexBuggy = has("bug-string-char-index");- // Define additional utility methods if the `Date` methods are buggy.- if (!isExtended) {- var floor = Math.floor;- // A mapping between the months of the year and the number of days between- // January 1st and the first of the respective month.- var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];- // Internal: Calculates the number of days between the Unix epoch and the- // first day of the given month.- var getDay = function (year, month) {- return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);- };- }+ function InflateState() {+ this.mode = 0; /* current inflate mode */+ this.last = false; /* true if processing last block */+ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */+ this.havedict = false; /* true if dictionary provided */+ this.flags = 0; /* gzip header method and flags (0 if zlib) */+ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */+ this.check = 0; /* protected copy of check value */+ this.total = 0; /* protected copy of output count */+ // TODO: may be {}+ this.head = null; /* where to save gzip header information */- // Internal: Determines if a property is a direct property of the given- // object. Delegates to the native `Object#hasOwnProperty` method.- if (!(isProperty = {}.hasOwnProperty)) {- isProperty = function (property) {- var members = {}, constructor;- if ((members.__proto__ = null, members.__proto__ = {- // The *proto* property cannot be set multiple times in recent- // versions of Firefox and SeaMonkey.- "toString": 1- }, members).toString != getClass) {- // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but- // supports the mutable *proto* property.- isProperty = function (property) {- // Capture and break the object's prototype chain (see section 8.6.2- // of the ES 5.1 spec). The parenthesized expression prevents an- // unsafe transformation by the Closure Compiler.- var original = this.__proto__, result = property in (this.__proto__ = null, this);- // Restore the original prototype chain.- this.__proto__ = original;- return result;- };- } else {- // Capture a reference to the top-level `Object` constructor.- constructor = members.constructor;- // Use the `constructor` property to simulate `Object#hasOwnProperty` in- // other environments.- isProperty = function (property) {- var parent = (this.constructor || constructor).prototype;- return property in this && !(property in parent && this[property] === parent[property]);- };- }- members = null;- return isProperty.call(this, property);- };- }+ /* sliding window */+ this.wbits = 0; /* log base 2 of requested window size */+ this.wsize = 0; /* window size or zero if not using window */+ this.whave = 0; /* valid bytes in the window */+ this.wnext = 0; /* window write index */+ this.window = null; /* allocated sliding window, if needed */- // Internal: A set of primitive types used by `isHostType`.- var PrimitiveTypes = {- 'boolean': 1,- 'number': 1,- 'string': 1,- 'undefined': 1- };+ /* bit accumulator */+ this.hold = 0; /* input bit accumulator */+ this.bits = 0; /* number of bits in "in" */- // Internal: Determines if the given object `property` value is a- // non-primitive.- var isHostType = function (object, property) {- var type = typeof object[property];- return type == 'object' ? !!object[property] : !PrimitiveTypes[type];- };+ /* for string and stored block copying */+ this.length = 0; /* literal or length of data to copy */+ this.offset = 0; /* distance back to copy string from */- // Internal: Normalizes the `for...in` iteration algorithm across- // environments. Each enumerated key is yielded to a `callback` function.- forEach = function (object, callback) {- var size = 0, Properties, members, property;+ /* for table and code decoding */+ this.extra = 0; /* extra bits needed */- // Tests for bugs in the current environment's `for...in` algorithm. The- // `valueOf` property inherits the non-enumerable flag from- // `Object.prototype` in older versions of IE, Netscape, and Mozilla.- (Properties = function () {- this.valueOf = 0;- }).prototype.valueOf = 0;+ /* fixed and dynamic code tables */+ this.lencode = null; /* starting table for length/literal codes */+ this.distcode = null; /* starting table for distance codes */+ this.lenbits = 0; /* index bits for lencode */+ this.distbits = 0; /* index bits for distcode */- // Iterate over a new instance of the `Properties` class.- members = new Properties();- for (property in members) {- // Ignore all properties inherited from `Object.prototype`.- if (isProperty.call(members, property)) {- size++;- }- }- Properties = members = null;+ /* dynamic table building */+ this.ncode = 0; /* number of code length code lengths */+ this.nlen = 0; /* number of length code lengths */+ this.ndist = 0; /* number of distance code lengths */+ this.have = 0; /* number of code lengths in lens[] */+ this.next = null; /* next available space in codes[] */- // Normalize the iteration algorithm.- if (!size) {- // A list of non-enumerable properties inherited from `Object.prototype`.- members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];- // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable- // properties.- forEach = function (object, callback) {- var isFunction = getClass.call(object) == functionClass, property, length;- var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;- for (property in object) {- // Gecko <= 1.0 enumerates the `prototype` property of functions under- // certain conditions; IE does not.- if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {- callback(property);- }- }- // Manually invoke the callback for each non-enumerable property.- for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));- };- } else if (size == 2) {- // Safari <= 2.0.4 enumerates shadowed properties twice.- forEach = function (object, callback) {- // Create a set of iterated properties.- var members = {}, isFunction = getClass.call(object) == functionClass, property;- for (property in object) {- // Store each property name to prevent double enumeration. The- // `prototype` property of functions is not enumerated due to cross-- // environment inconsistencies.- if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {- callback(property);- }- }- };- } else {- // No bugs detected; use the standard `for...in` algorithm.- forEach = function (object, callback) {- var isFunction = getClass.call(object) == functionClass, property, isConstructor;- for (property in object) {- if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {- callback(property);- }- }- // Manually invoke the callback for the `constructor` property due to- // cross-environment inconsistencies.- if (isConstructor || isProperty.call(object, (property = "constructor"))) {- callback(property);- }- };- }- return forEach(object, callback);- };+ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */+ this.work = new utils.Buf16(288); /* work area for code table building */- // Public: Serializes a JavaScript `value` as a JSON string. The optional- // `filter` argument may specify either a function that alters how object and- // array members are serialized, or an array of strings and numbers that- // indicates which properties should be serialized. The optional `width`- // argument may be either a string or number that specifies the indentation- // level of the output.- if (!has("json-stringify")) {- // Internal: A map of control characters and their escaped equivalents.- var Escapes = {- 92: "\\\\",- 34: '\\"',- 8: "\\b",- 12: "\\f",- 10: "\\n",- 13: "\\r",- 9: "\\t"- };+ /*+ because we don't have pointers in js, we use lencode and distcode directly+ as buffers so we don't need codes+ */+ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */+ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */+ this.distdyn = null; /* dynamic table for distance codes (JS specific) */+ this.sane = 0; /* if false, allow invalid distance too far */+ this.back = 0; /* bits back of last unprocessed length/lit */+ this.was = 0; /* initial length of match */+ }- // Internal: Converts `value` into a zero-padded string such that its- // length is at least equal to `width`. The `width` must be <= 6.- var leadingZeroes = "000000";- var toPaddedString = function (width, value) {- // The `|| 0` expression is necessary to work around a bug in- // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.- return (leadingZeroes + (value || 0)).slice(-width);- };+ function inflateResetKeep(strm) {+ var state;- // Internal: Double-quotes a string `value`, replacing all ASCII control- // characters (characters with code unit values between 0 and 31) with- // their escaped equivalents. This is an implementation of the- // `Quote(value)` operation defined in ES 5.1 section 15.12.3.- var unicodePrefix = "\\u00";- var quote = function (value) {- var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;- if (isLarge) {- symbols = value.split("");- }- for (; index < length; index++) {- var charCode = value.charCodeAt(index);- // If the character is a control character, append its Unicode or- // shorthand escape sequence; otherwise, append the character as-is.- switch (charCode) {- case 8: case 9: case 10: case 12: case 13: case 34: case 92:- result += Escapes[charCode];- break;- default:- if (charCode < 32) {- result += unicodePrefix + toPaddedString(2, charCode.toString(16));- break;- }- result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];- }- }- return result + '"';- };+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;+ strm.total_in = strm.total_out = state.total = 0;+ strm.msg = ''; /*Z_NULL*/+ if (state.wrap) { /* to support ill-conceived Java test suite */+ strm.adler = state.wrap & 1;+ }+ state.mode = HEAD;+ state.last = 0;+ state.havedict = 0;+ state.dmax = 32768;+ state.head = null/*Z_NULL*/;+ state.hold = 0;+ state.bits = 0;+ //state.lencode = state.distcode = state.next = state.codes;+ state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);+ state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);- // Internal: Recursively serializes an object. Implements the- // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.- var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {- var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;- try {- // Necessary for host object support.- value = object[property];- } catch (exception) {}- if (typeof value == "object" && value) {- className = getClass.call(value);- if (className == dateClass && !isProperty.call(value, "toJSON")) {- if (value > -1 / 0 && value < 1 / 0) {- // Dates are serialized according to the `Date#toJSON` method- // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15- // for the ISO 8601 date time string format.- if (getDay) {- // Manually compute the year, month, date, hours, minutes,- // seconds, and milliseconds if the `getUTC*` methods are- // buggy. Adapted from @Yaffle's `date-shim` project.- date = floor(value / 864e5);- for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);- for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);- date = 1 + date - getDay(year, month);- // The `time` value specifies the time within the day (see ES- // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used- // to compute `A modulo B`, as the `%` operator does not- // correspond to the `modulo` operation for negative numbers.- time = (value % 864e5 + 864e5) % 864e5;- // The hours, minutes, seconds, and milliseconds are obtained by- // decomposing the time within the day. See section 15.9.1.10.- hours = floor(time / 36e5) % 24;- minutes = floor(time / 6e4) % 60;- seconds = floor(time / 1e3) % 60;- milliseconds = time % 1e3;- } else {- year = value.getUTCFullYear();- month = value.getUTCMonth();- date = value.getUTCDate();- hours = value.getUTCHours();- minutes = value.getUTCMinutes();- seconds = value.getUTCSeconds();- milliseconds = value.getUTCMilliseconds();- }- // Serialize extended years correctly.- value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +- "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +- // Months, dates, hours, minutes, and seconds should have two- // digits; milliseconds should have three.- "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +- // Milliseconds are optional in ES 5.0, but required in 5.1.- "." + toPaddedString(3, milliseconds) + "Z";- } else {- value = null;- }- } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {- // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the- // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3- // ignores all `toJSON` methods on these objects unless they are- // defined directly on an instance.- value = value.toJSON(property);- }- }- if (callback) {- // If a replacement function was provided, call it to obtain the value- // for serialization.- value = callback.call(object, property, value);- }- if (value === null) {- return "null";- }- className = getClass.call(value);- if (className == booleanClass) {- // Booleans are represented literally.- return "" + value;- } else if (className == numberClass) {- // JSON numbers must be finite. `Infinity` and `NaN` are serialized as- // `"null"`.- return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";- } else if (className == stringClass) {- // Strings are double-quoted and escaped.- return quote("" + value);- }- // Recursively serialize objects and arrays.- if (typeof value == "object") {- // Check for cyclic structures. This is a linear search; performance- // is inversely proportional to the number of unique nested objects.- for (length = stack.length; length--;) {- if (stack[length] === value) {- // Cyclic structures cannot be serialized by `JSON.stringify`.- throw TypeError();- }- }- // Add the object to the stack of traversed objects.- stack.push(value);- results = [];- // Save the current indentation level and indent one additional level.- prefix = indentation;- indentation += whitespace;- if (className == arrayClass) {- // Recursively serialize array elements.- for (index = 0, length = value.length; index < length; index++) {- element = serialize(index, value, callback, properties, whitespace, indentation, stack);- results.push(element === undef ? "null" : element);- }- result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";- } else {- // Recursively serialize object members. Members are selected from- // either a user-specified list of property names, or the object- // itself.- forEach(properties || value, function (property) {- var element = serialize(property, value, callback, properties, whitespace, indentation, stack);- if (element !== undef) {- // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}- // is not the empty string, let `member` {quote(property) + ":"}- // be the concatenation of `member` and the `space` character."- // The "`space` character" refers to the literal space- // character, not the `space` {width} argument provided to- // `JSON.stringify`.- results.push(quote(property) + ":" + (whitespace ? " " : "") + element);- }- });- result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";- }- // Remove the object from the traversed object stack.- stack.pop();- return result;- }- };+ state.sane = 1;+ state.back = -1;+ //Tracev((stderr, "inflate: reset\n"));+ return Z_OK;+ }- // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.- JSON3.stringify = function (source, filter, width) {- var whitespace, callback, properties, className;- if (typeof filter == "function" || typeof filter == "object" && filter) {- if ((className = getClass.call(filter)) == functionClass) {- callback = filter;- } else if (className == arrayClass) {- // Convert the property names array into a makeshift set.- properties = {};- for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));- }- }- if (width) {- if ((className = getClass.call(width)) == numberClass) {- // Convert the `width` to an integer and create a string containing- // `width` number of space characters.- if ((width -= width % 1) > 0) {- for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");- }- } else if (className == stringClass) {- whitespace = width.length <= 10 ? width : width.slice(0, 10);- }- }- // Opera <= 7.54u2 discards the values associated with empty string keys- // (`""`) only if they are used directly within an object member list- // (e.g., `!("" in { "": 1})`).- return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);- };- }+ function inflateReset(strm) {+ var state;- // Public: Parses a JSON source string.- if (!has("json-parse")) {- var fromCharCode = String.fromCharCode;+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;+ state.wsize = 0;+ state.whave = 0;+ state.wnext = 0;+ return inflateResetKeep(strm);- // Internal: A map of escaped control characters and their unescaped- // equivalents.- var Unescapes = {- 92: "\\",- 34: '"',- 47: "/",- 98: "\b",- 116: "\t",- 110: "\n",- 102: "\f",- 114: "\r"- };+ }- // Internal: Stores the parser state.- var Index, Source;+ function inflateReset2(strm, windowBits) {+ var wrap;+ var state;- // Internal: Resets the parser state and throws a `SyntaxError`.- var abort = function() {- Index = Source = null;- throw SyntaxError();- };+ /* get the state */+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;- // Internal: Returns the next token, or `"$"` if the parser has reached- // the end of the source string. A token may be a string, number, `null`- // literal, or Boolean literal.- var lex = function () {- var source = Source, length = source.length, value, begin, position, isSigned, charCode;- while (Index < length) {- charCode = source.charCodeAt(Index);- switch (charCode) {- case 9: case 10: case 13: case 32:- // Skip whitespace tokens, including tabs, carriage returns, line- // feeds, and space characters.- Index++;- break;- case 123: case 125: case 91: case 93: case 58: case 44:- // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at- // the current position.- value = charIndexBuggy ? source.charAt(Index) : source[Index];- Index++;- return value;- case 34:- // `"` delimits a JSON string; advance to the next character and- // begin parsing the string. String tokens are prefixed with the- // sentinel `@` character to distinguish them from punctuators and- // end-of-string tokens.- for (value = "@", Index++; Index < length;) {- charCode = source.charCodeAt(Index);- if (charCode < 32) {- // Unescaped ASCII control characters (those with a code unit- // less than the space character) are not permitted.- abort();- } else if (charCode == 92) {- // A reverse solidus (`\`) marks the beginning of an escaped- // control character (including `"`, `\`, and `/`) or Unicode- // escape sequence.- charCode = source.charCodeAt(++Index);- switch (charCode) {- case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:- // Revive escaped control characters.- value += Unescapes[charCode];- Index++;- break;- case 117:- // `\u` marks the beginning of a Unicode escape sequence.- // Advance to the first character and validate the- // four-digit code point.- begin = ++Index;- for (position = Index + 4; Index < position; Index++) {- charCode = source.charCodeAt(Index);- // A valid sequence comprises four hexdigits (case-- // insensitive) that form a single hexadecimal value.- if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {- // Invalid Unicode escape sequence.- abort();- }- }- // Revive the escaped character.- value += fromCharCode("0x" + source.slice(begin, Index));- break;- default:- // Invalid escape sequence.- abort();- }- } else {- if (charCode == 34) {- // An unescaped double-quote character marks the end of the- // string.- break;- }- charCode = source.charCodeAt(Index);- begin = Index;- // Optimize for the common case where a string is valid.- while (charCode >= 32 && charCode != 92 && charCode != 34) {- charCode = source.charCodeAt(++Index);- }- // Append the string as-is.- value += source.slice(begin, Index);- }- }- if (source.charCodeAt(Index) == 34) {- // Advance to the next character and return the revived string.- Index++;- return value;- }- // Unterminated string.- abort();- default:- // Parse numbers and literals.- begin = Index;- // Advance past the negative sign, if one is specified.- if (charCode == 45) {- isSigned = true;- charCode = source.charCodeAt(++Index);- }- // Parse an integer or floating-point value.- if (charCode >= 48 && charCode <= 57) {- // Leading zeroes are interpreted as octal literals.- if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {- // Illegal octal literal.- abort();- }- isSigned = false;- // Parse the integer component.- for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);- // Floats cannot contain a leading decimal point; however, this- // case is already accounted for by the parser.- if (source.charCodeAt(Index) == 46) {- position = ++Index;- // Parse the decimal component.- for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);- if (position == Index) {- // Illegal trailing decimal.- abort();- }- Index = position;- }- // Parse exponents. The `e` denoting the exponent is- // case-insensitive.- charCode = source.charCodeAt(Index);- if (charCode == 101 || charCode == 69) {- charCode = source.charCodeAt(++Index);- // Skip past the sign following the exponent, if one is- // specified.- if (charCode == 43 || charCode == 45) {- Index++;- }- // Parse the exponential component.- for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);- if (position == Index) {- // Illegal empty exponent.- abort();- }- Index = position;- }- // Coerce the parsed value to a JavaScript number.- return +source.slice(begin, Index);- }- // A negative sign may only precede numbers.- if (isSigned) {- abort();- }- // `true`, `false`, and `null` literals.- if (source.slice(Index, Index + 4) == "true") {- Index += 4;- return true;- } else if (source.slice(Index, Index + 5) == "false") {- Index += 5;- return false;- } else if (source.slice(Index, Index + 4) == "null") {- Index += 4;- return null;- }- // Unrecognized token.- abort();- }- }- // Return the sentinel `$` character if the parser has reached the end- // of the source string.- return "$";- };+ /* extract wrap request from windowBits parameter */+ if (windowBits < 0) {+ wrap = 0;+ windowBits = -windowBits;+ }+ else {+ wrap = (windowBits >> 4) + 1;+ if (windowBits < 48) {+ windowBits &= 15;+ }+ }- // Internal: Parses a JSON `value` token.- var get = function (value) {- var results, hasMembers;- if (value == "$") {- // Unexpected end of input.- abort();- }- if (typeof value == "string") {- if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {- // Remove the sentinel `@` character.- return value.slice(1);- }- // Parse object and array literals.- if (value == "[") {- // Parses a JSON array, returning a new JavaScript array.- results = [];- for (;; hasMembers || (hasMembers = true)) {- value = lex();- // A closing square bracket marks the end of the array literal.- if (value == "]") {- break;- }- // If the array literal contains elements, the current token- // should be a comma separating the previous element from the- // next.- if (hasMembers) {- if (value == ",") {- value = lex();- if (value == "]") {- // Unexpected trailing `,` in array literal.- abort();- }- } else {- // A `,` must separate each array element.- abort();- }- }- // Elisions and leading commas are not permitted.- if (value == ",") {- abort();- }- results.push(get(value));- }- return results;- } else if (value == "{") {- // Parses a JSON object, returning a new JavaScript object.- results = {};- for (;; hasMembers || (hasMembers = true)) {- value = lex();- // A closing curly brace marks the end of the object literal.- if (value == "}") {- break;- }- // If the object literal contains members, the current token- // should be a comma separator.- if (hasMembers) {- if (value == ",") {- value = lex();- if (value == "}") {- // Unexpected trailing `,` in object literal.- abort();- }- } else {- // A `,` must separate each object member.- abort();- }- }- // Leading commas are not permitted, object property names must be- // double-quoted strings, and a `:` must separate each property- // name and value.- if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {- abort();- }- results[value.slice(1)] = get(lex());- }- return results;- }- // Unexpected token encountered.- abort();- }- return value;- };+ /* set number of window bits, free window if different */+ if (windowBits && (windowBits < 8 || windowBits > 15)) {+ return Z_STREAM_ERROR;+ }+ if (state.window !== null && state.wbits !== windowBits) {+ state.window = null;+ }- // Internal: Updates a traversed object member.- var update = function(source, property, callback) {- var element = walk(source, property, callback);- if (element === undef) {- delete source[property];- } else {- source[property] = element;- }- };+ /* update state and reset the rest of it */+ state.wrap = wrap;+ state.wbits = windowBits;+ return inflateReset(strm);+ }- // Internal: Recursively traverses a parsed JSON object, invoking the- // `callback` function for each value. This is an implementation of the- // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.- var walk = function (source, property, callback) {- var value = source[property], length;- if (typeof value == "object" && value) {- // `forEach` can't be used to traverse an array in Opera <= 8.54- // because its `Object#hasOwnProperty` implementation returns `false`- // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).- if (getClass.call(value) == arrayClass) {- for (length = value.length; length--;) {- update(value, length, callback);- }- } else {- forEach(value, function (property) {- update(value, property, callback);- });- }- }- return callback.call(source, property, value);- };+ function inflateInit2(strm, windowBits) {+ var ret;+ var state;- // Public: `JSON.parse`. See ES 5.1 section 15.12.2.- JSON3.parse = function (source, callback) {- var result, value;- Index = 0;- Source = "" + source;- result = get(lex());- // If a JSON string contains multiple tokens, it is invalid.- if (lex() != "$") {- abort();- }- // Reset the parser state.- Index = Source = null;- return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;- };- }- }+ if (!strm) { return Z_STREAM_ERROR; }+ //strm.msg = Z_NULL; /* in case we return an error */- // Export for asynchronous module loaders.- if (isLoader) {- define(function () {- return JSON3;- });+ state = new InflateState();++ //if (state === Z_NULL) return Z_MEM_ERROR;+ //Tracev((stderr, "inflate: allocated\n"));+ strm.state = state;+ state.window = null/*Z_NULL*/;+ ret = inflateReset2(strm, windowBits);+ if (ret !== Z_OK) {+ strm.state = null/*Z_NULL*/;}- }(this));+ return ret;+ }++ function inflateInit(strm) {+ return inflateInit2(strm, DEF_WBITS);+ }+- },{}],81:[function(require,module,exports){/*- A JavaScript implementation of the SHA family of hashes, as- defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation- as defined in FIPS PUB 198a+ Return state with length and distance decoding tables and index sizes set to+ fixed code decoding. Normally this returns fixed tables from inffixed.h.+ If BUILDFIXED is defined, then instead this routine builds the tables the+ first time it's called, and returns those tables the first time and+ thereafter. This reduces the size of the code by about 2K bytes, in+ exchange for a little execution time. However, BUILDFIXED should not be+ used for threaded applications, since the rewriting of the tables and virgin+ may not be thread-safe.+ */+ var virgin = true;- Copyright Brian Turek 2008-2013- Distributed under the BSD License- See http://caligatio.github.com/jsSHA/ for more information+ var lenfix, distfix; // We have no pointers in JS, so keep tables separate- Several functions taken from Paul Johnston- */- (function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==- typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";- return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===- b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|- (g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,- binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,- c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=- {outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):- new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,- 34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>- 16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>- 16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>- 16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-- 14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,- 1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,- 2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],- 3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),- new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),- new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,- 3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,- d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?- new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,- d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);+ function fixedtables(state) {+ /* build fixed huffman tables if first call (may not be thread safe) */+ if (virgin) {+ var sym;- },{}],82:[function(require,module,exports){- /**- * Helpers.- */+ lenfix = new utils.Buf32(512);+ distfix = new utils.Buf32(32);- var s = 1000;- var m = s * 60;- var h = m * 60;- var d = h * 24;- var y = d * 365.25;+ /* literal/length table */+ sym = 0;+ while (sym < 144) { state.lens[sym++] = 8; }+ while (sym < 256) { state.lens[sym++] = 9; }+ while (sym < 280) { state.lens[sym++] = 7; }+ while (sym < 288) { state.lens[sym++] = 8; }- /**- * Parse or format the given `val`.- *- * Options:- *- * - `long` verbose formatting [false]- *- * @param {String|Number} val- * @param {Object} options- * @return {String|Number}- * @api public- */+ inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});- module.exports = function(val, options){- options = options || {};- if ('string' == typeof val) return parse(val);- return options.long- ? long(val)- : short(val);- };+ /* distance table */+ sym = 0;+ while (sym < 32) { state.lens[sym++] = 5; }- /**- * Parse the given `str` and return milliseconds.- *- * @param {String} str- * @return {Number}- * @api private- */+ inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});- function parse(str) {- var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);- if (!match) return;- var n = parseFloat(match[1]);- var type = (match[2] || 'ms').toLowerCase();- switch (type) {- case 'years':- case 'year':- case 'y':- return n * y;- case 'days':- case 'day':- case 'd':- return n * d;- case 'hours':- case 'hour':- case 'h':- return n * h;- case 'minutes':- case 'minute':- case 'm':- return n * m;- case 'seconds':- case 'second':- case 's':- return n * s;- case 'ms':- return n;+ /* do this just once */+ virgin = false;}- }-- /**- * Short format for `ms`.- *- * @param {Number} ms- * @return {String}- * @api private- */- function short(ms) {- if (ms >= d) return Math.round(ms / d) + 'd';- if (ms >= h) return Math.round(ms / h) + 'h';- if (ms >= m) return Math.round(ms / m) + 'm';- if (ms >= s) return Math.round(ms / s) + 's';- return ms + 'ms';+ state.lencode = lenfix;+ state.lenbits = 9;+ state.distcode = distfix;+ state.distbits = 5;}- /**- * Long format for `ms`.- *- * @param {Number} ms- * @return {String}- * @api private- */-- function long(ms) {- return plural(ms, d, 'day')- || plural(ms, h, 'hour')- || plural(ms, m, 'minute')- || plural(ms, s, 'second')- || ms + ' ms';- }-- /**- * Pluralization helper.- */-- function plural(ms, n, name) {- if (ms < n) return;- if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;- return Math.ceil(ms / n) + ' ' + name + 's';- }- },{}],83:[function(require,module,exports){+ /*+ Update the window with the last wsize (normally 32K) bytes written before+ returning. If window does not exist yet, create it. This is only called+ when a window is already in use, or when output has been written during this+ inflate call, but the end of the deflate stream has not been reached yet.+ It is also called to create a window for dictionary data when a dictionary+ is loaded.- /**- * HOP ref.+ Providing output buffers larger than 32K to inflate() should provide a speed+ advantage, since only the last 32K of output is copied to the sliding window+ upon return from inflate(), and since all distances after the first 32K of+ output will fall in the output data, making match copies simpler and faster.+ The advantage may be dependent on the size of the processor's data caches.*/+ function updatewindow(strm, src, end, copy) {+ var dist;+ var state = strm.state;- var has = Object.prototype.hasOwnProperty;-- /**- * Return own keys in `obj`.- *- * @param {Object} obj- * @return {Array}- * @api public- */+ /* if it hasn't been done already, allocate space for the window */+ if (state.window === null) {+ state.wsize = 1 << state.wbits;+ state.wnext = 0;+ state.whave = 0;- exports.keys = Object.keys || function(obj){- var keys = [];- for (var key in obj) {- if (has.call(obj, key)) {- keys.push(key);- }+ state.window = new utils.Buf8(state.wsize);}- return keys;- };- /**- * Return own values in `obj`.- *- * @param {Object} obj- * @return {Array}- * @api public- */-- exports.values = function(obj){- var vals = [];- for (var key in obj) {- if (has.call(obj, key)) {- vals.push(obj[key]);- }+ /* copy state->wsize or less output bytes into the circular window */+ if (copy >= state.wsize) {+ utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);+ state.wnext = 0;+ state.whave = state.wsize;}- return vals;- };-- /**- * Merge `b` into `a`.- *- * @param {Object} a- * @param {Object} b- * @return {Object} a- * @api public- */-- exports.merge = function(a, b){- for (var key in b) {- if (has.call(b, key)) {- a[key] = b[key];+ else {+ dist = state.wsize - state.wnext;+ if (dist > copy) {+ dist = copy;+ }+ //zmemcpy(state->window + state->wnext, end - copy, dist);+ utils.arraySet(state.window,src, end - copy, dist, state.wnext);+ copy -= dist;+ if (copy) {+ //zmemcpy(state->window, end - copy, copy);+ utils.arraySet(state.window,src, end - copy, copy, 0);+ state.wnext = copy;+ state.whave = state.wsize;+ }+ else {+ state.wnext += dist;+ if (state.wnext === state.wsize) { state.wnext = 0; }+ if (state.whave < state.wsize) { state.whave += dist; }}}- return a;- };-- /**- * Return length of `obj`.- *- * @param {Object} obj- * @return {Number}- * @api public- */-- exports.length = function(obj){- return exports.keys(obj).length;- };-- /**- * Check if `obj` is empty.- *- * @param {Object} obj- * @return {Boolean}- * @api public- */-- exports.isEmpty = function(obj){- return 0 == exports.length(obj);- };- },{}],84:[function(require,module,exports){- // Top level file is just a mixin of submodules & constants- 'use strict';-- var assign = require('./lib/utils/common').assign;-- var deflate = require('./lib/deflate');- var inflate = require('./lib/inflate');- var constants = require('./lib/zlib/constants');-- var pako = {};-- assign(pako, deflate, inflate, constants);-- module.exports = pako;-- },{"./lib/deflate":85,"./lib/inflate":86,"./lib/utils/common":87,"./lib/zlib/constants":90}],85:[function(require,module,exports){- 'use strict';--- var zlib_deflate = require('./zlib/deflate.js');- var utils = require('./utils/common');- var strings = require('./utils/strings');- var msg = require('./zlib/messages');- var zstream = require('./zlib/zstream');+ return 0;+ }- var toString = Object.prototype.toString;+ function inflate(strm, flush) {+ var state;+ var input, output; // input/output buffers+ var next; /* next input INDEX */+ var put; /* next output INDEX */+ var have, left; /* available input and output */+ var hold; /* bit buffer */+ var bits; /* bits in bit buffer */+ var _in, _out; /* save starting available input and output */+ var copy; /* number of stored or match bytes to copy */+ var from; /* where to copy match bytes from */+ var from_source;+ var here = 0; /* current decoding table entry */+ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)+ //var last; /* parent table entry */+ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)+ var len; /* length to copy for repeats, bits to drop */+ var ret; /* return code */+ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */+ var opts;- /* Public constants ==========================================================*/- /* ===========================================================================*/+ var n; // temporary var for NEED_BITS- var Z_NO_FLUSH = 0;- var Z_FINISH = 4;+ var order = /* permutation of code lengths */+ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];- var Z_OK = 0;- var Z_STREAM_END = 1;- var Z_SYNC_FLUSH = 2;- var Z_DEFAULT_COMPRESSION = -1;+ if (!strm || !strm.state || !strm.output ||+ (!strm.input && strm.avail_in !== 0)) {+ return Z_STREAM_ERROR;+ }- var Z_DEFAULT_STRATEGY = 0;+ state = strm.state;+ if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */- var Z_DEFLATED = 8;- /* ===========================================================================*/+ //--- LOAD() ---+ put = strm.next_out;+ output = strm.output;+ left = strm.avail_out;+ next = strm.next_in;+ input = strm.input;+ have = strm.avail_in;+ hold = state.hold;+ bits = state.bits;+ //---+ _in = have;+ _out = left;+ ret = Z_OK;- /**- * class Deflate- *- * Generic JS-style wrapper for zlib calls. If you don't need- * streaming behaviour - use more simple functions: [[deflate]],- * [[deflateRaw]] and [[gzip]].- **/+ inf_leave: // goto emulation+ for (;;) {+ switch (state.mode) {+ case HEAD:+ if (state.wrap === 0) {+ state.mode = TYPEDO;+ break;+ }+ //=== NEEDBITS(16);+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */+ state.check = 0/*crc32(0L, Z_NULL, 0)*/;+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//- /* internal- * Deflate.chunks -> Array- *- * Chunks of output data, if [[Deflate#onData]] not overriden.- **/-- /**- * Deflate.result -> Uint8Array|Array- *- * Compressed result, generated by default [[Deflate#onData]]- * and [[Deflate#onEnd]] handlers. Filled after you push last chunk- * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you- * push a chunk with explicit flush (call [[Deflate#push]] with- * `Z_SYNC_FLUSH` param).- **/-- /**- * Deflate.err -> Number- *- * Error code after deflate finished. 0 (Z_OK) on success.- * You will not need it in real life, because deflate errors- * are possible only on wrong options or bad `onData` / `onEnd`- * custom handlers.- **/-- /**- * Deflate.msg -> String- *- * Error message, if [[Deflate.err]] != 0- **/--- /**- * new Deflate(options)- * - options (Object): zlib deflate options.- *- * Creates new deflator instance with specified params. Throws exception- * on bad params. Supported options:- *- * - `level`- * - `windowBits`- * - `memLevel`- * - `strategy`- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information on these.- *- * Additional options, for internal needs:- *- * - `chunkSize` - size of generated data chunks (16K by default)- * - `raw` (Boolean) - do raw deflate- * - `gzip` (Boolean) - create gzip wrapper- * - `to` (String) - if equal to 'string', then result will be "binary string"- * (each char code [0..255])- * - `header` (Object) - custom header for gzip- * - `text` (Boolean) - true if compressed data believed to be text- * - `time` (Number) - modification time, unix timestamp- * - `os` (Number) - operation system code- * - `extra` (Array) - array of bytes with extra data (max 65536)- * - `name` (String) - file name (binary string)- * - `comment` (String) - comment (binary string)- * - `hcrc` (Boolean) - true if header crc should be added- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);- *- * var deflate = new pako.Deflate({ level: 3});- *- * deflate.push(chunk1, false);- * deflate.push(chunk2, true); // true -> last chunk- *- * if (deflate.err) { throw new Error(deflate.err); }- *- * console.log(deflate.result);- * ```- **/- var Deflate = function(options) {-- this.options = utils.assign({- level: Z_DEFAULT_COMPRESSION,- method: Z_DEFLATED,- chunkSize: 16384,- windowBits: 15,- memLevel: 8,- strategy: Z_DEFAULT_STRATEGY,- to: ''- }, options || {});-- var opt = this.options;-- if (opt.raw && (opt.windowBits > 0)) {- opt.windowBits = -opt.windowBits;- }-- else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {- opt.windowBits += 16;- }-- this.err = 0; // error code, if happens (0 = Z_OK)- this.msg = ''; // error message- this.ended = false; // used to avoid multiple onEnd() calls- this.chunks = []; // chunks of compressed data-- this.strm = new zstream();- this.strm.avail_out = 0;-- var status = zlib_deflate.deflateInit2(- this.strm,- opt.level,- opt.method,- opt.windowBits,- opt.memLevel,- opt.strategy- );-- if (status !== Z_OK) {- throw new Error(msg[status]);- }-- if (opt.header) {- zlib_deflate.deflateSetHeader(this.strm, opt.header);- }- };-- /**- * Deflate#push(data[, mode]) -> Boolean- * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be- * converted to utf8 byte sequence.- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.- *- * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with- * new compressed chunks. Returns `true` on success. The last data block must have- * mode Z_FINISH (or `true`). That will flush internal pending buffers and call- * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you- * can use mode Z_SYNC_FLUSH, keeping the compression context.- *- * On fail call [[Deflate#onEnd]] with error code and return false.- *- * We strongly recommend to use `Uint8Array` on input for best speed (output- * array format is detected automatically). Also, don't skip last param and always- * use the same type in your code (boolean or number). That will improve JS speed.- *- * For regular `Array`-s make sure all elements are [0..255].- *- * ##### Example- *- * ```javascript- * push(chunk, false); // push one of data chunks- * ...- * push(chunk, true); // push last chunk- * ```- **/- Deflate.prototype.push = function(data, mode) {- var strm = this.strm;- var chunkSize = this.options.chunkSize;- var status, _mode;-- if (this.ended) { return false; }-- _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);-- // Convert data if needed- if (typeof data === 'string') {- // If we need to compress text, change encoding to utf8.- strm.input = strings.string2buf(data);- } else if (toString.call(data) === '[object ArrayBuffer]') {- strm.input = new Uint8Array(data);- } else {- strm.input = data;- }-- strm.next_in = 0;- strm.avail_in = strm.input.length;-- do {- if (strm.avail_out === 0) {- strm.output = new utils.Buf8(chunkSize);- strm.next_out = 0;- strm.avail_out = chunkSize;- }- status = zlib_deflate.deflate(strm, _mode); /* no bad return value */-- if (status !== Z_STREAM_END && status !== Z_OK) {- this.onEnd(status);- this.ended = true;- return false;- }- if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {- if (this.options.to === 'string') {- this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));- } else {- this.onData(utils.shrinkBuf(strm.output, strm.next_out));+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = FLAGS;+ break;}- }- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);-- // Finalize on the last chunk.- if (_mode === Z_FINISH) {- status = zlib_deflate.deflateEnd(this.strm);- this.onEnd(status);- this.ended = true;- return status === Z_OK;- }-- // callback interim results if Z_SYNC_FLUSH.- if (_mode === Z_SYNC_FLUSH) {- this.onEnd(Z_OK);- strm.avail_out = 0;- return true;- }-- return true;- };--- /**- * Deflate#onData(chunk) -> Void- * - chunk (Uint8Array|Array|String): ouput data. Type of array depends- * on js engine support. When string output requested, each chunk- * will be string.- *- * By default, stores data blocks in `chunks[]` property and glue- * those in `onEnd`. Override this handler, if you need another behaviour.- **/- Deflate.prototype.onData = function(chunk) {- this.chunks.push(chunk);- };--- /**- * Deflate#onEnd(status) -> Void- * - status (Number): deflate status. 0 (Z_OK) on success,- * other if not.- *- * Called once after you tell deflate that the input stream is- * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)- * or if an error happened. By default - join collected chunks,- * free memory and fill `results` / `err` properties.- **/- Deflate.prototype.onEnd = function(status) {- // On success - join- if (status === Z_OK) {- if (this.options.to === 'string') {- this.result = this.chunks.join('');- } else {- this.result = utils.flattenChunks(this.chunks);- }- }- this.chunks = [];- this.err = status;- this.msg = this.strm.msg;- };--- /**- * deflate(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to compress.- * - options (Object): zlib deflate options.- *- * Compress `data` with deflate alrorythm and `options`.- *- * Supported options are:- *- * - level- * - windowBits- * - memLevel- * - strategy- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information on these.- *- * Sugar (options):- *- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify- * negative windowBits implicitly.- * - `to` (String) - if equal to 'string', then result will be "binary string"- * (each char code [0..255])- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);- *- * console.log(pako.deflate(data));- * ```- **/- function deflate(input, options) {- var deflator = new Deflate(options);-- deflator.push(input, true);-- // That will never happens, if you don't cheat with options :)- if (deflator.err) { throw deflator.msg; }-- return deflator.result;- }--- /**- * deflateRaw(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to compress.- * - options (Object): zlib deflate options.- *- * The same as [[deflate]], but creates raw data, without wrapper- * (header and adler32 crc).- **/- function deflateRaw(input, options) {- options = options || {};- options.raw = true;- return deflate(input, options);- }--- /**- * gzip(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to compress.- * - options (Object): zlib deflate options.- *- * The same as [[deflate]], but create gzip wrapper instead of- * deflate one.- **/- function gzip(input, options) {- options = options || {};- options.gzip = true;- return deflate(input, options);- }--- exports.Deflate = Deflate;- exports.deflate = deflate;- exports.deflateRaw = deflateRaw;- exports.gzip = gzip;-- },{"./utils/common":87,"./utils/strings":88,"./zlib/deflate.js":92,"./zlib/messages":97,"./zlib/zstream":99}],86:[function(require,module,exports){- 'use strict';--- var zlib_inflate = require('./zlib/inflate.js');- var utils = require('./utils/common');- var strings = require('./utils/strings');- var c = require('./zlib/constants');- var msg = require('./zlib/messages');- var zstream = require('./zlib/zstream');- var gzheader = require('./zlib/gzheader');-- var toString = Object.prototype.toString;-- /**- * class Inflate- *- * Generic JS-style wrapper for zlib calls. If you don't need- * streaming behaviour - use more simple functions: [[inflate]]- * and [[inflateRaw]].- **/-- /* internal- * inflate.chunks -> Array- *- * Chunks of output data, if [[Inflate#onData]] not overriden.- **/-- /**- * Inflate.result -> Uint8Array|Array|String- *- * Uncompressed result, generated by default [[Inflate#onData]]- * and [[Inflate#onEnd]] handlers. Filled after you push last chunk- * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you- * push a chunk with explicit flush (call [[Inflate#push]] with- * `Z_SYNC_FLUSH` param).- **/-- /**- * Inflate.err -> Number- *- * Error code after inflate finished. 0 (Z_OK) on success.- * Should be checked if broken data possible.- **/-- /**- * Inflate.msg -> String- *- * Error message, if [[Inflate.err]] != 0- **/--- /**- * new Inflate(options)- * - options (Object): zlib inflate options.- *- * Creates new inflator instance with specified params. Throws exception- * on bad params. Supported options:- *- * - `windowBits`- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information on these.- *- * Additional options, for internal needs:- *- * - `chunkSize` - size of generated data chunks (16K by default)- * - `raw` (Boolean) - do raw inflate- * - `to` (String) - if equal to 'string', then result will be converted- * from utf8 to utf16 (javascript) string. When string output requested,- * chunk length can differ from `chunkSize`, depending on content.- *- * By default, when no options set, autodetect deflate/gzip data format via- * wrapper header.- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);- *- * var inflate = new pako.Inflate({ level: 3});- *- * inflate.push(chunk1, false);- * inflate.push(chunk2, true); // true -> last chunk- *- * if (inflate.err) { throw new Error(inflate.err); }- *- * console.log(inflate.result);- * ```- **/- var Inflate = function(options) {-- this.options = utils.assign({- chunkSize: 16384,- windowBits: 0,- to: ''- }, options || {});-- var opt = this.options;-- // Force window size for `raw` data, if not set directly,- // because we have no header for autodetect.- if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {- opt.windowBits = -opt.windowBits;- if (opt.windowBits === 0) { opt.windowBits = -15; }- }-- // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate- if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&- !(options && options.windowBits)) {- opt.windowBits += 32;- }-- // Gzip header has no info about windows size, we can do autodetect only- // for deflate. So, if window size not set, force it to max when gzip possible- if ((opt.windowBits > 15) && (opt.windowBits < 48)) {- // bit 3 (16) -> gzipped data- // bit 4 (32) -> autodetect gzip/deflate- if ((opt.windowBits & 15) === 0) {- opt.windowBits |= 15;- }- }-- this.err = 0; // error code, if happens (0 = Z_OK)- this.msg = ''; // error message- this.ended = false; // used to avoid multiple onEnd() calls- this.chunks = []; // chunks of compressed data-- this.strm = new zstream();- this.strm.avail_out = 0;-- var status = zlib_inflate.inflateInit2(- this.strm,- opt.windowBits- );-- if (status !== c.Z_OK) {- throw new Error(msg[status]);- }+ state.flags = 0; /* expect zlib header */+ if (state.head) {+ state.head.done = false;+ }+ if (!(state.wrap & 1) || /* check if zlib header allowed */+ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {+ strm.msg = 'incorrect header check';+ state.mode = BAD;+ break;+ }+ if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {+ strm.msg = 'unknown compression method';+ state.mode = BAD;+ break;+ }+ //--- DROPBITS(4) ---//+ hold >>>= 4;+ bits -= 4;+ //---//+ len = (hold & 0x0f)/*BITS(4)*/ + 8;+ if (state.wbits === 0) {+ state.wbits = len;+ }+ else if (len > state.wbits) {+ strm.msg = 'invalid window size';+ state.mode = BAD;+ break;+ }+ state.dmax = 1 << len;+ //Tracev((stderr, "inflate: zlib header ok\n"));+ strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;+ state.mode = hold & 0x200 ? DICTID : TYPE;+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ break;+ case FLAGS:+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.flags = hold;+ if ((state.flags & 0xff) !== Z_DEFLATED) {+ strm.msg = 'unknown compression method';+ state.mode = BAD;+ break;+ }+ if (state.flags & 0xe000) {+ strm.msg = 'unknown header flags set';+ state.mode = BAD;+ break;+ }+ if (state.head) {+ state.head.text = ((hold >> 8) & 1);+ }+ if (state.flags & 0x0200) {+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = TIME;+ /* falls through */+ case TIME:+ //=== NEEDBITS(32); */+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (state.head) {+ state.head.time = hold;+ }+ if (state.flags & 0x0200) {+ //=== CRC4(state.check, hold)+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ hbuf[2] = (hold >>> 16) & 0xff;+ hbuf[3] = (hold >>> 24) & 0xff;+ state.check = crc32(state.check, hbuf, 4, 0);+ //===+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = OS;+ /* falls through */+ case OS:+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (state.head) {+ state.head.xflags = (hold & 0xff);+ state.head.os = (hold >> 8);+ }+ if (state.flags & 0x0200) {+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = EXLEN;+ /* falls through */+ case EXLEN:+ if (state.flags & 0x0400) {+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.length = hold;+ if (state.head) {+ state.head.extra_len = hold;+ }+ if (state.flags & 0x0200) {+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ }+ else if (state.head) {+ state.head.extra = null/*Z_NULL*/;+ }+ state.mode = EXTRA;+ /* falls through */+ case EXTRA:+ if (state.flags & 0x0400) {+ copy = state.length;+ if (copy > have) { copy = have; }+ if (copy) {+ if (state.head) {+ len = state.head.extra_len - state.length;+ if (!state.head.extra) {+ // Use untyped array for more conveniend processing later+ state.head.extra = new Array(state.head.extra_len);+ }+ utils.arraySet(+ state.head.extra,+ input,+ next,+ // extra field is limited to 65536 bytes+ // - no need for additional size check+ copy,+ /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/+ len+ );+ //zmemcpy(state.head.extra + len, next,+ // len + copy > state.head.extra_max ?+ // state.head.extra_max - len : copy);+ }+ if (state.flags & 0x0200) {+ state.check = crc32(state.check, input, copy, next);+ }+ have -= copy;+ next += copy;+ state.length -= copy;+ }+ if (state.length) { break inf_leave; }+ }+ state.length = 0;+ state.mode = NAME;+ /* falls through */+ case NAME:+ if (state.flags & 0x0800) {+ if (have === 0) { break inf_leave; }+ copy = 0;+ do {+ // TODO: 2 or 1 bytes?+ len = input[next + copy++];+ /* use constant limit because in js we should not preallocate memory */+ if (state.head && len &&+ (state.length < 65536 /*state.head.name_max*/)) {+ state.head.name += String.fromCharCode(len);+ }+ } while (len && copy < have);- this.header = new gzheader();+ if (state.flags & 0x0200) {+ state.check = crc32(state.check, input, copy, next);+ }+ have -= copy;+ next += copy;+ if (len) { break inf_leave; }+ }+ else if (state.head) {+ state.head.name = null;+ }+ state.length = 0;+ state.mode = COMMENT;+ /* falls through */+ case COMMENT:+ if (state.flags & 0x1000) {+ if (have === 0) { break inf_leave; }+ copy = 0;+ do {+ len = input[next + copy++];+ /* use constant limit because in js we should not preallocate memory */+ if (state.head && len &&+ (state.length < 65536 /*state.head.comm_max*/)) {+ state.head.comment += String.fromCharCode(len);+ }+ } while (len && copy < have);+ if (state.flags & 0x0200) {+ state.check = crc32(state.check, input, copy, next);+ }+ have -= copy;+ next += copy;+ if (len) { break inf_leave; }+ }+ else if (state.head) {+ state.head.comment = null;+ }+ state.mode = HCRC;+ /* falls through */+ case HCRC:+ if (state.flags & 0x0200) {+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (hold !== (state.check & 0xffff)) {+ strm.msg = 'header crc mismatch';+ state.mode = BAD;+ break;+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ }+ if (state.head) {+ state.head.hcrc = ((state.flags >> 9) & 1);+ state.head.done = true;+ }+ strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;+ state.mode = TYPE;+ break;+ case DICTID:+ //=== NEEDBITS(32); */+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ strm.adler = state.check = ZSWAP32(hold);+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = DICT;+ /* falls through */+ case DICT:+ if (state.havedict === 0) {+ //--- RESTORE() ---+ strm.next_out = put;+ strm.avail_out = left;+ strm.next_in = next;+ strm.avail_in = have;+ state.hold = hold;+ state.bits = bits;+ //---+ return Z_NEED_DICT;+ }+ strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;+ state.mode = TYPE;+ /* falls through */+ case TYPE:+ if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }+ /* falls through */+ case TYPEDO:+ if (state.last) {+ //--- BYTEBITS() ---//+ hold >>>= bits & 7;+ bits -= bits & 7;+ //---//+ state.mode = CHECK;+ break;+ }+ //=== NEEDBITS(3); */+ while (bits < 3) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.last = (hold & 0x01)/*BITS(1)*/;+ //--- DROPBITS(1) ---//+ hold >>>= 1;+ bits -= 1;+ //---//- zlib_inflate.inflateGetHeader(this.strm, this.header);- };+ switch ((hold & 0x03)/*BITS(2)*/) {+ case 0: /* stored block */+ //Tracev((stderr, "inflate: stored block%s\n",+ // state.last ? " (last)" : ""));+ state.mode = STORED;+ break;+ case 1: /* fixed block */+ fixedtables(state);+ //Tracev((stderr, "inflate: fixed codes block%s\n",+ // state.last ? " (last)" : ""));+ state.mode = LEN_; /* decode codes */+ if (flush === Z_TREES) {+ //--- DROPBITS(2) ---//+ hold >>>= 2;+ bits -= 2;+ //---//+ break inf_leave;+ }+ break;+ case 2: /* dynamic block */+ //Tracev((stderr, "inflate: dynamic codes block%s\n",+ // state.last ? " (last)" : ""));+ state.mode = TABLE;+ break;+ case 3:+ strm.msg = 'invalid block type';+ state.mode = BAD;+ }+ //--- DROPBITS(2) ---//+ hold >>>= 2;+ bits -= 2;+ //---//+ break;+ case STORED:+ //--- BYTEBITS() ---// /* go to byte boundary */+ hold >>>= bits & 7;+ bits -= bits & 7;+ //---//+ //=== NEEDBITS(32); */+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {+ strm.msg = 'invalid stored block lengths';+ state.mode = BAD;+ break;+ }+ state.length = hold & 0xffff;+ //Tracev((stderr, "inflate: stored length %u\n",+ // state.length));+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = COPY_;+ if (flush === Z_TREES) { break inf_leave; }+ /* falls through */+ case COPY_:+ state.mode = COPY;+ /* falls through */+ case COPY:+ copy = state.length;+ if (copy) {+ if (copy > have) { copy = have; }+ if (copy > left) { copy = left; }+ if (copy === 0) { break inf_leave; }+ //--- zmemcpy(put, next, copy); ---+ utils.arraySet(output, input, next, copy, put);+ //---//+ have -= copy;+ next += copy;+ left -= copy;+ put += copy;+ state.length -= copy;+ break;+ }+ //Tracev((stderr, "inflate: stored end\n"));+ state.mode = TYPE;+ break;+ case TABLE:+ //=== NEEDBITS(14); */+ while (bits < 14) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;+ //--- DROPBITS(5) ---//+ hold >>>= 5;+ bits -= 5;+ //---//+ state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;+ //--- DROPBITS(5) ---//+ hold >>>= 5;+ bits -= 5;+ //---//+ state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;+ //--- DROPBITS(4) ---//+ hold >>>= 4;+ bits -= 4;+ //---//+ //#ifndef PKZIP_BUG_WORKAROUND+ if (state.nlen > 286 || state.ndist > 30) {+ strm.msg = 'too many length or distance symbols';+ state.mode = BAD;+ break;+ }+ //#endif+ //Tracev((stderr, "inflate: table sizes ok\n"));+ state.have = 0;+ state.mode = LENLENS;+ /* falls through */+ case LENLENS:+ while (state.have < state.ncode) {+ //=== NEEDBITS(3);+ while (bits < 3) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);+ //--- DROPBITS(3) ---//+ hold >>>= 3;+ bits -= 3;+ //---//+ }+ while (state.have < 19) {+ state.lens[order[state.have++]] = 0;+ }+ // We have separate tables & no pointers. 2 commented lines below not needed.+ //state.next = state.codes;+ //state.lencode = state.next;+ // Switch to use dynamic table+ state.lencode = state.lendyn;+ state.lenbits = 7;- /**- * Inflate#push(data[, mode]) -> Boolean- * - data (Uint8Array|Array|ArrayBuffer|String): input data- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.- *- * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with- * new output chunks. Returns `true` on success. The last data block must have- * mode Z_FINISH (or `true`). That will flush internal pending buffers and call- * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you- * can use mode Z_SYNC_FLUSH, keeping the decompression context.- *- * On fail call [[Inflate#onEnd]] with error code and return false.- *- * We strongly recommend to use `Uint8Array` on input for best speed (output- * format is detected automatically). Also, don't skip last param and always- * use the same type in your code (boolean or number). That will improve JS speed.- *- * For regular `Array`-s make sure all elements are [0..255].- *- * ##### Example- *- * ```javascript- * push(chunk, false); // push one of data chunks- * ...- * push(chunk, true); // push last chunk- * ```- **/- Inflate.prototype.push = function(data, mode) {- var strm = this.strm;- var chunkSize = this.options.chunkSize;- var status, _mode;- var next_out_utf8, tail, utf8str;+ opts = {bits: state.lenbits};+ ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);+ state.lenbits = opts.bits;- // Flag to properly process Z_BUF_ERROR on testing inflate call- // when we check that all output data was flushed.- var allowBufError = false;+ if (ret) {+ strm.msg = 'invalid code lengths set';+ state.mode = BAD;+ break;+ }+ //Tracev((stderr, "inflate: code lengths ok\n"));+ state.have = 0;+ state.mode = CODELENS;+ /* falls through */+ case CODELENS:+ while (state.have < state.nlen + state.ndist) {+ for (;;) {+ here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- if (this.ended) { return false; }- _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);+ if ((here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ if (here_val < 16) {+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ state.lens[state.have++] = here_val;+ }+ else {+ if (here_val === 16) {+ //=== NEEDBITS(here.bits + 2);+ n = here_bits + 2;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ if (state.have === 0) {+ strm.msg = 'invalid bit length repeat';+ state.mode = BAD;+ break;+ }+ len = state.lens[state.have - 1];+ copy = 3 + (hold & 0x03);//BITS(2);+ //--- DROPBITS(2) ---//+ hold >>>= 2;+ bits -= 2;+ //---//+ }+ else if (here_val === 17) {+ //=== NEEDBITS(here.bits + 3);+ n = here_bits + 3;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ len = 0;+ copy = 3 + (hold & 0x07);//BITS(3);+ //--- DROPBITS(3) ---//+ hold >>>= 3;+ bits -= 3;+ //---//+ }+ else {+ //=== NEEDBITS(here.bits + 7);+ n = here_bits + 7;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ len = 0;+ copy = 11 + (hold & 0x7f);//BITS(7);+ //--- DROPBITS(7) ---//+ hold >>>= 7;+ bits -= 7;+ //---//+ }+ if (state.have + copy > state.nlen + state.ndist) {+ strm.msg = 'invalid bit length repeat';+ state.mode = BAD;+ break;+ }+ while (copy--) {+ state.lens[state.have++] = len;+ }+ }+ }- // Convert data if needed- if (typeof data === 'string') {- // Only binary strings can be decompressed on practice- strm.input = strings.binstring2buf(data);- } else if (toString.call(data) === '[object ArrayBuffer]') {- strm.input = new Uint8Array(data);- } else {- strm.input = data;- }+ /* handle error breaks in while */+ if (state.mode === BAD) { break; }- strm.next_in = 0;- strm.avail_in = strm.input.length;+ /* check for end-of-block code (better have one) */+ if (state.lens[256] === 0) {+ strm.msg = 'invalid code -- missing end-of-block';+ state.mode = BAD;+ break;+ }- do {- if (strm.avail_out === 0) {- strm.output = new utils.Buf8(chunkSize);- strm.next_out = 0;- strm.avail_out = chunkSize;- }+ /* build code tables -- note: do not change the lenbits or distbits+ values here (9 and 6) without reading the comments in inftrees.h+ concerning the ENOUGH constants, which depend on those values */+ state.lenbits = 9;- status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */+ opts = {bits: state.lenbits};+ ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);+ // We have separate tables & no pointers. 2 commented lines below not needed.+ // state.next_index = opts.table_index;+ state.lenbits = opts.bits;+ // state.lencode = state.next;- if (status === c.Z_BUF_ERROR && allowBufError === true) {- status = c.Z_OK;- allowBufError = false;- }+ if (ret) {+ strm.msg = 'invalid literal/lengths set';+ state.mode = BAD;+ break;+ }- if (status !== c.Z_STREAM_END && status !== c.Z_OK) {- this.onEnd(status);- this.ended = true;- return false;- }+ state.distbits = 6;+ //state.distcode.copy(state.codes);+ // Switch to use dynamic table+ state.distcode = state.distdyn;+ opts = {bits: state.distbits};+ ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);+ // We have separate tables & no pointers. 2 commented lines below not needed.+ // state.next_index = opts.table_index;+ state.distbits = opts.bits;+ // state.distcode = state.next;- if (strm.next_out) {- if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {+ if (ret) {+ strm.msg = 'invalid distances set';+ state.mode = BAD;+ break;+ }+ //Tracev((stderr, 'inflate: codes ok\n'));+ state.mode = LEN_;+ if (flush === Z_TREES) { break inf_leave; }+ /* falls through */+ case LEN_:+ state.mode = LEN;+ /* falls through */+ case LEN:+ if (have >= 6 && left >= 258) {+ //--- RESTORE() ---+ strm.next_out = put;+ strm.avail_out = left;+ strm.next_in = next;+ strm.avail_in = have;+ state.hold = hold;+ state.bits = bits;+ //---+ inflate_fast(strm, _out);+ //--- LOAD() ---+ put = strm.next_out;+ output = strm.output;+ left = strm.avail_out;+ next = strm.next_in;+ input = strm.input;+ have = strm.avail_in;+ hold = state.hold;+ bits = state.bits;+ //---- if (this.options.to === 'string') {+ if (state.mode === TYPE) {+ state.back = -1;+ }+ break;+ }+ state.back = 0;+ for (;;) {+ here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- next_out_utf8 = strings.utf8border(strm.output, strm.next_out);+ if (here_bits <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ if (here_op && (here_op & 0xf0) === 0) {+ last_bits = here_bits;+ last_op = here_op;+ last_val = here_val;+ for (;;) {+ here = state.lencode[last_val ++ ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- tail = strm.next_out - next_out_utf8;- utf8str = strings.buf2string(strm.output, next_out_utf8);+ if ((last_bits + here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ //--- DROPBITS(last.bits) ---//+ hold >>>= last_bits;+ bits -= last_bits;+ //---//+ state.back += last_bits;+ }+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ state.back += here_bits;+ state.length = here_val;+ if (here_op === 0) {+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?+ // "inflate: literal '%c'\n" :+ // "inflate: literal 0x%02x\n", here.val));+ state.mode = LIT;+ break;+ }+ if (here_op & 32) {+ //Tracevv((stderr, "inflate: end of block\n"));+ state.back = -1;+ state.mode = TYPE;+ break;+ }+ if (here_op & 64) {+ strm.msg = 'invalid literal/length code';+ state.mode = BAD;+ break;+ }+ state.extra = here_op & 15;+ state.mode = LENEXT;+ /* falls through */+ case LENEXT:+ if (state.extra) {+ //=== NEEDBITS(state.extra);+ n = state.extra;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;+ //--- DROPBITS(state.extra) ---//+ hold >>>= state.extra;+ bits -= state.extra;+ //---//+ state.back += state.extra;+ }+ //Tracevv((stderr, "inflate: length %u\n", state.length));+ state.was = state.length;+ state.mode = DIST;+ /* falls through */+ case DIST:+ for (;;) {+ here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- // move tail- strm.next_out = tail;- strm.avail_out = chunkSize - tail;- if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }+ if ((here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ if ((here_op & 0xf0) === 0) {+ last_bits = here_bits;+ last_op = here_op;+ last_val = here_val;+ for (;;) {+ here = state.distcode[last_val ++ ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- this.onData(utf8str);+ if ((last_bits + here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ //--- DROPBITS(last.bits) ---//+ hold >>>= last_bits;+ bits -= last_bits;+ //---//+ state.back += last_bits;+ }+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ state.back += here_bits;+ if (here_op & 64) {+ strm.msg = 'invalid distance code';+ state.mode = BAD;+ break;+ }+ state.offset = here_val;+ state.extra = (here_op) & 15;+ state.mode = DISTEXT;+ /* falls through */+ case DISTEXT:+ if (state.extra) {+ //=== NEEDBITS(state.extra);+ n = state.extra;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;+ //--- DROPBITS(state.extra) ---//+ hold >>>= state.extra;+ bits -= state.extra;+ //---//+ state.back += state.extra;+ }+ //#ifdef INFLATE_STRICT+ if (state.offset > state.dmax) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break;+ }+ //#endif+ //Tracevv((stderr, "inflate: distance %u\n", state.offset));+ state.mode = MATCH;+ /* falls through */+ case MATCH:+ if (left === 0) { break inf_leave; }+ copy = _out - left;+ if (state.offset > copy) { /* copy from window */+ copy = state.offset - copy;+ if (copy > state.whave) {+ if (state.sane) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break;+ }+ // (!) This block is disabled in zlib defailts,+ // don't enable it for binary compatibility+ //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR+ // Trace((stderr, "inflate.c too far\n"));+ // copy -= state.whave;+ // if (copy > state.length) { copy = state.length; }+ // if (copy > left) { copy = left; }+ // left -= copy;+ // state.length -= copy;+ // do {+ // output[put++] = 0;+ // } while (--copy);+ // if (state.length === 0) { state.mode = LEN; }+ // break;+ //#endif+ }+ if (copy > state.wnext) {+ copy -= state.wnext;+ from = state.wsize - copy;+ }+ else {+ from = state.wnext - copy;+ }+ if (copy > state.length) { copy = state.length; }+ from_source = state.window;+ }+ else { /* copy from output */+ from_source = output;+ from = put - state.offset;+ copy = state.length;+ }+ if (copy > left) { copy = left; }+ left -= copy;+ state.length -= copy;+ do {+ output[put++] = from_source[from++];+ } while (--copy);+ if (state.length === 0) { state.mode = LEN; }+ break;+ case LIT:+ if (left === 0) { break inf_leave; }+ output[put++] = state.length;+ left--;+ state.mode = LEN;+ break;+ case CHECK:+ if (state.wrap) {+ //=== NEEDBITS(32);+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ // Use '|' insdead of '+' to make sure that result is signed+ hold |= input[next++] << bits;+ bits += 8;+ }+ //===//+ _out -= left;+ strm.total_out += _out;+ state.total += _out;+ if (_out) {+ strm.adler = state.check =+ /*UPDATE(state.check, put - _out, _out);*/+ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));- } else {- this.onData(utils.shrinkBuf(strm.output, strm.next_out));}+ _out = left;+ // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too+ if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {+ strm.msg = 'incorrect data check';+ state.mode = BAD;+ break;+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ //Tracev((stderr, "inflate: check matches trailer\n"));+ }+ state.mode = LENGTH;+ /* falls through */+ case LENGTH:+ if (state.wrap && state.flags) {+ //=== NEEDBITS(32);+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (hold !== (state.total & 0xffffffff)) {+ strm.msg = 'incorrect length check';+ state.mode = BAD;+ break;+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ //Tracev((stderr, "inflate: length matches trailer\n"));}+ state.mode = DONE;+ /* falls through */+ case DONE:+ ret = Z_STREAM_END;+ break inf_leave;+ case BAD:+ ret = Z_DATA_ERROR;+ break inf_leave;+ case MEM:+ return Z_MEM_ERROR;+ case SYNC:+ /* falls through */+ default:+ return Z_STREAM_ERROR;}+ }- // When no more input data, we should check that internal inflate buffers- // are flushed. The only way to do it when avail_out = 0 - run one more- // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.- // Here we set flag to process this error properly.- //- // NOTE. Deflate does not return error in this case and does not needs such- // logic.- if (strm.avail_in === 0 && strm.avail_out === 0) {- allowBufError = true;- }+ // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);+ /*+ Return from inflate(), updating the total counts and the check value.+ If there was no progress during the inflate() call, return a buffer+ error. Call updatewindow() to create and/or update the window state.+ Note: a memory error from inflate() is non-recoverable.+ */- if (status === c.Z_STREAM_END) {- _mode = c.Z_FINISH;+ //--- RESTORE() ---+ strm.next_out = put;+ strm.avail_out = left;+ strm.next_in = next;+ strm.avail_in = have;+ state.hold = hold;+ state.bits = bits;+ //---++ if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&+ (state.mode < CHECK || flush !== Z_FINISH))) {+ if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {+ state.mode = MEM;+ return Z_MEM_ERROR;+ }+ }+ _in -= strm.avail_in;+ _out -= strm.avail_out;+ strm.total_in += _in;+ strm.total_out += _out;+ state.total += _out;+ if (state.wrap && _out) {+ strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/+ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));+ }+ strm.data_type = state.bits + (state.last ? 64 : 0) ++ (state.mode === TYPE ? 128 : 0) ++ (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);+ if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {+ ret = Z_BUF_ERROR;}+ return ret;+ }- // Finalize on the last chunk.- if (_mode === c.Z_FINISH) {- status = zlib_inflate.inflateEnd(this.strm);- this.onEnd(status);- this.ended = true;- return status === c.Z_OK;+ function inflateEnd(strm) {++ if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {+ return Z_STREAM_ERROR;}- // callback interim results if Z_SYNC_FLUSH.- if (_mode === c.Z_SYNC_FLUSH) {- this.onEnd(c.Z_OK);- strm.avail_out = 0;- return true;+ var state = strm.state;+ if (state.window) {+ state.window = null;}+ strm.state = null;+ return Z_OK;+ }- return true;- };+ function inflateGetHeader(strm, head) {+ var state;+ /* check state */+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;+ if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }- /**- * Inflate#onData(chunk) -> Void- * - chunk (Uint8Array|Array|String): ouput data. Type of array depends- * on js engine support. When string output requested, each chunk- * will be string.- *- * By default, stores data blocks in `chunks[]` property and glue- * those in `onEnd`. Override this handler, if you need another behaviour.- **/- Inflate.prototype.onData = function(chunk) {- this.chunks.push(chunk);- };+ /* save header structure */+ state.head = head;+ head.done = false;+ return Z_OK;+ }- /**- * Inflate#onEnd(status) -> Void- * - status (Number): inflate status. 0 (Z_OK) on success,- * other if not.- *- * Called either after you tell inflate that the input stream is- * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)- * or if an error happened. By default - join collected chunks,- * free memory and fill `results` / `err` properties.- **/- Inflate.prototype.onEnd = function(status) {- // On success - join- if (status === c.Z_OK) {- if (this.options.to === 'string') {- // Glue & convert here, until we teach pako to send- // utf8 alligned strings to onData- this.result = this.chunks.join('');- } else {- this.result = utils.flattenChunks(this.chunks);- }- }- this.chunks = [];- this.err = status;- this.msg = this.strm.msg;- };+ exports.inflateReset = inflateReset;+ exports.inflateReset2 = inflateReset2;+ exports.inflateResetKeep = inflateResetKeep;+ exports.inflateInit = inflateInit;+ exports.inflateInit2 = inflateInit2;+ exports.inflate = inflate;+ exports.inflateEnd = inflateEnd;+ exports.inflateGetHeader = inflateGetHeader;+ exports.inflateInfo = 'pako inflate (from Nodeca project)';+ /* Not implemented+ exports.inflateCopy = inflateCopy;+ exports.inflateGetDictionary = inflateGetDictionary;+ exports.inflateMark = inflateMark;+ exports.inflatePrime = inflatePrime;+ exports.inflateSetDictionary = inflateSetDictionary;+ exports.inflateSync = inflateSync;+ exports.inflateSyncPoint = inflateSyncPoint;+ exports.inflateUndermine = inflateUndermine;+ */- /**- * inflate(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to decompress.- * - options (Object): zlib inflate options.- *- * Decompress `data` with inflate/ungzip and `options`. Autodetect- * format via wrapper header by default. That's why we don't provide- * separate `ungzip` method.- *- * Supported options are:- *- * - windowBits- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information.- *- * Sugar (options):- *- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify- * negative windowBits implicitly.- * - `to` (String) - if equal to 'string', then result will be converted- * from utf8 to utf16 (javascript) string. When string output requested,- * chunk length can differ from `chunkSize`, depending on content.- *- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , input = pako.deflate([1,2,3,4,5,6,7,8,9])- * , output;- *- * try {- * output = pako.inflate(input);- * } catch (err)- * console.log(err);- * }- * ```- **/- function inflate(input, options) {- var inflator = new Inflate(options);-},{"../utils/common":54,"./adler32":56,"./crc32":58,"./inffast":61,"./inftrees":63}],63:[function(require,module,exports){++},{"../utils/common":55,"./adler32":57,"./crc32":59,"./inffast":62,"./inftrees":64}],64:[function(require,module,exports){+ 'use strict';- inflator.push(input, true);- // That will never happens, if you don't cheat with options :)- if (inflator.err) { throw inflator.msg; }+ var utils = require('../utils/common');- return inflator.result;- }+ var MAXBITS = 15;+ var ENOUGH_LENS = 852;+ var ENOUGH_DISTS = 592;+ //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);+ var CODES = 0;+ var LENS = 1;+ var DISTS = 2;- /**- * inflateRaw(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to decompress.- * - options (Object): zlib inflate options.- *- * The same as [[inflate]], but creates raw data, without wrapper- * (header and adler32 crc).- **/- function inflateRaw(input, options) {- options = options || {};- options.raw = true;- return inflate(input, options);- }+ var lbase = [ /* Length codes 257..285 base */+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0+ ];+ var lext = [ /* Length codes 257..285 extra */+ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,+ 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78+ ];- /**- * ungzip(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to decompress.- * - options (Object): zlib inflate options.- *- * Just shortcut to [[inflate]], because it autodetects format- * by header.content. Done for convenience.- **/+ var dbase = [ /* Distance codes 0..29 base */+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,+ 8193, 12289, 16385, 24577, 0, 0+ ];+ var dext = [ /* Distance codes 0..29 extra */+ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,+ 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,+ 28, 28, 29, 29, 64, 64+ ];- exports.Inflate = Inflate;- exports.inflate = inflate;- exports.inflateRaw = inflateRaw;- exports.ungzip = inflate;+ module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)+ {+ var bits = opts.bits;+ //here = opts.here; /* table entry for duplication */- },{"./utils/common":87,"./utils/strings":88,"./zlib/constants":90,"./zlib/gzheader":93,"./zlib/inflate.js":95,"./zlib/messages":97,"./zlib/zstream":99}],87:[function(require,module,exports){- 'use strict';+ var len = 0; /* a code's length in bits */+ var sym = 0; /* index of code symbols */+ var min = 0, max = 0; /* minimum and maximum code lengths */+ var root = 0; /* number of index bits for root table */+ var curr = 0; /* number of index bits for current table */+ var drop = 0; /* code bits to drop for sub-table */+ var left = 0; /* number of prefix codes available */+ var used = 0; /* code entries in table used */+ var huff = 0; /* Huffman code */+ var incr; /* for incrementing code, index */+ var fill; /* index for replicating entries */+ var low; /* low bits for current root entry */+ var mask; /* mask for low root bits */+ var next; /* next available space in table */+ var base = null; /* base value table to use */+ var base_index = 0;+ // var shoextra; /* extra bits table to use */+ var end; /* use base and extra for symbol > end */+ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */+ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */+ var extra = null;+ var extra_index = 0;+ var here_bits, here_op, here_val;- var TYPED_OK = (typeof Uint8Array !== 'undefined') &&- (typeof Uint16Array !== 'undefined') &&- (typeof Int32Array !== 'undefined');+ /*+ Process a set of code lengths to create a canonical Huffman code. The+ code lengths are lens[0..codes-1]. Each length corresponds to the+ symbols 0..codes-1. The Huffman code is generated by first sorting the+ symbols by length from short to long, and retaining the symbol order+ for codes with equal lengths. Then the code starts with all zero bits+ for the first code of the shortest length, and the codes are integer+ increments for the same length, and zeros are appended as the length+ increases. For the deflate format, these bits are stored backwards+ from their more natural integer increment ordering, and so when the+ decoding tables are built in the large loop below, the integer codes+ are incremented backwards.+ This routine assumes, but does not check, that all of the entries in+ lens[] are in the range 0..MAXBITS. The caller must assure this.+ 1..MAXBITS is interpreted as that code length. zero means that that+ symbol does not occur in this code.- exports.assign = function (obj /*from1, from2, from3, ...*/) {- var sources = Array.prototype.slice.call(arguments, 1);- while (sources.length) {- var source = sources.shift();- if (!source) { continue; }+ The codes are sorted by computing a count of codes for each length,+ creating from that a table of starting indices for each length in the+ sorted table, and then entering the symbols in order in the sorted+ table. The sorted table is work[], with that space being provided by+ the caller.- if (typeof source !== 'object') {- throw new TypeError(source + 'must be non-object');- }+ The length counts are used for other purposes as well, i.e. finding+ the minimum and maximum length codes, determining if there are any+ codes at all, checking for a valid set of lengths, and looking ahead+ at length counts to determine sub-table sizes when building the+ decoding tables.+ */- for (var p in source) {- if (source.hasOwnProperty(p)) {- obj[p] = source[p];- }- }+ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */+ for (len = 0; len <= MAXBITS; len++) {+ count[len] = 0;+ }+ for (sym = 0; sym < codes; sym++) {+ count[lens[lens_index + sym]]++;}- return obj;- };--- // reduce buffer size, avoiding mem copy- exports.shrinkBuf = function (buf, size) {- if (buf.length === size) { return buf; }- if (buf.subarray) { return buf.subarray(0, size); }- buf.length = size;- return buf;- };+ /* bound code lengths, force root to be within code lengths */+ root = bits;+ for (max = MAXBITS; max >= 1; max--) {+ if (count[max] !== 0) { break; }+ }+ if (root > max) {+ root = max;+ }+ if (max === 0) { /* no symbols to code at all */+ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */+ //table.bits[opts.table_index] = 1; //here.bits = (var char)1;+ //table.val[opts.table_index++] = 0; //here.val = (var short)0;+ table[table_index++] = (1 << 24) | (64 << 16) | 0;- var fnTyped = {- arraySet: function (dest, src, src_offs, len, dest_offs) {- if (src.subarray && dest.subarray) {- dest.set(src.subarray(src_offs, src_offs+len), dest_offs);- return;- }- // Fallback to ordinary array- for (var i=0; i<len; i++) {- dest[dest_offs + i] = src[src_offs + i];- }- },- // Join array of chunks to single array.- flattenChunks: function(chunks) {- var i, l, len, pos, chunk, result;+ //table.op[opts.table_index] = 64;+ //table.bits[opts.table_index] = 1;+ //table.val[opts.table_index++] = 0;+ table[table_index++] = (1 << 24) | (64 << 16) | 0;- // calculate data length- len = 0;- for (i=0, l=chunks.length; i<l; i++) {- len += chunks[i].length;- }+ opts.bits = 1;+ return 0; /* no symbols, but wait for decoding to report error */+ }+ for (min = 1; min < max; min++) {+ if (count[min] !== 0) { break; }+ }+ if (root < min) {+ root = min;+ }- // join chunks- result = new Uint8Array(len);- pos = 0;- for (i=0, l=chunks.length; i<l; i++) {- chunk = chunks[i];- result.set(chunk, pos);- pos += chunk.length;- }+ /* check for an over-subscribed or incomplete set of lengths */+ left = 1;+ for (len = 1; len <= MAXBITS; len++) {+ left <<= 1;+ left -= count[len];+ if (left < 0) {+ return -1;+ } /* over-subscribed */+ }+ if (left > 0 && (type === CODES || max !== 1)) {+ return -1; /* incomplete set */+ }- return result;+ /* generate offsets into symbol table for each length for sorting */+ offs[1] = 0;+ for (len = 1; len < MAXBITS; len++) {+ offs[len + 1] = offs[len] + count[len];}- };- var fnUntyped = {- arraySet: function (dest, src, src_offs, len, dest_offs) {- for (var i=0; i<len; i++) {- dest[dest_offs + i] = src[src_offs + i];+ /* sort symbols by length, by symbol order within each length */+ for (sym = 0; sym < codes; sym++) {+ if (lens[lens_index + sym] !== 0) {+ work[offs[lens[lens_index + sym]]++] = sym;}- },- // Join array of chunks to single array.- flattenChunks: function(chunks) {- return [].concat.apply([], chunks);}- };+ /*+ Create and fill in decoding tables. In this loop, the table being+ filled is at next and has curr index bits. The code being used is huff+ with length len. That code is converted to an index by dropping drop+ bits off of the bottom. For codes where len is less than drop + curr,+ those top drop + curr - len bits are incremented through all values to+ fill the table with replicated entries.- // Enable/Disable typed arrays use, for testing- //- exports.setTyped = function (on) {- if (on) {- exports.Buf8 = Uint8Array;- exports.Buf16 = Uint16Array;- exports.Buf32 = Int32Array;- exports.assign(exports, fnTyped);- } else {- exports.Buf8 = Array;- exports.Buf16 = Array;- exports.Buf32 = Array;- exports.assign(exports, fnUntyped);- }- };+ root is the number of index bits for the root table. When len exceeds+ root, sub-tables are created pointed to by the root entry with an index+ of the low root bits of huff. This is saved in low to check for when a+ new sub-table should be started. drop is zero when the root table is+ being filled, and drop is root when sub-tables are being filled.- exports.setTyped(TYPED_OK);+ When a new sub-table is needed, it is necessary to look ahead in the+ code lengths to determine what size sub-table is needed. The length+ counts are used for this, and so count[] is decremented as codes are+ entered in the tables.- },{}],88:[function(require,module,exports){- // String encode/decode helpers- 'use strict';+ used keeps track of how many table entries have been allocated from the+ provided *table space. It is checked for LENS and DIST tables against+ the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in+ the initial root table size constants. See the comments in inftrees.h+ for more information.+ sym increments through all symbols, and the loop terminates when+ all codes of length max, i.e. all codes, have been processed. This+ routine permits incomplete codes, so another loop after this one fills+ in the rest of the decoding tables with invalid code markers.+ */- var utils = require('./common');+ /* set up for code type */+ // poor man optimization - use if-else instead of switch,+ // to avoid deopts in old v8+ if (type === CODES) {+ base = extra = work; /* dummy value--not used */+ end = 19;+ } else if (type === LENS) {+ base = lbase;+ base_index -= 257;+ extra = lext;+ extra_index -= 257;+ end = 256;- // Quick check if we can use fast array to bin string conversion- //- // - apply(Array) can fail on Android 2.2- // - apply(Uint8Array) can fail on iOS 5.1 Safary- //- var STR_APPLY_OK = true;- var STR_APPLY_UIA_OK = true;+ } else { /* DISTS */+ base = dbase;+ extra = dext;+ end = -1;+ }- try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }- try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }+ /* initialize opts for loop */+ huff = 0; /* starting code */+ sym = 0; /* starting code symbol */+ len = min; /* starting code length */+ next = table_index; /* current table to fill in */+ curr = root; /* current table index bits */+ drop = 0; /* current bits to drop from code for index */+ low = -1; /* trigger new sub-table when len > root */+ used = 1 << root; /* use root table entries */+ mask = used - 1; /* mask for comparing low */+ /* check available table space */+ if ((type === LENS && used > ENOUGH_LENS) ||+ (type === DISTS && used > ENOUGH_DISTS)) {+ return 1;+ }- // Table with utf8 lengths (calculated by first byte of sequence)- // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,- // because max possible codepoint is 0x10ffff- var _utf8len = new utils.Buf8(256);- for (var q=0; q<256; q++) {- _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);- }- _utf8len[254]=_utf8len[254]=1; // Invalid sequence start+ var i=0;+ /* process all codes and make table entries */+ for (;;) {+ i++;+ /* create table entry */+ here_bits = len - drop;+ if (work[sym] < end) {+ here_op = 0;+ here_val = work[sym];+ }+ else if (work[sym] > end) {+ here_op = extra[extra_index + work[sym]];+ here_val = base[base_index + work[sym]];+ }+ else {+ here_op = 32 + 64; /* end of block */+ here_val = 0;+ }+ /* replicate for those indices with low len bits equal to huff */+ incr = 1 << (len - drop);+ fill = 1 << curr;+ min = fill; /* save offset to next table */+ do {+ fill -= incr;+ table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;+ } while (fill !== 0);- // convert string to array (typed, when possible)- exports.string2buf = function (str) {- var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;+ /* backwards increment the len-bit code huff */+ incr = 1 << (len - 1);+ while (huff & incr) {+ incr >>= 1;+ }+ if (incr !== 0) {+ huff &= incr - 1;+ huff += incr;+ } else {+ huff = 0;+ }- // count binary size- for (m_pos = 0; m_pos < str_len; m_pos++) {- c = str.charCodeAt(m_pos);- if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {- c2 = str.charCodeAt(m_pos+1);- if ((c2 & 0xfc00) === 0xdc00) {- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);- m_pos++;- }+ /* go to next symbol, update count, len */+ sym++;+ if (--count[len] === 0) {+ if (len === max) { break; }+ len = lens[lens_index + work[sym]];}- buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;- }- // allocate buffer- buf = new utils.Buf8(buf_len);+ /* create new sub-table if needed */+ if (len > root && (huff & mask) !== low) {+ /* if first time, transition to sub-tables */+ if (drop === 0) {+ drop = root;+ }- // convert- for (i=0, m_pos = 0; i < buf_len; m_pos++) {- c = str.charCodeAt(m_pos);- if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {- c2 = str.charCodeAt(m_pos+1);- if ((c2 & 0xfc00) === 0xdc00) {- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);- m_pos++;+ /* increment past last table */+ next += min; /* here min is 1 << curr */++ /* determine length of next table */+ curr = len - drop;+ left = 1 << curr;+ while (curr + drop < max) {+ left -= count[curr + drop];+ if (left <= 0) { break; }+ curr++;+ left <<= 1;}- }- if (c < 0x80) {- /* one byte */- buf[i++] = c;- } else if (c < 0x800) {- /* two bytes */- buf[i++] = 0xC0 | (c >>> 6);- buf[i++] = 0x80 | (c & 0x3f);- } else if (c < 0x10000) {- /* three bytes */- buf[i++] = 0xE0 | (c >>> 12);- buf[i++] = 0x80 | (c >>> 6 & 0x3f);- buf[i++] = 0x80 | (c & 0x3f);- } else {- /* four bytes */- buf[i++] = 0xf0 | (c >>> 18);- buf[i++] = 0x80 | (c >>> 12 & 0x3f);- buf[i++] = 0x80 | (c >>> 6 & 0x3f);- buf[i++] = 0x80 | (c & 0x3f);- }- }- return buf;- };+ /* check for enough space */+ used += 1 << curr;+ if ((type === LENS && used > ENOUGH_LENS) ||+ (type === DISTS && used > ENOUGH_DISTS)) {+ return 1;+ }- // Helper (used in 2 places)- function buf2binstring(buf, len) {- // use fallback for big arrays to avoid stack overflow- if (len < 65537) {- if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {- return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));+ /* point entry in root table to sub-table */+ low = huff & mask;+ /*table.op[low] = curr;+ table.bits[low] = root;+ table.val[low] = next - opts.table_index;*/+ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;}}- var result = '';- for (var i=0; i < len; i++) {- result += String.fromCharCode(buf[i]);+ /* fill in remaining table entry if code is incomplete (guaranteed to have+ at most one remaining entry, since if the code is incomplete, the+ maximum code length that was allowed to get this far is one bit) */+ if (huff !== 0) {+ //table.op[next + huff] = 64; /* invalid code marker */+ //table.bits[next + huff] = len - drop;+ //table.val[next + huff] = 0;+ table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;}- return result;- }-- // Convert byte array to binary string- exports.buf2binstring = function(buf) {- return buf2binstring(buf, buf.length);+ /* set return parameters */+ //opts.table_index += used;+ opts.bits = root;+ return 0;};-},{"../utils/common":54}],64:[function(require,module,exports){++},{"../utils/common":55}],65:[function(require,module,exports){+ 'use strict';- // Convert binary string (typed, when possible)- exports.binstring2buf = function(str) {- var buf = new utils.Buf8(str.length);- for (var i=0, len=buf.length; i < len; i++) {- buf[i] = str.charCodeAt(i);- }- return buf;+ module.exports = {+ '2': 'need dictionary', /* Z_NEED_DICT 2 */+ '1': 'stream end', /* Z_STREAM_END 1 */+ '0': '', /* Z_OK 0 */+ '-1': 'file error', /* Z_ERRNO (-1) */+ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */+ '-3': 'data error', /* Z_DATA_ERROR (-3) */+ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */+ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */+ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */};-},{}],65:[function(require,module,exports){++},{}],66:[function(require,module,exports){+ 'use strict';- // convert array to string- exports.buf2string = function (buf, max) {- var i, out, c, c_len;- var len = max || buf.length;- // Reserve max possible length (2 words per char)- // NB: by unknown reasons, Array is significantly faster for- // String.fromCharCode.apply than Uint16Array.- var utf16buf = new Array(len*2);+ var utils = require('../utils/common');- for (out=0, i=0; i<len;) {- c = buf[i++];- // quick process ascii- if (c < 0x80) { utf16buf[out++] = c; continue; }+ /* Public constants ==========================================================*/+ /* ===========================================================================*/- c_len = _utf8len[c];- // skip 5 & 6 byte codes- if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }- // apply mask on first byte- c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;- // join the rest- while (c_len > 1 && i < len) {- c = (c << 6) | (buf[i++] & 0x3f);- c_len--;- }+ //var Z_FILTERED = 1;+ //var Z_HUFFMAN_ONLY = 2;+ //var Z_RLE = 3;+ var Z_FIXED = 4;+ //var Z_DEFAULT_STRATEGY = 0;- // terminated by end of string?- if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }+ /* Possible values of the data_type field (though see inflate()) */+ var Z_BINARY = 0;+ var Z_TEXT = 1;+ //var Z_ASCII = 1; // = Z_TEXT+ var Z_UNKNOWN = 2;- if (c < 0x10000) {- utf16buf[out++] = c;- } else {- c -= 0x10000;- utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);- utf16buf[out++] = 0xdc00 | (c & 0x3ff);- }- }+ /*============================================================================*/- return buf2binstring(utf16buf, out);- };+ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }- // Calculate max possible position in utf8 buffer,- // that will not break sequence. If that's not possible- // - (very small limits) return max size as is.- //- // buf[] - utf8 bytes array- // max - length limit (mandatory);- exports.utf8border = function(buf, max) {- var pos;+ // From zutil.h- max = max || buf.length;- if (max > buf.length) { max = buf.length; }+ var STORED_BLOCK = 0;+ var STATIC_TREES = 1;+ var DYN_TREES = 2;+ /* The three kinds of block type */- // go back from last position, until start of sequence found- pos = max-1;- while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }+ var MIN_MATCH = 3;+ var MAX_MATCH = 258;+ /* The minimum and maximum match lengths */- // Fuckup - very small and broken sequence,- // return max, because we should return something anyway.- if (pos < 0) { return max; }+ // From deflate.h+ /* ===========================================================================+ * Internal compression state.+ */- // If we came to start of buffer - that means vuffer is too small,- // return max too.- if (pos === 0) { return max; }+ var LENGTH_CODES = 29;+ /* number of length codes, not counting the special END_BLOCK code */- return (pos + _utf8len[buf[pos]] > max) ? pos : max;- };+ var LITERALS = 256;+ /* number of literal bytes 0..255 */++ var L_CODES = LITERALS + 1 + LENGTH_CODES;+ /* number of Literal or Length codes, including the END_BLOCK code */++ var D_CODES = 30;+ /* number of distance codes */++ var BL_CODES = 19;+ /* number of codes used to transfer the bit lengths */++ var HEAP_SIZE = 2*L_CODES + 1;+ /* maximum heap size */++ var MAX_BITS = 15;+ /* All codes must not exceed MAX_BITS bits */++ var Buf_size = 16;+ /* size of bit buffer in bi_buf */+++ /* ===========================================================================+ * Constants+ */- },{"./common":87}],89:[function(require,module,exports){- 'use strict';+ var MAX_BL_BITS = 7;+ /* Bit length codes must not exceed MAX_BL_BITS bits */- // Note: adler32 takes 12% for level 0 and 2% for level 6.- // It doesn't worth to make additional optimizationa as in original.- // Small size is preferable.+ var END_BLOCK = 256;+ /* end of block literal code */- function adler32(adler, buf, len, pos) {- var s1 = (adler & 0xffff) |0,- s2 = ((adler >>> 16) & 0xffff) |0,- n = 0;+ var REP_3_6 = 16;+ /* repeat previous bit length 3-6 times (2 bits of repeat count) */- while (len !== 0) {- // Set limit ~ twice less than 5552, to keep- // s2 in 31-bits, because we force signed ints.- // in other case %= will fail.- n = len > 2000 ? 2000 : len;- len -= n;+ var REPZ_3_10 = 17;+ /* repeat a zero length 3-10 times (3 bits of repeat count) */- do {- s1 = (s1 + buf[pos++]) |0;- s2 = (s2 + s1) |0;- } while (--n);+ var REPZ_11_138 = 18;+ /* repeat a zero length 11-138 times (7 bits of repeat count) */- s1 %= 65521;- s2 %= 65521;- }+ var extra_lbits = /* extra bits for each length code */+ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];- return (s1 | (s2 << 16)) |0;- }+ var extra_dbits = /* extra bits for each distance code */+ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];+ var extra_blbits = /* extra bits for each bit length code */+ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];- module.exports = adler32;+ var bl_order =+ [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];+ /* The lengths of the bit length codes are sent in order of decreasing+ * probability, to avoid transmitting the lengths for unused bit length codes.+ */- },{}],90:[function(require,module,exports){- module.exports = {+ /* ===========================================================================+ * Local data. These are initialized only once.+ */- /* Allowed flush values; see deflate() and inflate() below for details */- Z_NO_FLUSH: 0,- Z_PARTIAL_FLUSH: 1,- Z_SYNC_FLUSH: 2,- Z_FULL_FLUSH: 3,- Z_FINISH: 4,- Z_BLOCK: 5,- Z_TREES: 6,+ // We pre-fill arrays with 0 to avoid uninitialized gaps- /* Return codes for the compression/decompression functions. Negative values- * are errors, positive values are used for special but normal events.- */- Z_OK: 0,- Z_STREAM_END: 1,- Z_NEED_DICT: 2,- Z_ERRNO: -1,- Z_STREAM_ERROR: -2,- Z_DATA_ERROR: -3,- //Z_MEM_ERROR: -4,- Z_BUF_ERROR: -5,- //Z_VERSION_ERROR: -6,+ var DIST_CODE_LEN = 512; /* see definition of array dist_code below */- /* compression levels */- Z_NO_COMPRESSION: 0,- Z_BEST_SPEED: 1,- Z_BEST_COMPRESSION: 9,- Z_DEFAULT_COMPRESSION: -1,+ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1+ var static_ltree = new Array((L_CODES+2) * 2);+ zero(static_ltree);+ /* The static literal tree. Since the bit lengths are imposed, there is no+ * need for the L_CODES extra codes used during heap construction. However+ * The codes 286 and 287 are needed to build a canonical tree (see _tr_init+ * below).+ */+ var static_dtree = new Array(D_CODES * 2);+ zero(static_dtree);+ /* The static distance tree. (Actually a trivial tree since all codes use+ * 5 bits.)+ */- Z_FILTERED: 1,- Z_HUFFMAN_ONLY: 2,- Z_RLE: 3,- Z_FIXED: 4,- Z_DEFAULT_STRATEGY: 0,+ var _dist_code = new Array(DIST_CODE_LEN);+ zero(_dist_code);+ /* Distance codes. The first 256 values correspond to the distances+ * 3 .. 258, the last 256 values correspond to the top 8 bits of+ * the 15 bit distances.+ */- /* Possible values of the data_type field (though see inflate()) */- Z_BINARY: 0,- Z_TEXT: 1,- //Z_ASCII: 1, // = Z_TEXT (deprecated)- Z_UNKNOWN: 2,+ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);+ zero(_length_code);+ /* length code for each normalized match length (0 == MIN_MATCH) */- /* The deflate compression method */- Z_DEFLATED: 8- //Z_NULL: null // Use -1 or null inline, depending on var type- };+ var base_length = new Array(LENGTH_CODES);+ zero(base_length);+ /* First normalized length for each code (0 = MIN_MATCH) */- },{}],91:[function(require,module,exports){- 'use strict';+ var base_dist = new Array(D_CODES);+ zero(base_dist);+ /* First normalized distance for each code (0 = distance of 1) */- // Note: we can't get significant speed boost here.- // So write code to minimize size - no pregenerated tables- // and array tools dependencies.+ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {- // Use ordinary array, since untyped makes no boost here- function makeTable() {- var c, table = [];+ this.static_tree = static_tree; /* static tree or NULL */+ this.extra_bits = extra_bits; /* extra bits for each code or NULL */+ this.extra_base = extra_base; /* base index for extra_bits */+ this.elems = elems; /* max number of elements in the tree */+ this.max_length = max_length; /* max bit length for the codes */- for (var n =0; n < 256; n++) {- c = n;- for (var k =0; k < 8; k++) {- c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));- }- table[n] = c;- }+ // show if `static_tree` has data or dummy - needed for monomorphic objects+ this.has_stree = static_tree && static_tree.length;+ };- return table;- }- // Create table on load. Just 255 signed longs. Not a problem.- var crcTable = makeTable();+ var static_l_desc;+ var static_d_desc;+ var static_bl_desc;- function crc32(crc, buf, len, pos) {- var t = crcTable,- end = pos + len;+ var TreeDesc = function(dyn_tree, stat_desc) {+ this.dyn_tree = dyn_tree; /* the dynamic tree */+ this.max_code = 0; /* largest code with non zero frequency */+ this.stat_desc = stat_desc; /* the corresponding static tree */+ };- crc = crc ^ (-1);- for (var i = pos; i < end; i++) {- crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];- }- return (crc ^ (-1)); // >>> 0;+ function d_code(dist) {+ return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];}@@@ -23024,4367 -22232,4445 +22316,4437 @@@ function detect_data_type(s)}+ var static_init_done = false;+/* ===========================================================================- * For Z_RLE, simply look for runs of bytes, generate matches only of distance- * one. Do not maintain a hash table. (It will be regenerated if this run of- * deflate switches away from Z_RLE.)+ * Initialize the tree data structures for a new zlib stream.*/- function deflate_rle(s, flush) {- var bflush; /* set if current block must be flushed */- var prev; /* byte at distance one to match */- var scan, strend; /* scan goes up to strend for length of run */+ function _tr_init(s)+ {- var _win = s.window;+ if (!static_init_done) {+ tr_static_init();+ static_init_done = true;+ }- for (;;) {- /* Make sure that we always have enough lookahead, except- * at the end of the input file. We need MAX_MATCH bytes- * for the longest run, plus one for the unrolled loop.- */- if (s.lookahead <= MAX_MATCH) {- fill_window(s);- if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }- if (s.lookahead === 0) { break; } /* flush the current block */- }+ s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);+ s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);+ s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);- /* See how many times the previous byte repeats */- s.match_length = 0;- if (s.lookahead >= MIN_MATCH && s.strstart > 0) {- scan = s.strstart - 1;- prev = _win[scan];- if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {- strend = s.strstart + MAX_MATCH;- do {- /*jshint noempty:false*/- } while (prev === _win[++scan] && prev === _win[++scan] &&- prev === _win[++scan] && prev === _win[++scan] &&- prev === _win[++scan] && prev === _win[++scan] &&- prev === _win[++scan] && prev === _win[++scan] &&- scan < strend);- s.match_length = MAX_MATCH - (strend - scan);- if (s.match_length > s.lookahead) {- s.match_length = s.lookahead;- }- }- //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");- }+ s.bi_buf = 0;+ s.bi_valid = 0;- /* Emit match if have run of MIN_MATCH or longer, else emit literal */- if (s.match_length >= MIN_MATCH) {- //check_match(s, s.strstart, s.strstart - 1, s.match_length);+ /* Initialize the first block of the first file: */+ init_block(s);+ }- /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/- bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);- s.lookahead -= s.match_length;- s.strstart += s.match_length;- s.match_length = 0;- } else {- /* No match, output a literal byte */- //Tracevv((stderr,"%c", s->window[s->strstart]));- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);+ /* ===========================================================================+ * Send a stored block+ */+ function _tr_stored_block(s, buf, stored_len, last)+ //DeflateState *s;+ //charf *buf; /* input block */+ //ulg stored_len; /* length of input block */+ //int last; /* one if this is the last block for a file */+ {+ send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */+ copy_block(s, buf, stored_len, true); /* with header */+ }- s.lookahead--;- s.strstart++;- }- if (bflush) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/- }- }- s.insert = 0;- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;- }- /***/- return BS_FINISH_DONE;- }- if (s.last_lit) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/- }- return BS_BLOCK_DONE;++ /* ===========================================================================+ * Send one empty static block to give enough lookahead for inflate.+ * This takes 10 bits, of which 7 may remain in the bit buffer.+ */+ function _tr_align(s) {+ send_bits(s, STATIC_TREES<<1, 3);+ send_code(s, END_BLOCK, static_ltree);+ bi_flush(s);}+/* ===========================================================================- * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.- * (It will be regenerated if this run of deflate switches away from Huffman.)+ * Determine the best encoding for the current block: dynamic trees, static+ * trees or store, and output the encoded block to the zip file.*/- function deflate_huff(s, flush) {- var bflush; /* set if current block must be flushed */+ function _tr_flush_block(s, buf, stored_len, last)+ //DeflateState *s;+ //charf *buf; /* input block, or NULL if too old */+ //ulg stored_len; /* length of input block */+ //int last; /* one if this is the last block for a file */+ {+ var opt_lenb, static_lenb; /* opt_len and static_len in bytes */+ var max_blindex = 0; /* index of last bit length code of non zero freq */- for (;;) {- /* Make sure that we have a literal to write. */- if (s.lookahead === 0) {- fill_window(s);- if (s.lookahead === 0) {- if (flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }- break; /* flush the current block */- }- }+ /* Build the Huffman trees unless a stored block is forced */+ if (s.level > 0) {- /* Output a literal byte */- s.match_length = 0;- //Tracevv((stderr,"%c", s->window[s->strstart]));- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);- s.lookahead--;- s.strstart++;- if (bflush) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/+ /* Check if the file is binary or text */+ if (s.strm.data_type === Z_UNKNOWN) {+ s.strm.data_type = detect_data_type(s);}++ /* Construct the literal and distance trees */+ build_tree(s, s.l_desc);+ // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,+ // s->static_len));++ build_tree(s, s.d_desc);+ // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,+ // s->static_len));+ /* At this point, opt_len and static_len are the total bit lengths of+ * the compressed block data, excluding the tree representations.+ */++ /* Build the bit length tree for the above two trees, and get the index+ * in bl_order of the last bit length code to send.+ */+ max_blindex = build_bl_tree(s);++ /* Determine the best encoding. Compute the block lengths in bytes. */+ opt_lenb = (s.opt_len+3+7) >>> 3;+ static_lenb = (s.static_len+3+7) >>> 3;++ // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",+ // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,+ // s->last_lit));++ if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }++ } else {+ // Assert(buf != (char*)0, "lost buf");+ opt_lenb = static_lenb = stored_len + 5; /* force a stored block */}- s.insert = 0;- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;- }- /***/- return BS_FINISH_DONE;++ if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {+ /* 4: two words for the lengths */++ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.+ * Otherwise we can't have processed more than WSIZE input bytes since+ * the last block flush, because compression would have been+ * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to+ * transform a block into a stored block.+ */+ _tr_stored_block(s, buf, stored_len, last);++ } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {++ send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);+ compress_block(s, static_ltree, static_dtree);++ } else {+ send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);+ send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);+ compress_block(s, s.dyn_ltree, s.dyn_dtree);}- if (s.last_lit) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/+ // Assert (s->compressed_len == s->bits_sent, "bad compressed size");+ /* The above check is made mod 2^32, for files larger than 512 MB+ * and uLong implemented on 32 bits.+ */+ init_block(s);++ if (last) {+ bi_windup(s);}- return BS_BLOCK_DONE;+ // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,+ // s->compressed_len-7*last));}- /* Values for max_lazy_match, good_match and max_chain_length, depending on- * the desired pack level (0..9). The values given below have been tuned to- * exclude worst case performance for pathological files. Better values may be- * found for specific files.+ /* ===========================================================================+ * Save the match info and tally the frequency counts. Return true if+ * the current block must be flushed.*/- var Config = function (good_length, max_lazy, nice_length, max_chain, func) {- this.good_length = good_length;- this.max_lazy = max_lazy;- this.nice_length = nice_length;- this.max_chain = max_chain;- this.func = func;- };+ function _tr_tally(s, dist, lc)+ // deflate_state *s;+ // unsigned dist; /* distance of matched string */+ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */+ {+ //var out_length, in_length, dcode;- var configuration_table;+ s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;+ s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;- configuration_table = [- /* good lazy nice chain */- new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */- new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */- new Config(4, 5, 16, 8, deflate_fast), /* 2 */- new Config(4, 6, 32, 32, deflate_fast), /* 3 */+ s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;+ s.last_lit++;- new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */- new Config(8, 16, 32, 32, deflate_slow), /* 5 */- new Config(8, 16, 128, 128, deflate_slow), /* 6 */- new Config(8, 32, 128, 256, deflate_slow), /* 7 */- new Config(32, 128, 258, 1024, deflate_slow), /* 8 */- new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */- ];+ if (dist === 0) {+ /* lc is the unmatched char */+ s.dyn_ltree[lc*2]/*.Freq*/++;+ } else {+ s.matches++;+ /* Here, lc is the match length - MIN_MATCH */+ dist--; /* dist = match distance - 1 */+ //Assert((ush)dist < (ush)MAX_DIST(s) &&+ // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&+ // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");+ s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;+ s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;+ }- /* ===========================================================================- * Initialize the "longest match" routines for a new zlib stream- */- function lm_init(s) {- s.window_size = 2 * s.w_size;+ // (!) This block is disabled in zlib defailts,+ // don't enable it for binary compatibility- /*** CLEAR_HASH(s); ***/- zero(s.head); // Fill with NIL (= 0);+ //#ifdef TRUNCATE_BLOCK+ // /* Try to guess if it is profitable to stop the current block here */+ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {+ // /* Compute an upper bound for the compressed length */+ // out_length = s.last_lit*8;+ // in_length = s.strstart - s.block_start;+ //+ // for (dcode = 0; dcode < D_CODES; dcode++) {+ // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);+ // }+ // out_length >>>= 3;+ // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",+ // // s->last_lit, in_length, out_length,+ // // 100L - out_length*100L/in_length));+ // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {+ // return true;+ // }+ // }+ //#endif- /* Set the default configuration parameters:+ return (s.last_lit === s.lit_bufsize-1);+ /* We avoid equality with lit_bufsize because of wraparound at 64K+ * on 16 bit machines and because stored blocks are restricted to+ * 64K-1 bytes.*/- s.max_lazy_match = configuration_table[s.level].max_lazy;- s.good_match = configuration_table[s.level].good_length;- s.nice_match = configuration_table[s.level].nice_length;- s.max_chain_length = configuration_table[s.level].max_chain;+ }- s.strstart = 0;- s.block_start = 0;- s.lookahead = 0;- s.insert = 0;- s.match_length = s.prev_length = MIN_MATCH - 1;- s.match_available = 0;- s.ins_h = 0;+ exports._tr_init = _tr_init;+ exports._tr_stored_block = _tr_stored_block;+ exports._tr_flush_block = _tr_flush_block;+ exports._tr_tally = _tr_tally;+ exports._tr_align = _tr_align;+-},{"../utils/common":54}],66:[function(require,module,exports){++},{"../utils/common":55}],67:[function(require,module,exports){+ 'use strict';+++ function ZStream() {+ /* next input byte */+ this.input = null; // JS specific, because we have no pointers+ this.next_in = 0;+ /* number of bytes available at input */+ this.avail_in = 0;+ /* total number of input bytes read so far */+ this.total_in = 0;+ /* next output byte should be put there */+ this.output = null; // JS specific, because we have no pointers+ this.next_out = 0;+ /* remaining free space at output */+ this.avail_out = 0;+ /* total number of bytes output so far */+ this.total_out = 0;+ /* last error message, NULL if no error */+ this.msg = ''/*Z_NULL*/;+ /* not visible by applications */+ this.state = null;+ /* best guess about the data type: binary or text */+ this.data_type = 2/*Z_UNKNOWN*/;+ /* adler32 value of the uncompressed data */+ this.adler = 0;}+ module.exports = ZStream;- function DeflateState() {- this.strm = null; /* pointer back to this zlib stream */- this.status = 0; /* as the name implies */- this.pending_buf = null; /* output still pending */- this.pending_buf_size = 0; /* size of pending_buf */- this.pending_out = 0; /* next pending byte to output to the stream */- this.pending = 0; /* nb of bytes in the pending buffer */- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */- this.gzhead = null; /* gzip header information to write */- this.gzindex = 0; /* where in extra, name, or comment */- this.method = Z_DEFLATED; /* can only be DEFLATED */- this.last_flush = -1; /* value of flush param for previous deflate call */-},{}],67:[function(require,module,exports){++},{}],68:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ */- this.w_size = 0; /* LZ77 window size (32K by default) */- this.w_bits = 0; /* log2(w_size) (8..16) */- this.w_mask = 0; /* w_size - 1 */+ module.exports = function arrayEquals(array) {+ // if the other array is a falsy value, return+ if (!array)+ return false;- this.window = null;- /* Sliding window. Input bytes are read into the second half of the window,- * and move to the first half later to keep a dictionary of at least wSize- * bytes. With this organization, matches are limited to a distance of- * wSize-MAX_MATCH bytes, but this ensures that IO is always- * performed with a length multiple of the block size.- */+ // compare lengths - can save a lot of time+ if (this.length != array.length)+ return false;- this.window_size = 0;- /* Actual size of window: 2*wSize, except when the user input buffer- * is directly used as sliding window.- */+ for (var i = 0, l = this.length; i < l; i++) {+ // Check if we have nested arrays+ if (this[i] instanceof Array && array[i] instanceof Array) {+ // recurse into the nested arrays+ if (!arrayEquals.apply(this[i], [array[i]]))+ return false;+ } else if (this[i] != array[i]) {+ // Warning - two different object instances will never be equal:+ // {x:20} != {x:20}+ return false;+ }+ }+ return true;+ };- this.prev = null;- /* Link to older string with same hash index. To limit the size of this- * array to 64K, this link is maintained only for the last 32K strings.- * An index in this array is thus a window index modulo 32K.- */- this.head = null; /* Heads of the hash chains or NIL. */-},{}],68:[function(require,module,exports){++},{}],69:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ */- this.ins_h = 0; /* hash index of string to be inserted */- this.hash_size = 0; /* number of elements in hash table */- this.hash_bits = 0; /* log2(hash_size) */- this.hash_mask = 0; /* hash_size-1 */+ exports.Interop = require('./interop');+-},{"./interop":69}],69:[function(require,module,exports){++},{"./interop":70}],70:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ */++ /* global RTCSessionDescription */+ /* jshint -W097 */+ "use strict";- this.hash_shift = 0;- /* Number of bits by which ins_h must be shifted at each input- * step. It must be such that after MIN_MATCH steps, the oldest- * byte no longer takes part in the hash key, that is:- * hash_shift * MIN_MATCH >= hash_bits- */+ var transform = require('./transform');+ var arrayEquals = require('./array-equals');- this.block_start = 0;- /* Window position at the beginning of the current output block. Gets- * negative when the window is moved backwards.- */+ function Interop() {- this.match_length = 0; /* length of best match */- this.prev_match = 0; /* previous match */- this.match_available = 0; /* set if previous match exists */- this.strstart = 0; /* start of string to insert */- this.match_start = 0; /* start of matching string */- this.lookahead = 0; /* number of valid bytes ahead in window */+ /**+ * This map holds the most recent Unified Plan offer/answer SDP that was+ * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and+ * the SDP string as values.+ *+ * @type {{}}+ */+ this.cache = {};+ }- this.prev_length = 0;- /* Length of the best match at previous step. Matches not greater than this- * are discarded. This is used in the lazy match evaluation.- */+ module.exports = Interop;- this.max_chain_length = 0;- /* To speed up deflation, hash chains are never searched beyond this- * length. A higher limit improves compression ratio but degrades the- * speed.- */+ /**+ * Returns the index of the first m-line with the given media type and with a+ * direction which allows sending, in the last Unified Plan description with+ * type "answer" converted to Plan B. Returns {null} if there is no saved+ * answer, or if none of its m-lines with the given type allow sending.+ * @param type the media type ("audio" or "video").+ * @returns {*}+ */+ Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {+ if (!this.cache.answer) {+ return null;+ }- this.max_lazy_match = 0;- /* Attempt to find a better match only when the current match is strictly- * smaller than this value. This mechanism is used only for compression- * levels >= 4.- */- // That's alias to max_lazy_match, don't use directly- //this.max_insert_length = 0;- /* Insert new strings in the hash table only if the match length is not- * greater than this length. This saves time but degrades compression.- * max_insert_length is used only for compression levels <= 3.- */+ var session = transform.parse(this.cache.answer);+ if (session && session.media && Array.isArray(session.media)){+ for (var i = 0; i < session.media.length; i++) {+ if (session.media[i].type == type &&+ (!session.media[i].direction /* default to sendrecv */ ||+ session.media[i].direction === 'sendrecv' ||+ session.media[i].direction === 'sendonly')){+ return i;+ }+ }+ }- this.level = 0; /* compression level (1..9) */- this.strategy = 0; /* favor or force Huffman coding*/+ return null;+ };- this.good_match = 0;- /* Use a faster search when the previous match is longer than this */+ /**+ * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A+ * PeerConnection wrapper transforms the SDP to Plan B before passing it to the+ * application.+ *+ * @param desc+ * @returns {*}+ */+ Interop.prototype.toPlanB = function(desc) {+ var self = this;+ //#region Preliminary input validation.- this.nice_match = 0; /* Stop searching when current match exceeds this */+ if (typeof desc !== 'object' || desc === null ||+ typeof desc.sdp !== 'string') {+ console.warn('An empty description was passed as an argument.');+ return desc;+ }- /* used by trees.c: */+ // Objectify the SDP for easier manipulation.+ var session = transform.parse(desc.sdp);- /* Didn't use ct_data typedef below to suppress compiler warning */+ // If the SDP contains no media, there's nothing to transform.+ if (typeof session.media === 'undefined' ||+ !Array.isArray(session.media) || session.media.length === 0) {+ console.warn('The description has no media.');+ return desc;+ }- // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */- // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */- // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */+ // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B+ // SDP has a video, an audio and a data "channel" at most.+ if (session.media.length <= 3 && session.media.every(function(m) {+ return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;+ })) {+ console.warn('This description does not look like Unified Plan.');+ return desc;+ }- // Use flat array of DOUBLE size, with interleaved fata,- // because JS does not support effective- this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);- this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);- this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);- zero(this.dyn_ltree);- zero(this.dyn_dtree);- zero(this.bl_tree);+ //#endregion- this.l_desc = null; /* desc. for literal tree */- this.d_desc = null; /* desc. for distance tree */- this.bl_desc = null; /* desc. for bit length tree */+ // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443+ var sdp = desc.sdp;+ var rewrite = false;+ for (var i = 0; i < session.media.length; i++) {+ var uLine = session.media[i];+ uLine.rtp.forEach(function(rtp) {+ if (rtp.codec === 'NULL')+ {+ rewrite = true;+ var offer = transform.parse(self.cache['offer']);+ rtp.codec = offer.media[i].rtp[0].codec;+ }+ });+ };+ if (rewrite) {+ sdp = transform.write(session);+ }- //ush bl_count[MAX_BITS+1];- this.bl_count = new utils.Buf16(MAX_BITS+1);- /* number of codes at each bit length for an optimal tree */+ // Unified Plan SDP is our "precious". Cache it for later use in the Plan B+ // -> Unified Plan transformation.+ this.cache[desc.type] = sdp;- //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */- this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */- zero(this.heap);+ //#region Convert from Unified Plan to Plan B.- this.heap_len = 0; /* number of elements in the heap */- this.heap_max = 0; /* element of largest frequency */- /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.- * The same heap array is used to build all trees.- */+ // We rebuild the session.media array.+ var media = session.media;+ session.media = [];- this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];- zero(this.depth);- /* Depth of each subtree used as tie breaker for trees of equal frequency- */+ // Associative array that maps channel types to channel objects for fast+ // access to channel objects by their type, e.g. type2bl['audio']->channel+ // obj.+ var type2bl = {};- this.l_buf = 0; /* buffer index for literals or lengths */+ // Used to build the group:BUNDLE value after the channels construction+ // loop.+ var types = [];- this.lit_bufsize = 0;- /* Size of match buffer for literals/lengths. There are 4 reasons for- * limiting lit_bufsize to 64K:- * - frequencies can be kept in 16 bit counters- * - if compression is not successful for the first block, all input- * data is still in the window so we can still emit a stored block even- * when input comes from standard input. (This can also be done for- * all blocks if lit_bufsize is not greater than 32K.)- * - if compression is not successful for a file smaller than 64K, we can- * even emit a stored file instead of a stored block (saving 5 bytes).- * This is applicable only for zip (not gzip or zlib).- * - creating new Huffman trees less frequently may not provide fast- * adaptation to changes in the input data statistics. (Take for- * example a binary file with poorly compressible code followed by- * a highly compressible string table.) Smaller buffer sizes give- * fast adaptation but have of course the overhead of transmitting- * trees more frequently.- * - I can't count above 4- */+ // Implode the Unified Plan m-lines/tracks into Plan B channels.+ media.forEach(function(uLine) {- this.last_lit = 0; /* running index in l_buf */+ // rtcp-mux is required in the Plan B SDP.+ if ((typeof uLine.rtcpMux !== 'string' ||+ uLine.rtcpMux !== 'rtcp-mux') &&+ uLine.direction !== 'inactive') {+ throw new Error('Cannot convert to Plan B because m-lines ' ++ 'without the rtcp-mux attribute were found.');+ }- this.d_buf = 0;- /* Buffer index for distances. To simplify the code, d_buf and l_buf have- * the same number of elements. To use different lengths, an extra flag- * array would be necessary.- */+ if (uLine.type === 'application') {+ session.media.push(uLine);+ types.push(uLine.mid);+ return;+ }- this.opt_len = 0; /* bit length of current block with optimal trees */- this.static_len = 0; /* bit length of current block with static trees */- this.matches = 0; /* number of string matches in current block */- this.insert = 0; /* bytes at end of window left to insert */+ // If we don't have a channel for this uLine.type, then use this+ // uLine as the channel basis.+ if (typeof type2bl[uLine.type] === 'undefined') {+ type2bl[uLine.type] = uLine;+ }+ // Add sources to the channel and handle a=msid.+ if (typeof uLine.sources === 'object') {+ Object.keys(uLine.sources).forEach(function(ssrc) {+ if (typeof type2bl[uLine.type].sources !== 'object')+ type2bl[uLine.type].sources = {};- this.bi_buf = 0;- /* Output buffer. bits are inserted starting at the bottom (least- * significant bits).- */- this.bi_valid = 0;- /* Number of valid bits in bi_buf. All bits above the last valid bit- * are always zero.- */+ // Assign the sources to the channel.+ type2bl[uLine.type].sources[ssrc] =+ uLine.sources[ssrc];++ if (typeof uLine.msid !== 'undefined') {+ // In Plan B the msid is an SSRC attribute. Also, we don't+ // care about the obsolete label and mslabel attributes.+ //+ // Note that it is not guaranteed that the uLine will+ // have an msid. recvonly channels in particular don't have+ // one.+ type2bl[uLine.type].sources[ssrc].msid =+ uLine.msid;+ }+ // NOTE ssrcs in ssrc groups will share msids, as+ // draft-uberti-rtcweb-plan-00 mandates.+ });+ }- // Used for window memory init. We safely ignore it for JS. That makes- // sense only for pointers and memory check tools.- //this.high_water = 0;- /* High water mark offset in window for initialized bytes -- bytes above- * this are set to zero in order to avoid memory check warnings when- * longest match routines access bytes past the input. This is then- * updated to the new high water mark.- */- }+ // Add ssrc groups to the channel.+ if (typeof uLine.ssrcGroups !== 'undefined' &&+ Array.isArray(uLine.ssrcGroups)) {+ // Create the ssrcGroups array, if it's not defined.+ if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||+ !Array.isArray(type2bl[uLine.type].ssrcGroups)) {+ type2bl[uLine.type].ssrcGroups = [];+ }- function deflateResetKeep(strm) {- var s;+ type2bl[uLine.type].ssrcGroups =+ type2bl[uLine.type].ssrcGroups.concat(+ uLine.ssrcGroups);+ }- if (!strm || !strm.state) {- return err(strm, Z_STREAM_ERROR);- }+ if (type2bl[uLine.type] === uLine) {+ // Copy ICE related stuff from the principal media line.+ uLine.candidates = media[0].candidates;+ uLine.iceUfrag = media[0].iceUfrag;+ uLine.icePwd = media[0].icePwd;+ uLine.fingerprint = media[0].fingerprint;- strm.total_in = strm.total_out = 0;- strm.data_type = Z_UNKNOWN;+ // Plan B mids are in ['audio', 'video', 'data']+ uLine.mid = uLine.type;- s = strm.state;- s.pending = 0;- s.pending_out = 0;+ // Plan B doesn't support/need the bundle-only attribute.+ delete uLine.bundleOnly;- if (s.wrap < 0) {- s.wrap = -s.wrap;- /* was made negative by deflate(..., Z_FINISH); */- }- s.status = (s.wrap ? INIT_STATE : BUSY_STATE);- strm.adler = (s.wrap === 2) ?- 0 // crc32(0, Z_NULL, 0)- :- 1; // adler32(0, Z_NULL, 0)- s.last_flush = Z_NO_FLUSH;- trees._tr_init(s);- return Z_OK;- }+ // In Plan B the msid is an SSRC attribute.+ delete uLine.msid;+ // Used to build the group:BUNDLE value after this loop.+ types.push(uLine.type);- function deflateReset(strm) {- var ret = deflateResetKeep(strm);- if (ret === Z_OK) {- lm_init(strm.state);- }- return ret;- }+ // Add the channel to the new media array.+ session.media.push(uLine);+ }+ });+ // We regenerate the BUNDLE group with the new mids.+ session.groups.some(function(group) {+ if (group.type === 'BUNDLE') {+ group.mids = types.join(' ');+ return true;+ }+ });- function deflateSetHeader(strm, head) {- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }- strm.state.gzhead = head;- return Z_OK;- }+ // msid semantic+ session.msidSemantic = {+ semantic: 'WMS',+ token: '*'+ };+ var resStr = transform.write(session);- function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {- if (!strm) { // === Z_NULL- return Z_STREAM_ERROR;- }- var wrap = 1;+ return new RTCSessionDescription({+ type: desc.type,+ sdp: resStr+ });- if (level === Z_DEFAULT_COMPRESSION) {- level = 6;- }+ //#endregion+ };- if (windowBits < 0) { /* suppress zlib wrapper */- wrap = 0;- windowBits = -windowBits;- }+ /**+ * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A+ * PeerConnection wrapper transforms the SDP to Unified Plan before passing it+ * to FF.+ *+ * @param desc+ * @returns {*}+ */+ Interop.prototype.toUnifiedPlan = function(desc) {+ var self = this;+ //#region Preliminary input validation.- else if (windowBits > 15) {- wrap = 2; /* write gzip wrapper instead */- windowBits -= 16;- }+ if (typeof desc !== 'object' || desc === null ||+ typeof desc.sdp !== 'string') {+ console.warn('An empty description was passed as an argument.');+ return desc;+ }+ var session = transform.parse(desc.sdp);- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||- windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||- strategy < 0 || strategy > Z_FIXED) {- return err(strm, Z_STREAM_ERROR);- }+ // If the SDP contains no media, there's nothing to transform.+ if (typeof session.media === 'undefined' ||+ !Array.isArray(session.media) || session.media.length === 0) {+ console.warn('The description has no media.');+ return desc;+ }+ // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has+ // a video, an audio and a data "channel" at most.+ if (session.media.length > 3 || !session.media.every(function(m) {+ return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;+ })) {+ console.warn('This description does not look like Plan B.');+ return desc;+ }- if (windowBits === 8) {- windowBits = 9;- }- /* until 256-byte window bug fixed */+ // Make sure this Plan B SDP can be converted to a Unified Plan SDP.+ var mids = [];+ session.media.forEach(function(m) {+ mids.push(m.mid);+ });- var s = new DeflateState();+ var hasBundle = false;+ if (typeof session.groups !== 'undefined' &&+ Array.isArray(session.groups)) {+ hasBundle = session.groups.every(function(g) {+ return g.type !== 'BUNDLE' ||+ arrayEquals.apply(g.mids.sort(), [mids.sort()]);+ });+ }- strm.state = s;- s.strm = strm;+ if (!hasBundle) {+ throw new Error("Cannot convert to Unified Plan because m-lines that" ++ " are not bundled were found.");+ }- s.wrap = wrap;- s.gzhead = null;- s.w_bits = windowBits;- s.w_size = 1 << s.w_bits;- s.w_mask = s.w_size - 1;+ //#endregion- s.hash_bits = memLevel + 7;- s.hash_size = 1 << s.hash_bits;- s.hash_mask = s.hash_size - 1;- s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);- s.window = new utils.Buf8(s.w_size * 2);- s.head = new utils.Buf16(s.hash_size);- s.prev = new utils.Buf16(s.w_size);+ //#region Convert from Plan B to Unified Plan.- // Don't need mem init magic for JS.- //s.high_water = 0; /* nothing written to s->window yet */+ // Unfortunately, a Plan B offer/answer doesn't have enough information to+ // rebuild an equivalent Unified Plan offer/answer.+ //+ // For example, if this is a local answer (in Unified Plan style) that we+ // convert to Plan B prior to handing it over to the application (the+ // PeerConnection wrapper called us, for instance, after a successful+ // createAnswer), we want to remember the m-line at which we've seen the+ // (local) SSRC. That's because when the application wants to do call the+ // SLD method, forcing us to do the inverse transformation (from Plan B to+ // Unified Plan), we need to know to which m-line to assign the (local)+ // SSRC. We also need to know all the other m-lines that the original+ // answer had and include them in the transformed answer as well.+ //+ // Another example is if this is a remote offer that we convert to Plan B+ // prior to giving it to the application, we want to remember the mid at+ // which we've seen the (remote) SSRC.+ //+ // In the iteration that follows, we use the cached Unified Plan (if it+ // exists) to assign mids to ssrcs.- s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */+ var cached;+ if (typeof this.cache[desc.type] !== 'undefined') {+ cached = transform.parse(this.cache[desc.type]);+ }- s.pending_buf_size = s.lit_bufsize * 4;- s.pending_buf = new utils.Buf8(s.pending_buf_size);+ var recvonlySsrcs = {+ audio: {},+ video: {}+ };- s.d_buf = s.lit_bufsize >> 1;- s.l_buf = (1 + 2) * s.lit_bufsize;+ // A helper map that sends mids to m-line objects. We use it later to+ // rebuild the Unified Plan style session.media array.+ var mid2ul = {};+ session.media.forEach(function(bLine) {+ if ((typeof bLine.rtcpMux !== 'string' ||+ bLine.rtcpMux !== 'rtcp-mux') &&+ bLine.direction !== 'inactive') {+ throw new Error("Cannot convert to Unified Plan because m-lines " ++ "without the rtcp-mux attribute were found.");+ }- s.level = level;- s.strategy = strategy;- s.method = method;+ if (bLine.type === 'application') {+ mid2ul[bLine.mid] = bLine;+ return;+ }++ // With rtcp-mux and bundle all the channels should have the same ICE+ // stuff.+ var sources = bLine.sources;+ var ssrcGroups = bLine.ssrcGroups;+ var candidates = bLine.candidates;+ var iceUfrag = bLine.iceUfrag;+ var icePwd = bLine.icePwd;+ var fingerprint = bLine.fingerprint;+ var port = bLine.port;++ // We'll use the "bLine" object as a prototype for each new "mLine"+ // that we create, but first we need to clean it up a bit.+ delete bLine.sources;+ delete bLine.ssrcGroups;+ delete bLine.candidates;+ delete bLine.iceUfrag;+ delete bLine.icePwd;+ delete bLine.fingerprint;+ delete bLine.port;+ delete bLine.mid;- return deflateReset(strm);- }+ // inverted ssrc group map+ var ssrc2group = {};+ if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {+ ssrcGroups.forEach(function (ssrcGroup) {- function deflateInit(strm, level) {- return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);- }+ // TODO(gp) find out how to receive simulcast with FF. For the+ // time being, hide it.+ if (ssrcGroup.semantics === 'SIM') {+ return;+ }+ // XXX This might brake if an SSRC is in more than one group+ // for some reason.+ if (typeof ssrcGroup.ssrcs !== 'undefined' &&+ Array.isArray(ssrcGroup.ssrcs)) {+ ssrcGroup.ssrcs.forEach(function (ssrc) {+ if (typeof ssrc2group[ssrc] === 'undefined') {+ ssrc2group[ssrc] = [];+ }- function deflate(strm, flush) {- var old_flush, s;- var beg, val; // for gzip header write only+ ssrc2group[ssrc].push(ssrcGroup);+ });+ }+ });+ }- if (!strm || !strm.state ||- flush > Z_BLOCK || flush < 0) {- return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;- }+ // ssrc to m-line index.+ var ssrc2ml = {};- s = strm.state;+ if (typeof sources === 'object') {- if (!strm.output ||- (!strm.input && strm.avail_in !== 0) ||- (s.status === FINISH_STATE && flush !== Z_FINISH)) {- return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);- }+ // Explode the Plan B channel sources with one m-line per source.+ Object.keys(sources).forEach(function(ssrc) {- s.strm = strm; /* just in case */- old_flush = s.last_flush;- s.last_flush = flush;+ // The (unified) m-line for this SSRC. We either create it from+ // scratch or, if it's a grouped SSRC, we re-use a related+ // mline. In other words, if the source is grouped with another+ // source, put the two together in the same m-line.+ var uLine;- /* Write the header */- if (s.status === INIT_STATE) {+ // We assume here that we are the answerer in the O/A, so any+ // offers which we translate come from the remote side, while+ // answers are local. So the check below is to make that we+ // handle receive-only SSRCs in a special way only if they come+ // from the remote side.+ if (desc.type==='offer') {+ // We want to detect SSRCs which are used by a remote peer+ // in an m-line with direction=recvonly (i.e. they are+ // being used for RTCP only).+ // This information would have gotten lost if the remote+ // peer used Unified Plan and their local description was+ // translated to Plan B. So we use the lack of an MSID+ // attribute to deduce a "receive only" SSRC.+ if (!sources[ssrc].msid) {+ recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];+ // Receive-only SSRCs must not create new m-lines. We+ // will assign them to an existing m-line later.+ return;+ }+ }- if (s.wrap === 2) { // GZIP header- strm.adler = 0; //crc32(0L, Z_NULL, 0);- put_byte(s, 31);- put_byte(s, 139);- put_byte(s, 8);- if (!s.gzhead) { // s->gzhead == Z_NULL- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, s.level === 9 ? 2 :- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?- 4 : 0));- put_byte(s, OS_CODE);- s.status = BUSY_STATE;- }- else {- put_byte(s, (s.gzhead.text ? 1 : 0) +- (s.gzhead.hcrc ? 2 : 0) +- (!s.gzhead.extra ? 0 : 4) +- (!s.gzhead.name ? 0 : 8) +- (!s.gzhead.comment ? 0 : 16)- );- put_byte(s, s.gzhead.time & 0xff);- put_byte(s, (s.gzhead.time >> 8) & 0xff);- put_byte(s, (s.gzhead.time >> 16) & 0xff);- put_byte(s, (s.gzhead.time >> 24) & 0xff);- put_byte(s, s.level === 9 ? 2 :- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?- 4 : 0));- put_byte(s, s.gzhead.os & 0xff);- if (s.gzhead.extra && s.gzhead.extra.length) {- put_byte(s, s.gzhead.extra.length & 0xff);- put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);- }- if (s.gzhead.hcrc) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);- }- s.gzindex = 0;- s.status = EXTRA_STATE;- }- }- else // DEFLATE header- {- var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;- var level_flags = -1;+ if (typeof ssrc2group[ssrc] !== 'undefined' &&+ Array.isArray(ssrc2group[ssrc])) {+ ssrc2group[ssrc].some(function (ssrcGroup) {+ // ssrcGroup.ssrcs *is* an Array, no need to check+ // again here.+ return ssrcGroup.ssrcs.some(function (related) {+ if (typeof ssrc2ml[related] === 'object') {+ uLine = ssrc2ml[related];+ return true;+ }+ });+ });+ }- if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {- level_flags = 0;- } else if (s.level < 6) {- level_flags = 1;- } else if (s.level === 6) {- level_flags = 2;- } else {- level_flags = 3;- }- header |= (level_flags << 6);- if (s.strstart !== 0) { header |= PRESET_DICT; }- header += 31 - (header % 31);+ if (typeof uLine === 'object') {+ // the m-line already exists. Just add the source.+ uLine.sources[ssrc] = sources[ssrc];+ delete sources[ssrc].msid;+ } else {+ // Use the "bLine" as a prototype for the "uLine".+ uLine = Object.create(bLine);+ ssrc2ml[ssrc] = uLine;- s.status = BUSY_STATE;- putShortMSB(s, header);+ if (typeof sources[ssrc].msid !== 'undefined') {+ // Assign the msid of the source to the m-line. Note+ // that it is not guaranteed that the source will have+ // msid. In particular "recvonly" sources don't have an+ // msid. Note that "recvonly" is a term only defined+ // for m-lines.+ uLine.msid = sources[ssrc].msid;+ uLine.direction = 'sendrecv';+ delete sources[ssrc].msid;+ }- /* Save the adler32 of the preset dictionary: */- if (s.strstart !== 0) {- putShortMSB(s, strm.adler >>> 16);- putShortMSB(s, strm.adler & 0xffff);- }- strm.adler = 1; // adler32(0L, Z_NULL, 0);- }- }+ // We assign one SSRC per media line.+ uLine.sources = {};+ uLine.sources[ssrc] = sources[ssrc];+ uLine.ssrcGroups = ssrc2group[ssrc];- //#ifdef GZIP- if (s.status === EXTRA_STATE) {- if (s.gzhead.extra/* != Z_NULL*/) {- beg = s.pending; /* start of bytes to update crc */+ // Use the cached Unified Plan SDP (if it exists) to assign+ // SSRCs to mids.+ if (typeof cached !== 'undefined' &&+ typeof cached.media !== 'undefined' &&+ Array.isArray(cached.media)) {- while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {- if (s.pending === s.pending_buf_size) {- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- flush_pending(strm);- beg = s.pending;- if (s.pending === s.pending_buf_size) {- break;- }- }- put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);- s.gzindex++;- }- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- if (s.gzindex === s.gzhead.extra.length) {- s.gzindex = 0;- s.status = NAME_STATE;- }- }- else {- s.status = NAME_STATE;- }- }- if (s.status === NAME_STATE) {- if (s.gzhead.name/* != Z_NULL*/) {- beg = s.pending; /* start of bytes to update crc */- //int val;+ cached.media.forEach(function (m) {+ if (typeof m.sources === 'object') {+ Object.keys(m.sources).forEach(function (s) {+ if (s === ssrc) {+ uLine.mid = m.mid;+ }+ });+ }+ });+ }- do {- if (s.pending === s.pending_buf_size) {- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- flush_pending(strm);- beg = s.pending;- if (s.pending === s.pending_buf_size) {- val = 1;- break;- }- }- // JS specific: little magic to add zero terminator to end of string- if (s.gzindex < s.gzhead.name.length) {- val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;- } else {- val = 0;- }- put_byte(s, val);- } while (val !== 0);+ if (typeof uLine.mid === 'undefined') {++ // If this is an SSRC that we see for the first time+ // assign it a new mid. This is typically the case when+ // this method is called to transform a remote+ // description for the first time or when there is a+ // new SSRC in the remote description because a new+ // peer has joined the conference. Local SSRCs should+ // have already been added to the map in the toPlanB+ // method.+ //+ // Because FF generates answers in Unified Plan style,+ // we MUST already have a cached answer with all the+ // local SSRCs mapped to some m-line/mid.- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- if (val === 0) {- s.gzindex = 0;- s.status = COMMENT_STATE;- }- }- else {- s.status = COMMENT_STATE;- }- }- if (s.status === COMMENT_STATE) {- if (s.gzhead.comment/* != Z_NULL*/) {- beg = s.pending; /* start of bytes to update crc */- //int val;+ if (desc.type === 'answer') {+ throw new Error("An unmapped SSRC was found.");+ }- do {- if (s.pending === s.pending_buf_size) {- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- flush_pending(strm);- beg = s.pending;- if (s.pending === s.pending_buf_size) {- val = 1;- break;- }- }- // JS specific: little magic to add zero terminator to end of string- if (s.gzindex < s.gzhead.comment.length) {- val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;- } else {- val = 0;+ uLine.mid = [bLine.type, '-', ssrc].join('');+ }++ // Include the candidates in the 1st media line.+ uLine.candidates = candidates;+ uLine.iceUfrag = iceUfrag;+ uLine.icePwd = icePwd;+ uLine.fingerprint = fingerprint;+ uLine.port = port;++ mid2ul[uLine.mid] = uLine;+ }+ });}- put_byte(s, val);- } while (val !== 0);+ });- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- if (val === 0) {- s.status = HCRC_STATE;- }- }- else {- s.status = HCRC_STATE;- }- }- if (s.status === HCRC_STATE) {- if (s.gzhead.hcrc) {- if (s.pending + 2 > s.pending_buf_size) {- flush_pending(strm);- }- if (s.pending + 2 <= s.pending_buf_size) {- put_byte(s, strm.adler & 0xff);- put_byte(s, (strm.adler >> 8) & 0xff);- strm.adler = 0; //crc32(0L, Z_NULL, 0);- s.status = BUSY_STATE;- }- }- else {- s.status = BUSY_STATE;- }- }- //#endif+ // Rebuild the media array in the right order and add the missing mLines+ // (missing from the Plan B SDP).+ session.media = [];+ mids = []; // reuse- /* Flush as much pending output as possible */- if (s.pending !== 0) {- flush_pending(strm);- if (strm.avail_out === 0) {- /* Since avail_out is 0, deflate will be called again with- * more output space, but possibly with both pending and- * avail_in equal to zero. There won't be anything to do,- * but this is not an error situation so make sure we- * return OK instead of BUF_ERROR at next call of deflate:- */- s.last_flush = -1;- return Z_OK;- }+ if (desc.type === 'answer') {- /* Make sure there is something to do and avoid duplicate consecutive- * flushes. For repeated and useless calls with Z_FINISH, we keep- * returning Z_STREAM_END instead of Z_BUF_ERROR.- */- } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&- flush !== Z_FINISH) {- return err(strm, Z_BUF_ERROR);- }+ // The media lines in the answer must match the media lines in the+ // offer. The order is important too. Here we assume that Firefox is+ // the answerer, so we merely have to use the reconstructed (unified)+ // answer to update the cached (unified) answer accordingly.+ //+ // In the general case, one would have to use the cached (unified)+ // offer to find the m-lines that are missing from the reconstructed+ // answer, potentially grabbing them from the cached (unified) answer.+ // One has to be careful with this approach because inactive m-lines do+ // not always have an mid, making it tricky (impossible?) to find where+ // exactly and which m-lines are missing from the reconstructed answer.- /* User must not provide more input after the first FINISH: */- if (s.status === FINISH_STATE && strm.avail_in !== 0) {- return err(strm, Z_BUF_ERROR);- }+ for (var i = 0; i < cached.media.length; i++) {+ var uLine = cached.media[i];- /* Start a new block or continue the current one.- */- if (strm.avail_in !== 0 || s.lookahead !== 0 ||- (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {- var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :- (s.strategy === Z_RLE ? deflate_rle(s, flush) :- configuration_table[s.level].func(s, flush));+ if (typeof mid2ul[uLine.mid] === 'undefined') {- if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {- s.status = FINISH_STATE;- }- if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {- if (strm.avail_out === 0) {- s.last_flush = -1;- /* avoid BUF_ERROR next call, see above */- }- return Z_OK;- /* If flush != Z_NO_FLUSH && avail_out == 0, the next call- * of deflate should use the same flush parameter to make sure- * that the flush is complete. So we don't have to output an- * empty block here, this will be done at next call. This also- * ensures that for a very small output buffer, we emit at most- * one empty block.- */- }- if (bstate === BS_BLOCK_DONE) {- if (flush === Z_PARTIAL_FLUSH) {- trees._tr_align(s);- }- else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */+ // The mid isn't in the reconstructed (unified) answer.+ // This is either a (unified) m-line containing a remote+ // track only, or a (unified) m-line containing a remote+ // track and a local track that has been removed.+ // In either case, it MUST exist in the cached+ // (unified) answer.+ //+ // In case this is a removed local track, clean-up+ // the (unified) m-line and make sure it's 'recvonly' or+ // 'inactive'.- trees._tr_stored_block(s, 0, 0, false);- /* For a full flush, this empty block will be recognized- * as a special marker by inflate_sync().- */- if (flush === Z_FULL_FLUSH) {- /*** CLEAR_HASH(s); ***/ /* forget history */- zero(s.head); // Fill with NIL (= 0);+ delete uLine.msid;+ delete uLine.sources;+ delete uLine.ssrcGroups;+ if (!uLine.direction+ || uLine.direction === 'sendrecv')+ uLine.direction = 'recvonly';+ else if (uLine.direction === 'sendonly')+ uLine.direction = 'inactive';+ } else {+ // This is an (unified) m-line/channel that contains a local+ // track (sendrecv or sendonly channel) or it's a unified+ // recvonly m-line/channel. In either case, since we're+ // going from PlanB -> Unified Plan this m-line MUST+ // exist in the cached answer.+ }- if (s.lookahead === 0) {- s.strstart = 0;- s.block_start = 0;- s.insert = 0;- }+ session.media.push(uLine);++ if (typeof uLine.mid === 'string') {+ // inactive lines don't/may not have an mid.+ mids.push(uLine.mid);+ }}- }- flush_pending(strm);- if (strm.avail_out === 0) {- s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */- return Z_OK;- }- }- }- //Assert(strm->avail_out > 0, "bug2");- //if (strm.avail_out <= 0) { throw new Error("bug2");}+ } else {- if (flush !== Z_FINISH) { return Z_OK; }- if (s.wrap <= 0) { return Z_STREAM_END; }+ // SDP offer/answer (and the JSEP spec) forbids removing an m-section+ // under any circumstances. If we are no longer interested in sending a+ // track, we just remove the msid and ssrc attributes and set it to+ // either a=recvonly (as the reofferer, we must use recvonly if the+ // other side was previously sending on the m-section, but we can also+ // leave the possibility open if it wasn't previously in use), or+ // a=inactive.- /* Write the trailer */- if (s.wrap === 2) {- put_byte(s, strm.adler & 0xff);- put_byte(s, (strm.adler >> 8) & 0xff);- put_byte(s, (strm.adler >> 16) & 0xff);- put_byte(s, (strm.adler >> 24) & 0xff);- put_byte(s, strm.total_in & 0xff);- put_byte(s, (strm.total_in >> 8) & 0xff);- put_byte(s, (strm.total_in >> 16) & 0xff);- put_byte(s, (strm.total_in >> 24) & 0xff);- }- else- {- putShortMSB(s, strm.adler >>> 16);- putShortMSB(s, strm.adler & 0xffff);- }+ if (typeof cached !== 'undefined' &&+ typeof cached.media !== 'undefined' &&+ Array.isArray(cached.media)) {+ cached.media.forEach(function(uLine) {+ mids.push(uLine.mid);+ if (typeof mid2ul[uLine.mid] !== 'undefined') {+ session.media.push(mid2ul[uLine.mid]);+ } else {+ delete uLine.msid;+ delete uLine.sources;+ delete uLine.ssrcGroups;+ if (!uLine.direction+ || uLine.direction === 'sendrecv')+ uLine.direction = 'recvonly';+ if (!uLine.direction+ || uLine.direction === 'sendonly')+ uLine.direction = 'inactive';+ session.media.push(uLine);+ }+ });+ }- flush_pending(strm);- /* If avail_out is zero, the application will call deflate again- * to flush the rest.- */- if (s.wrap > 0) { s.wrap = -s.wrap; }- /* write the trailer only once! */- return s.pending !== 0 ? Z_OK : Z_STREAM_END;- }+ // Add all the remaining (new) m-lines of the transformed SDP.+ Object.keys(mid2ul).forEach(function(mid) {+ if (mids.indexOf(mid) === -1) {+ mids.push(mid);+ if (mid2ul[mid].direction === 'recvonly') {+ // This is a remote recvonly channel. Add its SSRC to the+ // appropriate sendrecv or sendonly channel.+ // TODO(gp) what if we don't have sendrecv/sendonly+ // channel?- function deflateEnd(strm) {- var status;+ session.media.some(function (uLine) {+ if ((uLine.direction === 'sendrecv' ||+ uLine.direction === 'sendonly') &&+ uLine.type === mid2ul[mid].type) {- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {- return Z_STREAM_ERROR;- }+ // mid2ul[mid] shouldn't have any ssrc-groups+ Object.keys(mid2ul[mid].sources).forEach(+ function (ssrc) {+ uLine.sources[ssrc] =+ mid2ul[mid].sources[ssrc];+ });- status = strm.state.status;- if (status !== INIT_STATE &&- status !== EXTRA_STATE &&- status !== NAME_STATE &&- status !== COMMENT_STATE &&- status !== HCRC_STATE &&- status !== BUSY_STATE &&- status !== FINISH_STATE- ) {- return err(strm, Z_STREAM_ERROR);- }+ return true;+ }+ });+ } else {+ session.media.push(mid2ul[mid]);+ }+ }+ });+ }- strm.state = null;+ // After we have constructed the Plan Unified m-lines we can figure out+ // where (in which m-line) to place the 'recvonly SSRCs'.+ // Note: we assume here that we are the answerer in the O/A, so any offers+ // which we translate come from the remote side, while answers are local+ // (and so our last local description is cached as an 'answer').+ ["audio", "video"].forEach(function (type) {+ if (!session || !session.media || !Array.isArray(session.media))+ return;- return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;- }+ var idx = null;+ if (Object.keys(recvonlySsrcs[type]).length > 0) {+ idx = self.getFirstSendingIndexFromAnswer(type);+ if (idx === null){+ // If this is the first offer we receive, we don't have a+ // cached answer. Assume that we will be sending media using+ // the first m-line for each media type.- /* =========================================================================- * Copy the source state to the destination state- */- //function deflateCopy(dest, source) {- //- //}+ for (var i = 0; i < session.media.length; i++) {+ if (session.media[i].type === type) {+ idx = i;+ break;+ }+ }+ }+ }- exports.deflateInit = deflateInit;- exports.deflateInit2 = deflateInit2;- exports.deflateReset = deflateReset;- exports.deflateResetKeep = deflateResetKeep;- exports.deflateSetHeader = deflateSetHeader;- exports.deflate = deflate;- exports.deflateEnd = deflateEnd;- exports.deflateInfo = 'pako deflate (from Nodeca project)';+ if (idx && session.media.length > idx) {+ var mLine = session.media[idx];+ Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {+ if (mLine.sources && mLine.sources[ssrc]) {+ console.warn("Replacing an existing SSRC.");+ }+ if (!mLine.sources) {+ mLine.sources = {};+ }- /* Not implemented- exports.deflateBound = deflateBound;- exports.deflateCopy = deflateCopy;- exports.deflateSetDictionary = deflateSetDictionary;- exports.deflateParams = deflateParams;- exports.deflatePending = deflatePending;- exports.deflatePrime = deflatePrime;- exports.deflateTune = deflateTune;- */+ mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];+ });+ }+ });- },{"../utils/common":87,"./adler32":89,"./crc32":91,"./messages":97,"./trees":98}],93:[function(require,module,exports){- 'use strict';+ // We regenerate the BUNDLE group (since we regenerated the mids)+ session.groups.some(function(group) {+ if (group.type === 'BUNDLE') {+ group.mids = mids.join(' ');+ return true;+ }+ });++ // msid semantic+ session.msidSemantic = {+ semantic: 'WMS',+ token: '*'+ };+ var resStr = transform.write(session);- function GZheader() {- /* true if compressed data believed to be text */- this.text = 0;- /* modification time */- this.time = 0;- /* extra flags (not used when writing a gzip file) */- this.xflags = 0;- /* operating system */- this.os = 0;- /* pointer to extra field or Z_NULL if none */- this.extra = null;- /* extra field length (valid if extra != Z_NULL) */- this.extra_len = 0; // Actually, we don't need it in JS,- // but leave for few code modifications+ // Cache the transformed SDP (Unified Plan) for later re-use in this+ // function.+ this.cache[desc.type] = resStr;- //- // Setup limits is not necessary because in js we should not preallocate memory- // for inflate use constant limit in 65536 bytes- //+ return new RTCSessionDescription({+ type: desc.type,+ sdp: resStr+ });- /* space at extra (only when reading header) */- // this.extra_max = 0;- /* pointer to zero-terminated file name or Z_NULL */- this.name = '';- /* space at name (only when reading header) */- // this.name_max = 0;- /* pointer to zero-terminated comment or Z_NULL */- this.comment = '';- /* space at comment (only when reading header) */- // this.comm_max = 0;- /* true if there was or will be a header crc */- this.hcrc = 0;- /* true when done reading gzip header (not used when writing a gzip file) */- this.done = false;- }+ //#endregion+ };- module.exports = GZheader;-},{"./array-equals":67,"./transform":70}],70:[function(require,module,exports){++},{"./array-equals":68,"./transform":71}],71:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ */- },{}],94:[function(require,module,exports){- 'use strict';+ var transform = require('sdp-transform');- // See state defs from inflate.js- var BAD = 30; /* got a data error -- remain here until reset */- var TYPE = 12; /* i: waiting for type bits, including last-flag bit */+ exports.write = function(session, opts) {- /*- Decode literal, length, and distance codes and write out the resulting- literal and match bytes until either not enough input or output is- available, an end-of-block is encountered, or a data error is encountered.- When large enough input and output buffers are supplied to inflate(), for- example, a 16K input buffer and a 64K output buffer, more than 95% of the- inflate execution time is spent in this routine.+ if (typeof session !== 'undefined' &&+ typeof session.media !== 'undefined' &&+ Array.isArray(session.media)) {- Entry assumptions:+ session.media.forEach(function (mLine) {+ // expand sources to ssrcs+ if (typeof mLine.sources !== 'undefined' &&+ Object.keys(mLine.sources).length !== 0) {+ mLine.ssrcs = [];+ Object.keys(mLine.sources).forEach(function (ssrc) {+ var source = mLine.sources[ssrc];+ Object.keys(source).forEach(function (attribute) {+ mLine.ssrcs.push({+ id: ssrc,+ attribute: attribute,+ value: source[attribute]+ });+ });+ });+ delete mLine.sources;+ }- state.mode === LEN- strm.avail_in >= 6- strm.avail_out >= 258- start >= strm.avail_out- state.bits < 8+ // join ssrcs in ssrc groups+ if (typeof mLine.ssrcGroups !== 'undefined' &&+ Array.isArray(mLine.ssrcGroups)) {+ mLine.ssrcGroups.forEach(function (ssrcGroup) {+ if (typeof ssrcGroup.ssrcs !== 'undefined' &&+ Array.isArray(ssrcGroup.ssrcs)) {+ ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');+ }+ });+ }+ });+ }- On return, state.mode is one of:+ // join group mids+ if (typeof session !== 'undefined' &&+ typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {- LEN -- ran out of enough output space or enough available input- TYPE -- reached end of block code, inflate() to interpret next block- BAD -- error in block data+ session.groups.forEach(function (g) {+ if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {+ g.mids = g.mids.join(' ');+ }+ });+ }++ return transform.write(session, opts);+ };- Notes:+ exports.parse = function(sdp) {+ var session = transform.parse(sdp);- - The maximum input bits used by a length/distance pair is 15 bits for the- length code, 5 bits for the length extra, 15 bits for the distance code,- and 13 bits for the distance extra. This totals 48 bits, or six bytes.- Therefore if strm.avail_in >= 6, then there is enough input to avoid- checking for available input while decoding.+ if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&+ Array.isArray(session.media)) {- - The maximum bytes that a single length/distance pair can output is 258- bytes, which is the maximum length that can be coded. inflate_fast()- requires strm.avail_out >= 258 for each loop to avoid checking for- output space.- */- module.exports = function inflate_fast(strm, start) {- var state;- var _in; /* local strm.input */- var last; /* have enough input while in < last */- var _out; /* local strm.output */- var beg; /* inflate()'s initial strm.output */- var end; /* while out < end, enough space available */- //#ifdef INFLATE_STRICT- var dmax; /* maximum distance from zlib header */- //#endif- var wsize; /* window size or zero if not using window */- var whave; /* valid bytes in the window */- var wnext; /* window write index */- // Use `s_window` instead `window`, avoid conflict with instrumentation tools- var s_window; /* allocated sliding window, if wsize != 0 */- var hold; /* local strm.hold */- var bits; /* local strm.bits */- var lcode; /* local strm.lencode */- var dcode; /* local strm.distcode */- var lmask; /* mask for first level of length codes */- var dmask; /* mask for first level of distance codes */- var here; /* retrieved table entry */- var op; /* code bits, operation, extra bits, or */- /* window position, window bytes to copy */- var len; /* match length, unused bytes */- var dist; /* match distance */- var from; /* where to copy match from */- var from_source;+ session.media.forEach(function (mLine) {+ // group sources attributes by ssrc+ if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {+ mLine.sources = {};+ mLine.ssrcs.forEach(function (ssrc) {+ if (!mLine.sources[ssrc.id])+ mLine.sources[ssrc.id] = {};+ mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;+ });+ delete mLine.ssrcs;+ }- var input, output; // JS specific, because we have no pointers+ // split ssrcs in ssrc groups+ if (typeof mLine.ssrcGroups !== 'undefined' &&+ Array.isArray(mLine.ssrcGroups)) {+ mLine.ssrcGroups.forEach(function (ssrcGroup) {+ if (typeof ssrcGroup.ssrcs === 'string') {+ ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');+ }+ });+ }+ });+ }+ // split group mids+ if (typeof session !== 'undefined' &&+ typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {- /* copy state to local variables */- state = strm.state;- //here = state.here;- _in = strm.next_in;- input = strm.input;- last = _in + (strm.avail_in - 5);- _out = strm.next_out;- output = strm.output;- beg = _out - (start - strm.avail_out);- end = _out + (strm.avail_out - 257);- //#ifdef INFLATE_STRICT- dmax = state.dmax;- //#endif- wsize = state.wsize;- whave = state.whave;- wnext = state.wnext;- s_window = state.window;- hold = state.hold;- bits = state.bits;- lcode = state.lencode;- dcode = state.distcode;- lmask = (1 << state.lenbits) - 1;- dmask = (1 << state.distbits) - 1;+ session.groups.forEach(function (g) {+ if (typeof g.mids === 'string') {+ g.mids = g.mids.split(' ');+ }+ });+ }++ return session;+ };- /* decode literals and length/distances until end-of-block or not enough- input data or output space */-},{"sdp-transform":72}],71:[function(require,module,exports){++},{"sdp-transform":73}],72:[function(require,module,exports){+ var grammar = module.exports = {+ v: [{+ name: 'version',+ reg: /^(\d*)$/+ }],+ o: [{ //o=- 20518 0 IN IP4 203.0.113.1+ // NB: sessionId will be a String in most cases because it is huge+ name: 'origin',+ reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,+ names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],+ format: "%s %s %d %s IP%d %s"+ }],+ // default parsing of these only (though some of these feel outdated)+ s: [{ name: 'name' }],+ i: [{ name: 'description' }],+ u: [{ name: 'uri' }],+ e: [{ name: 'email' }],+ p: [{ name: 'phone' }],+ z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..+ r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly+ //k: [{}], // outdated thing ignored+ t: [{ //t=0 0+ name: 'timing',+ reg: /^(\d*) (\d*)/,+ names: ['start', 'stop'],+ format: "%d %d"+ }],+ c: [{ //c=IN IP4 10.47.197.26+ name: 'connection',+ reg: /^IN IP(\d) (\S*)/,+ names: ['version', 'ip'],+ format: "IN IP%d %s"+ }],+ b: [{ //b=AS:4000+ push: 'bandwidth',+ reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,+ names: ['type', 'limit'],+ format: "%s:%s"+ }],+ m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31+ // NB: special - pushes to session+ // TODO: rtp/fmtp should be filtered by the payloads found here?+ reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,+ names: ['type', 'port', 'protocol', 'payloads'],+ format: "%s %d %s %s"+ }],+ a: [+ { //a=rtpmap:110 opus/48000/2+ push: 'rtp',+ reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,+ names: ['payload', 'codec', 'rate', 'encoding'],+ format: function (o) {+ return (o.encoding) ?+ "rtpmap:%d %s/%s/%s":+ o.rate ?+ "rtpmap:%d %s/%s":+ "rtpmap:%d %s";+ }+ },+ {+ //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000+ //a=fmtp:111 minptime=10; useinbandfec=1+ push: 'fmtp',+ reg: /^fmtp:(\d*) ([\S| ]*)/,+ names: ['payload', 'config'],+ format: "fmtp:%d %s"+ },+ { //a=control:streamid=0+ name: 'control',+ reg: /^control:(.*)/,+ format: "control:%s"+ },+ { //a=rtcp:65179 IN IP4 193.84.77.194+ name: 'rtcp',+ reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,+ names: ['port', 'netType', 'ipVer', 'address'],+ format: function (o) {+ return (o.address != null) ?+ "rtcp:%d %s IP%d %s":+ "rtcp:%d";+ }+ },+ { //a=rtcp-fb:98 trr-int 100+ push: 'rtcpFbTrrInt',+ reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,+ names: ['payload', 'value'],+ format: "rtcp-fb:%d trr-int %d"+ },+ { //a=rtcp-fb:98 nack rpsi+ push: 'rtcpFb',+ reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,+ names: ['payload', 'type', 'subtype'],+ format: function (o) {+ return (o.subtype != null) ?+ "rtcp-fb:%s %s %s":+ "rtcp-fb:%s %s";+ }+ },+ { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset+ //a=extmap:1/recvonly URI-gps-string+ push: 'ext',+ reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,+ names: ['value', 'uri', 'config'], // value may include "/direction" suffix+ format: function (o) {+ return (o.config != null) ?+ "extmap:%s %s %s":+ "extmap:%s %s";+ }+ },+ {+ //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32+ push: 'crypto',+ reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,+ names: ['id', 'suite', 'config', 'sessionConfig'],+ format: function (o) {+ return (o.sessionConfig != null) ?+ "crypto:%d %s %s %s":+ "crypto:%d %s %s";+ }+ },+ { //a=setup:actpass+ name: 'setup',+ reg: /^setup:(\w*)/,+ format: "setup:%s"+ },+ { //a=mid:1+ name: 'mid',+ reg: /^mid:([^\s]*)/,+ format: "mid:%s"+ },+ { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a+ name: 'msid',+ reg: /^msid:(.*)/,+ format: "msid:%s"+ },+ { //a=ptime:20+ name: 'ptime',+ reg: /^ptime:(\d*)/,+ format: "ptime:%d"+ },+ { //a=maxptime:60+ name: 'maxptime',+ reg: /^maxptime:(\d*)/,+ format: "maxptime:%d"+ },+ { //a=sendrecv+ name: 'direction',+ reg: /^(sendrecv|recvonly|sendonly|inactive)/+ },+ { //a=ice-lite+ name: 'icelite',+ reg: /^(ice-lite)/+ },+ { //a=ice-ufrag:F7gI+ name: 'iceUfrag',+ reg: /^ice-ufrag:(\S*)/,+ format: "ice-ufrag:%s"+ },+ { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g+ name: 'icePwd',+ reg: /^ice-pwd:(\S*)/,+ format: "ice-pwd:%s"+ },+ { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33+ name: 'fingerprint',+ reg: /^fingerprint:(\S*) (\S*)/,+ names: ['type', 'hash'],+ format: "fingerprint:%s %s"+ },+ {+ //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host+ //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0+ //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0+ //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0+ //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0+ push:'candidates',+ reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,+ names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],+ format: function (o) {+ var str = "candidate:%s %d %s %d %s %d typ %s";- top:- do {- if (bits < 15) {- hold += input[_in++] << bits;- bits += 8;- hold += input[_in++] << bits;- bits += 8;- }+ str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";- here = lcode[hold & lmask];+ // NB: candidate has three optional chunks, so %void middles one if it's missing+ str += (o.tcptype != null) ? " tcptype %s" : "%v";- dolen:- for (;;) { // Goto emulation- op = here >>> 24/*here.bits*/;- hold >>>= op;- bits -= op;- op = (here >>> 16) & 0xff/*here.op*/;- if (op === 0) { /* literal */- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?- // "inflate: literal '%c'\n" :- // "inflate: literal 0x%02x\n", here.val));- output[_out++] = here & 0xffff/*here.val*/;- }- else if (op & 16) { /* length base */- len = here & 0xffff/*here.val*/;- op &= 15; /* number of extra bits */- if (op) {- if (bits < op) {- hold += input[_in++] << bits;- bits += 8;- }- len += hold & ((1 << op) - 1);- hold >>>= op;- bits -= op;- }- //Tracevv((stderr, "inflate: length %u\n", len));- if (bits < 15) {- hold += input[_in++] << bits;- bits += 8;- hold += input[_in++] << bits;- bits += 8;+ if (o.generation != null) {+ str += " generation %d";}- here = dcode[hold & dmask];-- dodist:- for (;;) { // goto emulation- op = here >>> 24/*here.bits*/;- hold >>>= op;- bits -= op;- op = (here >>> 16) & 0xff/*here.op*/;-- if (op & 16) { /* distance base */- dist = here & 0xffff/*here.val*/;- op &= 15; /* number of extra bits */- if (bits < op) {- hold += input[_in++] << bits;- bits += 8;- if (bits < op) {- hold += input[_in++] << bits;- bits += 8;- }- }- dist += hold & ((1 << op) - 1);- //#ifdef INFLATE_STRICT- if (dist > dmax) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break top;- }- //#endif- hold >>>= op;- bits -= op;- //Tracevv((stderr, "inflate: distance %u\n", dist));- op = _out - beg; /* max distance in output */- if (dist > op) { /* see if copy from window */- op = dist - op; /* distance back in window */- if (op > whave) {- if (state.sane) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break top;- }-- // (!) This block is disabled in zlib defailts,- // don't enable it for binary compatibility- //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR- // if (len <= op - whave) {- // do {- // output[_out++] = 0;- // } while (--len);- // continue top;- // }- // len -= op - whave;- // do {- // output[_out++] = 0;- // } while (--op > whave);- // if (op === 0) {- // from = _out - dist;- // do {- // output[_out++] = output[from++];- // } while (--len);- // continue top;- // }- //#endif- }- from = 0; // window index- from_source = s_window;- if (wnext === 0) { /* very common case */- from += wsize - op;- if (op < len) { /* some from window */- len -= op;- do {- output[_out++] = s_window[from++];- } while (--op);- from = _out - dist; /* rest from output */- from_source = output;- }- }- else if (wnext < op) { /* wrap around window */- from += wsize + wnext - op;- op -= wnext;- if (op < len) { /* some from end of window */- len -= op;- do {- output[_out++] = s_window[from++];- } while (--op);- from = 0;- if (wnext < len) { /* some from start of window */- op = wnext;- len -= op;- do {- output[_out++] = s_window[from++];- } while (--op);- from = _out - dist; /* rest from output */- from_source = output;- }- }- }- else { /* contiguous in window */- from += wnext - op;- if (op < len) { /* some from window */- len -= op;- do {- output[_out++] = s_window[from++];- } while (--op);- from = _out - dist; /* rest from output */- from_source = output;- }- }- while (len > 2) {- output[_out++] = from_source[from++];- output[_out++] = from_source[from++];- output[_out++] = from_source[from++];- len -= 3;- }- if (len) {- output[_out++] = from_source[from++];- if (len > 1) {- output[_out++] = from_source[from++];- }- }- }- else {- from = _out - dist; /* copy direct from output */- do { /* minimum length is three */- output[_out++] = output[from++];- output[_out++] = output[from++];- output[_out++] = output[from++];- len -= 3;- } while (len > 2);- if (len) {- output[_out++] = output[from++];- if (len > 1) {- output[_out++] = output[from++];- }- }- }- }- else if ((op & 64) === 0) { /* 2nd level distance code */- here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];- continue dodist;- }- else {- strm.msg = 'invalid distance code';- state.mode = BAD;- break top;- }+ return str;+ }+ },+ { //a=end-of-candidates (keep after the candidates line for readability)+ name: 'endOfCandidates',+ reg: /^(end-of-candidates)/+ },+ { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...+ name: 'remoteCandidates',+ reg: /^remote-candidates:(.*)/,+ format: "remote-candidates:%s"+ },+ { //a=ice-options:google-ice+ name: 'iceOptions',+ reg: /^ice-options:(\S*)/,+ format: "ice-options:%s"+ },+ { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1+ push: "ssrcs",+ reg: /^ssrc:(\d*) ([\w_]*):(.*)/,+ names: ['id', 'attribute', 'value'],+ format: "ssrc:%d %s:%s"+ },+ { //a=ssrc-group:FEC 1 2+ push: "ssrcGroups",+ reg: /^ssrc-group:(\w*) (.*)/,+ names: ['semantics', 'ssrcs'],+ format: "ssrc-group:%s %s"+ },+ { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV+ name: "msidSemantic",+ reg: /^msid-semantic:\s?(\w*) (\S*)/,+ names: ['semantic', 'token'],+ format: "msid-semantic: %s %s" // space after ":" is not accidental+ },+ { //a=group:BUNDLE audio video+ push: 'groups',+ reg: /^group:(\w*) (.*)/,+ names: ['type', 'mids'],+ format: "group:%s %s"+ },+ { //a=rtcp-mux+ name: 'rtcpMux',+ reg: /^(rtcp-mux)/+ },+ { //a=rtcp-rsize+ name: 'rtcpRsize',+ reg: /^(rtcp-rsize)/+ },+ { // any a= that we don't understand is kepts verbatim on media.invalid+ push: 'invalid',+ names: ["value"]+ }+ ]+ };- break; // need to emulate goto via "continue"- }- }- else if ((op & 64) === 0) { /* 2nd level length code */- here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];- continue dolen;- }- else if (op & 32) { /* end-of-block */- //Tracevv((stderr, "inflate: end of block\n"));- state.mode = TYPE;- break top;- }- else {- strm.msg = 'invalid literal/length code';- state.mode = BAD;- break top;- }+ // set sensible defaults to avoid polluting the grammar with boring details+ Object.keys(grammar).forEach(function (key) {+ var objs = grammar[key];+ objs.forEach(function (obj) {+ if (!obj.reg) {+ obj.reg = /(.*)/;+ }+ if (!obj.format) {+ obj.format = "%s";+ }+ });+ });- break; // need to emulate goto via "continue"-},{}],72:[function(require,module,exports){++},{}],73:[function(require,module,exports){+ var parser = require('./parser');+ var writer = require('./writer');++ exports.write = writer;+ exports.parse = parser.parse;+ exports.parseFmtpConfig = parser.parseFmtpConfig;+ exports.parsePayloads = parser.parsePayloads;+ exports.parseRemoteCandidates = parser.parseRemoteCandidates;+-},{"./parser":73,"./writer":74}],73:[function(require,module,exports){++},{"./parser":74,"./writer":75}],74:[function(require,module,exports){+ var toIntIfInt = function (v) {+ return String(Number(v)) === v ? Number(v) : v;+ };++ var attachProperties = function (match, location, names, rawName) {+ if (rawName && !names) {+ location[rawName] = toIntIfInt(match[1]);+ }+ else {+ for (var i = 0; i < names.length; i += 1) {+ if (match[i+1] != null) {+ location[names[i]] = toIntIfInt(match[i+1]);+ }}- } while (_in < last && _out < end);+ }+ };- /* return unused bytes (on entry, bits < 8, so in won't go too far back) */- len = bits >> 3;- _in -= len;- bits -= len << 3;- hold &= (1 << bits) - 1;+ var parseReg = function (obj, location, content) {+ var needsBlank = obj.name && obj.names;+ if (obj.push && !location[obj.push]) {+ location[obj.push] = [];+ }+ else if (needsBlank && !location[obj.name]) {+ location[obj.name] = {};+ }+ var keyLocation = obj.push ?+ {} : // blank object that will be pushed+ needsBlank ? location[obj.name] : location; // otherwise, named location or root- /* update state and return */- strm.next_in = _in;- strm.next_out = _out;- strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));- strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));- state.hold = hold;- state.bits = bits;- return;+ attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);++ if (obj.push) {+ location[obj.push].push(keyLocation);+ }};- },{}],95:[function(require,module,exports){- 'use strict';+ var grammar = require('./grammar');+ var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);+ exports.parse = function (sdp) {+ var session = {}+ , media = []+ , location = session; // points at where properties go under (one of the above)- var utils = require('../utils/common');- var adler32 = require('./adler32');- var crc32 = require('./crc32');- var inflate_fast = require('./inffast');- var inflate_table = require('./inftrees');+ // parse lines we understand+ sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {+ var type = l[0];+ var content = l.slice(2);+ if (type === 'm') {+ media.push({rtp: [], fmtp: []});+ location = media[media.length-1]; // point at latest media line+ }- var CODES = 0;- var LENS = 1;- var DISTS = 2;+ for (var j = 0; j < (grammar[type] || []).length; j += 1) {+ var obj = grammar[type][j];+ if (obj.reg.test(content)) {+ return parseReg(obj, location, content);+ }+ }+ });- /* Public constants ==========================================================*/- /* ===========================================================================*/+ session.media = media; // link it up+ return session;+ };+ var fmtpReducer = function (acc, expr) {+ var s = expr.split('=');+ if (s.length === 2) {+ acc[s[0]] = toIntIfInt(s[1]);+ }+ return acc;+ };- /* Allowed flush values; see deflate() and inflate() below for details */- //var Z_NO_FLUSH = 0;- //var Z_PARTIAL_FLUSH = 1;- //var Z_SYNC_FLUSH = 2;- //var Z_FULL_FLUSH = 3;- var Z_FINISH = 4;- var Z_BLOCK = 5;- var Z_TREES = 6;+ exports.parseFmtpConfig = function (str) {+ return str.split(/\;\s?/).reduce(fmtpReducer, {});+ };+ exports.parsePayloads = function (str) {+ return str.split(' ').map(Number);+ };- /* Return codes for the compression/decompression functions. Negative values- * are errors, positive values are used for special but normal events.- */- var Z_OK = 0;- var Z_STREAM_END = 1;- var Z_NEED_DICT = 2;- //var Z_ERRNO = -1;- var Z_STREAM_ERROR = -2;- var Z_DATA_ERROR = -3;- var Z_MEM_ERROR = -4;- var Z_BUF_ERROR = -5;- //var Z_VERSION_ERROR = -6;+ exports.parseRemoteCandidates = function (str) {+ var candidates = [];+ var parts = str.split(' ').map(toIntIfInt);+ for (var i = 0; i < parts.length; i += 3) {+ candidates.push({+ component: parts[i],+ ip: parts[i + 1],+ port: parts[i + 2]+ });+ }+ return candidates;+ };- /* The deflate compression method */- var Z_DEFLATED = 8;-},{"./grammar":71}],74:[function(require,module,exports){++},{"./grammar":72}],75:[function(require,module,exports){+ var grammar = require('./grammar');++ // customized util.format - discards excess arguments and can void middle ones+ var formatRegExp = /%[sdv%]/g;+ var format = function (formatStr) {+ var i = 1;+ var args = arguments;+ var len = args.length;+ return formatStr.replace(formatRegExp, function (x) {+ if (i >= len) {+ return x; // missing argument+ }+ var arg = args[i];+ i += 1;+ switch (x) {+ case '%%':+ return '%';+ case '%s':+ return String(arg);+ case '%d':+ return Number(arg);+ case '%v':+ return '';+ }+ });+ // NB: we discard excess arguments - they are typically undefined from makeLine+ };+ var makeLine = function (type, obj, location) {+ var str = obj.format instanceof Function ?+ (obj.format(obj.push ? location : location[obj.name])) :+ obj.format;- /* STATES ====================================================================*/- /* ===========================================================================*/+ var args = [type + '=' + str];+ if (obj.names) {+ for (var i = 0; i < obj.names.length; i += 1) {+ var n = obj.names[i];+ if (obj.name) {+ args.push(location[obj.name][n]);+ }+ else { // for mLine and push attributes+ args.push(location[obj.names[i]]);+ }+ }+ }+ else {+ args.push(location[obj.name]);+ }+ return format.apply(null, args);+ };++ // RFC specified order+ // TODO: extend this with all the rest+ var defaultOuterOrder = [+ 'v', 'o', 's', 'i',+ 'u', 'e', 'p', 'c',+ 'b', 't', 'r', 'z', 'a'+ ];+ var defaultInnerOrder = ['i', 'c', 'b', 'a'];+++ module.exports = function (session, opts) {+ opts = opts || {};+ // ensure certain properties exist+ if (session.version == null) {+ session.version = 0; // "v=0" must be there (only defined version atm)+ }+ if (session.name == null) {+ session.name = " "; // "s= " must be there if no meaningful name set+ }+ session.media.forEach(function (mLine) {+ if (mLine.payloads == null) {+ mLine.payloads = "";+ }+ });+ var outerOrder = opts.outerOrder || defaultOuterOrder;+ var innerOrder = opts.innerOrder || defaultInnerOrder;+ var sdp = [];- var HEAD = 1; /* i: waiting for magic header */- var FLAGS = 2; /* i: waiting for method and flags (gzip) */- var TIME = 3; /* i: waiting for modification time (gzip) */- var OS = 4; /* i: waiting for extra flags and operating system (gzip) */- var EXLEN = 5; /* i: waiting for extra length (gzip) */- var EXTRA = 6; /* i: waiting for extra bytes (gzip) */- var NAME = 7; /* i: waiting for end of file name (gzip) */- var COMMENT = 8; /* i: waiting for end of comment (gzip) */- var HCRC = 9; /* i: waiting for header crc (gzip) */- var DICTID = 10; /* i: waiting for dictionary check value */- var DICT = 11; /* waiting for inflateSetDictionary() call */- var TYPE = 12; /* i: waiting for type bits, including last-flag bit */- var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */- var STORED = 14; /* i: waiting for stored size (length and complement) */- var COPY_ = 15; /* i/o: same as COPY below, but only first time in */- var COPY = 16; /* i/o: waiting for input or output to copy stored block */- var TABLE = 17; /* i: waiting for dynamic block table lengths */- var LENLENS = 18; /* i: waiting for code length code lengths */- var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */- var LEN_ = 20; /* i: same as LEN below, but only first time in */- var LEN = 21; /* i: waiting for length/lit/eob code */- var LENEXT = 22; /* i: waiting for length extra bits */- var DIST = 23; /* i: waiting for distance code */- var DISTEXT = 24; /* i: waiting for distance extra bits */- var MATCH = 25; /* o: waiting for output space to copy string */- var LIT = 26; /* o: waiting for output space to write literal */- var CHECK = 27; /* i: waiting for 32-bit check value */- var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */- var DONE = 29; /* finished check, done -- remain here until reset */- var BAD = 30; /* got a data error -- remain here until reset */- var MEM = 31; /* got an inflate() memory error -- remain here until reset */- var SYNC = 32; /* looking for synchronization bytes to restart inflate() */+ // loop through outerOrder for matching properties on session+ outerOrder.forEach(function (type) {+ grammar[type].forEach(function (obj) {+ if (obj.name in session && session[obj.name] != null) {+ sdp.push(makeLine(type, obj, session));+ }+ else if (obj.push in session && session[obj.push] != null) {+ session[obj.push].forEach(function (el) {+ sdp.push(makeLine(type, obj, el));+ });+ }+ });+ });- /* ===========================================================================*/+ // then for each media line, follow the innerOrder+ session.media.forEach(function (mLine) {+ sdp.push(makeLine('m', grammar.m[0], mLine));+ innerOrder.forEach(function (type) {+ grammar[type].forEach(function (obj) {+ if (obj.name in mLine && mLine[obj.name] != null) {+ sdp.push(makeLine(type, obj, mLine));+ }+ else if (obj.push in mLine && mLine[obj.push] != null) {+ mLine[obj.push].forEach(function (el) {+ sdp.push(makeLine(type, obj, el));+ });+ }+ });+ });+ });+ return sdp.join('\r\n') + '\r\n';+ };- var ENOUGH_LENS = 852;- var ENOUGH_DISTS = 592;- //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);-},{"./grammar":71}],75:[function(require,module,exports){++},{"./grammar":72}],76:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ */- var MAX_WBITS = 15;- /* 32K LZ77 window */- var DEF_WBITS = MAX_WBITS;+ var transform = require('sdp-transform');+ var transformUtils = require('./transform-utils');+ var parseSsrcs = transformUtils.parseSsrcs;+ var writeSsrcs = transformUtils.writeSsrcs;+ //region Constants- function ZSWAP32(q) {- return (((q >>> 24) & 0xff) +- ((q >>> 8) & 0xff00) +- ((q & 0xff00) << 8) +- ((q & 0xff) << 24));- }+ var DEFAULT_NUM_OF_LAYERS = 3;+ //endregion- function InflateState() {- this.mode = 0; /* current inflate mode */- this.last = false; /* true if processing last block */- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */- this.havedict = false; /* true if dictionary provided */- this.flags = 0; /* gzip header method and flags (0 if zlib) */- this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */- this.check = 0; /* protected copy of check value */- this.total = 0; /* protected copy of output count */- // TODO: may be {}- this.head = null; /* where to save gzip header information */+ //region Ctor- /* sliding window */- this.wbits = 0; /* log base 2 of requested window size */- this.wsize = 0; /* window size or zero if not using window */- this.whave = 0; /* valid bytes in the window */- this.wnext = 0; /* window write index */- this.window = null; /* allocated sliding window, if needed */+ function Simulcast(options) {- /* bit accumulator */- this.hold = 0; /* input bit accumulator */- this.bits = 0; /* number of bits in "in" */+ this.options = options ? options : {};- /* for string and stored block copying */- this.length = 0; /* literal or length of data to copy */- this.offset = 0; /* distance back to copy string from */+ if (!this.options.numOfLayers) {+ this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;+ }- /* for table and code decoding */- this.extra = 0; /* extra bits needed */+ this.layers = [];+ }- /* fixed and dynamic code tables */- this.lencode = null; /* starting table for length/literal codes */- this.distcode = null; /* starting table for distance codes */- this.lenbits = 0; /* index bits for lencode */- this.distbits = 0; /* index bits for distcode */+ //endregion- /* dynamic table building */- this.ncode = 0; /* number of code length code lengths */- this.nlen = 0; /* number of length code lengths */- this.ndist = 0; /* number of distance code lengths */- this.have = 0; /* number of code lengths in lens[] */- this.next = null; /* next available space in codes[] */+ //region Stateless private utility functions- this.lens = new utils.Buf16(320); /* temporary storage for code lengths */- this.work = new utils.Buf16(288); /* work area for code table building */+ /**+ * Returns a random integer between min (included) and max (excluded)+ * Using Math.round() gives a non-uniform distribution!+ * @returns {number}+ */+ function generateSSRC() {+ var min = 0, max = 0xffffffff;+ return Math.floor(Math.random() * (max - min)) + min;+ };- /*- because we don't have pointers in js, we use lencode and distcode directly- as buffers so we don't need codes- */- //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */- this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */- this.distdyn = null; /* dynamic table for distance codes (JS specific) */- this.sane = 0; /* if false, allow invalid distance too far */- this.back = 0; /* bits back of last unprocessed length/lit */- this.was = 0; /* initial length of match */+ function processVideo(session, action) {+ if (session == null || !Array.isArray(session.media)) {+ return;+ }++ session.media.forEach(function (mLine) {+ if (mLine.type === 'video') {+ action(mLine);+ }+ });}- function inflateResetKeep(strm) {- var state;+ function validateDescription(desc)+ {+ return desc && desc != null+ && desc.type && desc.type != ''+ && desc.sdp && desc.sdp != '';+ }- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;- strm.total_in = strm.total_out = state.total = 0;- strm.msg = ''; /*Z_NULL*/- if (state.wrap) { /* to support ill-conceived Java test suite */- strm.adler = state.wrap & 1;- }- state.mode = HEAD;- state.last = 0;- state.havedict = 0;- state.dmax = 32768;- state.head = null/*Z_NULL*/;- state.hold = 0;- state.bits = 0;- //state.lencode = state.distcode = state.next = state.codes;- state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);- state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);+ function explodeRemoteSimulcast(mLine) {- state.sane = 1;- state.back = -1;- //Tracev((stderr, "inflate: reset\n"));- return Z_OK;- }+ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {+ return;+ }- function inflateReset(strm) {- var state;+ var sources = parseSsrcs(mLine);+ var order = [];- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;- state.wsize = 0;- state.whave = 0;- state.wnext = 0;- return inflateResetKeep(strm);+ // Find the SIM group and explode its sources.+ var j = mLine.ssrcGroups.length;+ while (j--) {- }+ if (mLine.ssrcGroups[j].semantics !== 'SIM') {+ continue;+ }- function inflateReset2(strm, windowBits) {- var wrap;- var state;+ var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');- /* get the state */- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;+ for (var i = 0; i < simulcastSsrcs.length; i++) {- /* extract wrap request from windowBits parameter */- if (windowBits < 0) {- wrap = 0;- windowBits = -windowBits;- }- else {- wrap = (windowBits >> 4) + 1;- if (windowBits < 48) {- windowBits &= 15;- }- }+ var ssrc = simulcastSsrcs[i];+ order.push(ssrc);- /* set number of window bits, free window if different */- if (windowBits && (windowBits < 8 || windowBits > 15)) {- return Z_STREAM_ERROR;- }- if (state.window !== null && state.wbits !== windowBits) {- state.window = null;- }+ var parts = sources[ssrc].msid.split(' ');+ sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');+ sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');- /* update state and reset the rest of it */- state.wrap = wrap;- state.wbits = windowBits;- return inflateReset(strm);- }+ // Remove all the groups that this SSRC participates in.+ mLine.ssrcGroups.forEach(function (relatedGroup) {+ if (relatedGroup.semantics === 'SIM') {+ return;+ }- function inflateInit2(strm, windowBits) {- var ret;- var state;+ var relatedSsrcs = relatedGroup.ssrcs.split(' ');+ if (relatedSsrcs.indexOf(ssrc) === -1) {+ return;+ }- if (!strm) { return Z_STREAM_ERROR; }- //strm.msg = Z_NULL; /* in case we return an error */+ // Nuke all the related SSRCs.+ relatedSsrcs.forEach(function (relatedSSRC) {+ sources[relatedSSRC].msid = sources[ssrc].msid;+ sources[relatedSSRC].cname = sources[ssrc].cname;+ if (relatedSSRC !== ssrc) {+ order.push(relatedSSRC);+ }+ });- state = new InflateState();+ // Schedule the related group for nuking.+ })+ }- //if (state === Z_NULL) return Z_MEM_ERROR;- //Tracev((stderr, "inflate: allocated\n"));- strm.state = state;- state.window = null/*Z_NULL*/;- ret = inflateReset2(strm, windowBits);- if (ret !== Z_OK) {- strm.state = null/*Z_NULL*/;- }- return ret;+ mLine.ssrcs = writeSsrcs(sources, order);+ mLine.ssrcGroups.splice(j, 1);+ };}- function inflateInit(strm) {- return inflateInit2(strm, DEF_WBITS);- }+ function implodeRemoteSimulcast(mLine) {+ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {+ console.info('Halt: There are no SSRC groups in the remote ' ++ 'description.');+ return;+ }- /*- Return state with length and distance decoding tables and index sizes set to- fixed code decoding. Normally this returns fixed tables from inffixed.h.- If BUILDFIXED is defined, then instead this routine builds the tables the- first time it's called, and returns those tables the first time and- thereafter. This reduces the size of the code by about 2K bytes, in- exchange for a little execution time. However, BUILDFIXED should not be- used for threaded applications, since the rewriting of the tables and virgin- may not be thread-safe.- */- var virgin = true;+ var sources = parseSsrcs(mLine);- var lenfix, distfix; // We have no pointers in JS, so keep tables separate+ // Find the SIM group and nuke it.+ mLine.ssrcGroups.forEach(function (simulcastGroup) {+ if (simulcastGroup.semantics !== 'SIM') {+ return;+ }- function fixedtables(state) {- /* build fixed huffman tables if first call (may not be thread safe) */- if (virgin) {- var sym;+ console.info("Imploding SIM group: " + simulcastGroup.ssrcs);+ // Schedule the SIM group for nuking.+ simulcastGroup.nuke = true;- lenfix = new utils.Buf32(512);- distfix = new utils.Buf32(32);+ var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');- /* literal/length table */- sym = 0;- while (sym < 144) { state.lens[sym++] = 8; }- while (sym < 256) { state.lens[sym++] = 9; }- while (sym < 280) { state.lens[sym++] = 7; }- while (sym < 288) { state.lens[sym++] = 8; }+ // Nuke all the higher layer SSRCs.+ for (var i = 1; i < simulcastSsrcs.length; i++) {- inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});+ var ssrc = simulcastSsrcs[i];+ delete sources[ssrc];- /* distance table */- sym = 0;- while (sym < 32) { state.lens[sym++] = 5; }+ // Remove all the groups that this SSRC participates in.+ mLine.ssrcGroups.forEach(function (relatedGroup) {+ if (relatedGroup.semantics === 'SIM') {+ return;+ }- inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});+ var relatedSsrcs = relatedGroup.ssrcs.split(' ');+ if (relatedSsrcs.indexOf(ssrc) === -1) {+ return;+ }- /* do this just once */- virgin = false;- }+ // Nuke all the related SSRCs.+ relatedSsrcs.forEach(function (relatedSSRC) {+ delete sources[relatedSSRC];+ });- state.lencode = lenfix;- state.lenbits = 9;- state.distcode = distfix;- state.distbits = 5;- }+ // Schedule the related group for nuking.+ relatedGroup.nuke = true;+ })+ }+ return;+ });- /*- Update the window with the last wsize (normally 32K) bytes written before- returning. If window does not exist yet, create it. This is only called- when a window is already in use, or when output has been written during this- inflate call, but the end of the deflate stream has not been reached yet.- It is also called to create a window for dictionary data when a dictionary- is loaded.+ mLine.ssrcs = writeSsrcs(sources);- Providing output buffers larger than 32K to inflate() should provide a speed- advantage, since only the last 32K of output is copied to the sliding window- upon return from inflate(), and since all distances after the first 32K of- output will fall in the output data, making match copies simpler and faster.- The advantage may be dependent on the size of the processor's data caches.- */- function updatewindow(strm, src, end, copy) {- var dist;- var state = strm.state;+ // Nuke all the scheduled groups.+ var i = mLine.ssrcGroups.length;+ while (i--) {+ if (mLine.ssrcGroups[i].nuke) {+ mLine.ssrcGroups.splice(i, 1);+ }+ }+ }- /* if it hasn't been done already, allocate space for the window */- if (state.window === null) {- state.wsize = 1 << state.wbits;- state.wnext = 0;- state.whave = 0;+ function removeGoogConference(mLine) {+ if (!mLine || !Array.isArray(mLine.invalid)) {+ return;+ }- state.window = new utils.Buf8(state.wsize);- }+ var i = mLine.invalid.length;+ while (i--) {+ if (mLine.invalid[i].value == 'x-google-flag:conference') {+ mLine.invalid.splice(i, 1);+ }+ }+ }- /* copy state->wsize or less output bytes into the circular window */- if (copy >= state.wsize) {- utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);- state.wnext = 0;- state.whave = state.wsize;- }- else {- dist = state.wsize - state.wnext;- if (dist > copy) {- dist = copy;+ function assertGoogConference(mLine) {+ if (!mLine) {+ return;}- //zmemcpy(state->window + state->wnext, end - copy, dist);- utils.arraySet(state.window,src, end - copy, dist, state.wnext);- copy -= dist;- if (copy) {- //zmemcpy(state->window, end - copy, copy);- utils.arraySet(state.window,src, end - copy, copy, 0);- state.wnext = copy;- state.whave = state.wsize;++ if (!Array.isArray(mLine.invalid)) {+ mLine.invalid = [];}- else {- state.wnext += dist;- if (state.wnext === state.wsize) { state.wnext = 0; }- if (state.whave < state.wsize) { state.whave += dist; }++ if (!mLine.invalid.some(+ function (i) { return i.value === 'x-google-flag:conference' })) {+ mLine.invalid.push({'value': 'x-google-flag:conference'});}- }- return 0;}- function inflate(strm, flush) {- var state;- var input, output; // input/output buffers- var next; /* next input INDEX */- var put; /* next output INDEX */- var have, left; /* available input and output */- var hold; /* bit buffer */- var bits; /* bits in bit buffer */- var _in, _out; /* save starting available input and output */- var copy; /* number of stored or match bytes to copy */- var from; /* where to copy match bytes from */- var from_source;- var here = 0; /* current decoding table entry */- var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)- //var last; /* parent table entry */- var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)- var len; /* length to copy for repeats, bits to drop */- var ret; /* return code */- var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */- var opts;+ //endregion- var n; // temporary var for NEED_BITS+ //region "Private" functions- var order = /* permutation of code lengths */- [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];+ /**+ *+ * @param mLine+ * @private+ */+ Simulcast.prototype._maybeInitializeLayers = function(mLine) {+ if (!mLine || mLine.type !== 'video') {+ return;+ }- if (!strm || !strm.state || !strm.output ||- (!strm.input && strm.avail_in !== 0)) {- return Z_STREAM_ERROR;- }+ var sources = parseSsrcs(mLine);- state = strm.state;- if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */+ if (Object.keys(sources).length === 0) {++ // no sources, disable simulcast.+ if (this.layers.length !== 0) {+ this.layers = [];+ }++ return;+ }++ // find the base layer (we'll reuse its msid and cname).+ var baseLayerSSRC = Object.keys(sources)[0];+ var baseLayer = sources[baseLayerSSRC];+ // todo(gp) handle screen sharing.- //--- LOAD() ---- put = strm.next_out;- output = strm.output;- left = strm.avail_out;- next = strm.next_in;- input = strm.input;- have = strm.avail_in;- hold = state.hold;- bits = state.bits;- //---+ // check if base CNAME has changed and reinitialise layers.+ if (this.layers.length > 0+ && sources[baseLayerSSRC].cname !== this.layers[0].cname) {+ this.layers = [];+ }- _in = have;- _out = left;- ret = Z_OK;+ // (re)initialise layers+ if (this.layers.length < 1) {- inf_leave: // goto emulation- for (;;) {- switch (state.mode) {- case HEAD:- if (state.wrap === 0) {- state.mode = TYPEDO;- break;- }- //=== NEEDBITS(16);- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */- state.check = 0/*crc32(0L, Z_NULL, 0)*/;- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//+ // first push the base layer.+ this.layers.push({+ ssrc: baseLayerSSRC,+ msid: baseLayer.msid,+ cname: baseLayer.cname+ });- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = FLAGS;- break;- }- state.flags = 0; /* expect zlib header */- if (state.head) {- state.head.done = false;- }- if (!(state.wrap & 1) || /* check if zlib header allowed */- (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {- strm.msg = 'incorrect header check';- state.mode = BAD;- break;- }- if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {- strm.msg = 'unknown compression method';- state.mode = BAD;- break;- }- //--- DROPBITS(4) ---//- hold >>>= 4;- bits -= 4;- //---//- len = (hold & 0x0f)/*BITS(4)*/ + 8;- if (state.wbits === 0) {- state.wbits = len;- }- else if (len > state.wbits) {- strm.msg = 'invalid window size';- state.mode = BAD;- break;- }- state.dmax = 1 << len;- //Tracev((stderr, "inflate: zlib header ok\n"));- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;- state.mode = hold & 0x200 ? DICTID : TYPE;- //=== INITBITS();- hold = 0;- bits = 0;- //===//- break;- case FLAGS:- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.flags = hold;- if ((state.flags & 0xff) !== Z_DEFLATED) {- strm.msg = 'unknown compression method';- state.mode = BAD;- break;- }- if (state.flags & 0xe000) {- strm.msg = 'unknown header flags set';- state.mode = BAD;- break;- }- if (state.head) {- state.head.text = ((hold >> 8) & 1);- }- if (state.flags & 0x0200) {- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = TIME;- /* falls through */- case TIME:- //=== NEEDBITS(32); */- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if (state.head) {- state.head.time = hold;- }- if (state.flags & 0x0200) {- //=== CRC4(state.check, hold)- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- hbuf[2] = (hold >>> 16) & 0xff;- hbuf[3] = (hold >>> 24) & 0xff;- state.check = crc32(state.check, hbuf, 4, 0);- //===- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = OS;- /* falls through */- case OS:- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if (state.head) {- state.head.xflags = (hold & 0xff);- state.head.os = (hold >> 8);- }- if (state.flags & 0x0200) {- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = EXLEN;- /* falls through */- case EXLEN:- if (state.flags & 0x0400) {- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.length = hold;- if (state.head) {- state.head.extra_len = hold;+ var rtx = false; // RFC 4588+ if (Array.isArray(mLine.rtp)) {+ rtx = mLine.rtp.some(+ function (rtpmap) { return rtpmap.codec === 'rtx'; });}- if (state.flags & 0x0200) {- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//++ if (rtx) {+ this.layers[0].rtx = generateSSRC();}- //=== INITBITS();- hold = 0;- bits = 0;- //===//- }- else if (state.head) {- state.head.extra = null/*Z_NULL*/;- }- state.mode = EXTRA;- /* falls through */- case EXTRA:- if (state.flags & 0x0400) {- copy = state.length;- if (copy > have) { copy = have; }- if (copy) {- if (state.head) {- len = state.head.extra_len - state.length;- if (!state.head.extra) {- // Use untyped array for more conveniend processing later- state.head.extra = new Array(state.head.extra_len);- }- utils.arraySet(- state.head.extra,- input,- next,- // extra field is limited to 65536 bytes- // - no need for additional size check- copy,- /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/- len- );- //zmemcpy(state.head.extra + len, next,- // len + copy > state.head.extra_max ?- // state.head.extra_max - len : copy);- }- if (state.flags & 0x0200) {- state.check = crc32(state.check, input, copy, next);- }- have -= copy;- next += copy;- state.length -= copy;++ // now push additional layers.+ for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {++ var layer = { ssrc: generateSSRC() };+ if (rtx) {+ layer.rtx = generateSSRC();+ }++ this.layers.push(layer);}- if (state.length) { break inf_leave; }- }- state.length = 0;- state.mode = NAME;- /* falls through */- case NAME:- if (state.flags & 0x0800) {- if (have === 0) { break inf_leave; }- copy = 0;- do {- // TODO: 2 or 1 bytes?- len = input[next + copy++];- /* use constant limit because in js we should not preallocate memory */- if (state.head && len &&- (state.length < 65536 /*state.head.name_max*/)) {- state.head.name += String.fromCharCode(len);- }- } while (len && copy < have);+ }+ };- if (state.flags & 0x0200) {- state.check = crc32(state.check, input, copy, next);+ /**+ *+ * @param mLine+ * @private+ */+ Simulcast.prototype._restoreSimulcastView = function(mLine) {+ if (mLine && mLine.type === 'video' && this.layers.length !== 0) {++ var sources = {};++ var msid = this.layers[0].msid;+ var cname = this.layers[0].cname;+ var simulcastSsrcs = [];+ var ssrcGroups = [];++ for (var i = 0; i < this.layers.length; i++) {+ var layer = this.layers[i];++ sources[layer.ssrc] = { msid: msid, cname: cname };+ simulcastSsrcs.push(layer.ssrc);++ if (layer.rtx) {++ sources[layer.rtx] = {+ msid: msid,+ cname: cname+ }++ ssrcGroups.push({+ semantics: 'FID',+ ssrcs: [layer.ssrc, layer.rtx].join(' ')+ });+ }}- have -= copy;- next += copy;- if (len) { break inf_leave; }- }- else if (state.head) {- state.head.name = null;- }- state.length = 0;- state.mode = COMMENT;- /* falls through */- case COMMENT:- if (state.flags & 0x1000) {- if (have === 0) { break inf_leave; }- copy = 0;- do {- len = input[next + copy++];- /* use constant limit because in js we should not preallocate memory */- if (state.head && len &&- (state.length < 65536 /*state.head.comm_max*/)) {- state.head.comment += String.fromCharCode(len);- }- } while (len && copy < have);- if (state.flags & 0x0200) {- state.check = crc32(state.check, input, copy, next);++ ssrcGroups.push({+ semantics: 'SIM',+ ssrcs: simulcastSsrcs.join(' ')+ });++ mLine.ssrcGroups = ssrcGroups;+ mLine.ssrcs = writeSsrcs(sources);+ }+ }++ //endregion++ //region "Public" functions++ Simulcast.prototype.isSupported = function () {+ return window.chrome;++ // TODO this needs improvements. For example I doubt that Chrome in Android+ // has simulcast support. Also, only recent versions of Chromium have native+ // simulcast support.+ }++ /**+ *+ * @param desc+ * @returns {RTCSessionDescription}+ */+ Simulcast.prototype.mungeRemoteDescription = function (desc) {++ if (!validateDescription(desc)) {+ return desc;+ }++ var session = transform.parse(desc.sdp);++ var self = this;+ processVideo(session, function (mLine) {++ // Handle simulcast reception.+ if (self.options.explodeRemoteSimulcast) {+ explodeRemoteSimulcast(mLine);+ } else {+ implodeRemoteSimulcast(mLine);}- have -= copy;- next += copy;- if (len) { break inf_leave; }- }- else if (state.head) {- state.head.comment = null;- }- state.mode = HCRC;- /* falls through */- case HCRC:- if (state.flags & 0x0200) {- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;++ // If native simulcast is enabled, we must append the x-goog-conference+ // attribute to the SDP.+ if (self.layers.length < 1) {+ removeGoogConference(mLine);+ } else {+ assertGoogConference(mLine);}- //===//- if (hold !== (state.check & 0xffff)) {- strm.msg = 'header crc mismatch';- state.mode = BAD;- break;+ });++ return new RTCSessionDescription({+ type: desc.type,+ sdp: transform.write(session)+ });+ };++ /**+ *+ * @param desc+ * @returns {RTCSessionDescription}+ */+ Simulcast.prototype.mungeLocalDescription = function (desc) {++ if (!validateDescription(desc) || !this.isSupported()) {+ return desc;+ }++ var session = transform.parse(desc.sdp);++ var self = this;+ processVideo(session, function (mLine) {+ if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')+ {+ return;}- //=== INITBITS();- hold = 0;- bits = 0;- //===//- }- if (state.head) {- state.head.hcrc = ((state.flags >> 9) & 1);- state.head.done = true;- }- strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;- state.mode = TYPE;- break;- case DICTID:- //=== NEEDBITS(32); */- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- strm.adler = state.check = ZSWAP32(hold);- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = DICT;- /* falls through */- case DICT:- if (state.havedict === 0) {- //--- RESTORE() ---- strm.next_out = put;- strm.avail_out = left;- strm.next_in = next;- strm.avail_in = have;- state.hold = hold;- state.bits = bits;- //---- return Z_NEED_DICT;- }- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;- state.mode = TYPE;- /* falls through */- case TYPE:- if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }- /* falls through */- case TYPEDO:- if (state.last) {- //--- BYTEBITS() ---//- hold >>>= bits & 7;- bits -= bits & 7;- //---//- state.mode = CHECK;- break;- }- //=== NEEDBITS(3); */- while (bits < 3) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;+ // Initialize native simulcast layers, if not already done.+ self._maybeInitializeLayers(mLine);++ // Update the SDP with the simulcast layers.+ self._restoreSimulcastView(mLine);+ });++ return new RTCSessionDescription({+ type: desc.type,+ sdp: transform.write(session)+ });+ };++ //endregion++ module.exports = Simulcast;+-},{"./transform-utils":76,"sdp-transform":78}],76:[function(require,module,exports){++},{"./transform-utils":77,"sdp-transform":79}],77:[function(require,module,exports){+ /* Copyright @ 2015 Atlassian Pty Ltd+ *+ * 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.+ */++ exports.writeSsrcs = function(sources, order) {+ var ssrcs = [];++ // expand sources to ssrcs+ if (typeof sources !== 'undefined' &&+ Object.keys(sources).length !== 0) {++ if (Array.isArray(order)) {+ for (var i = 0; i < order.length; i++) {+ var ssrc = order[i];+ var source = sources[ssrc];+ Object.keys(source).forEach(function (attribute) {+ ssrcs.push({+ id: ssrc,+ attribute: attribute,+ value: source[attribute]+ });+ });}- //===//- state.last = (hold & 0x01)/*BITS(1)*/;- //--- DROPBITS(1) ---//- hold >>>= 1;- bits -= 1;- //---//+ } else {+ Object.keys(sources).forEach(function (ssrc) {+ var source = sources[ssrc];+ Object.keys(source).forEach(function (attribute) {+ ssrcs.push({+ id: ssrc,+ attribute: attribute,+ value: source[attribute]+ });+ });+ });+ }+ }++ return ssrcs;+ };++ exports.parseSsrcs = function (mLine) {+ var sources = {};+ // group sources attributes by ssrc.+ if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {+ mLine.ssrcs.forEach(function (ssrc) {+ if (!sources[ssrc.id])+ sources[ssrc.id] = {};+ sources[ssrc.id][ssrc.attribute] = ssrc.value;+ });+ }+ return sources;+ };++-},{}],77:[function(require,module,exports){-arguments[4][71][0].apply(exports,arguments)-},{"dup":71}],78:[function(require,module,exports){-arguments[4][72][0].apply(exports,arguments)-},{"./parser":79,"./writer":80,"dup":72}],79:[function(require,module,exports){-arguments[4][73][0].apply(exports,arguments)-},{"./grammar":77,"dup":73}],80:[function(require,module,exports){-arguments[4][74][0].apply(exports,arguments)-},{"./grammar":77,"dup":74}],81:[function(require,module,exports){-arguments[4][71][0].apply(exports,arguments)-},{"dup":71}],82:[function(require,module,exports){++},{}],78:[function(require,module,exports){+ arguments[4][72][0].apply(exports,arguments)-},{"./parser":83,"./writer":84,"dup":72}],83:[function(require,module,exports){++},{"dup":72}],79:[function(require,module,exports){+ arguments[4][73][0].apply(exports,arguments)-},{"./grammar":81,"dup":73}],84:[function(require,module,exports){++},{"./parser":80,"./writer":81,"dup":73}],80:[function(require,module,exports){+ arguments[4][74][0].apply(exports,arguments)-},{"./grammar":81,"dup":74}],85:[function(require,module,exports){++},{"./grammar":78,"dup":74}],81:[function(require,module,exports){++arguments[4][75][0].apply(exports,arguments)++},{"./grammar":78,"dup":75}],82:[function(require,module,exports){++ module.exports = require('./lib/');+-},{"./lib/":86}],86:[function(require,module,exports){++},{"./lib/":83}],83:[function(require,module,exports){++ /**+ * Module dependencies.+ */++ var url = require('./url');+ var parser = require('socket.io-parser');+ var Manager = require('./manager');+ var debug = require('debug')('socket.io-client');++ /**+ * Module exports.+ */++ module.exports = exports = lookup;++ /**+ * Managers cache.+ */++ var cache = exports.managers = {};++ /**+ * Looks up an existing `Manager` for multiplexing.+ * If the user summons:+ *+ * `io('http://localhost/a');`+ * `io('http://localhost/b');`+ *+ * We reuse the existing instance based on same scheme/port/host,+ * and we initialize sockets for each namespace.+ *+ * @api public+ */++ function lookup(uri, opts) {+ if (typeof uri == 'object') {+ opts = uri;+ uri = undefined;+ }++ opts = opts || {};++ var parsed = url(uri);+ var source = parsed.source;+ var id = parsed.id;+ var io;++ if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {+ debug('ignoring socket cache for %s', source);+ io = Manager(source, opts);+ } else {+ if (!cache[id]) {+ debug('new io instance for %s', source);+ cache[id] = Manager(source, opts);+ }+ io = cache[id];+ }++ return io.socket(parsed.path);+ }++ /**+ * Protocol version.+ *+ * @api public+ */++ exports.protocol = parser.protocol;++ /**+ * `connect`.+ *+ * @param {String} uri+ * @api public+ */++ exports.connect = lookup;++ /**+ * Expose constructors for standalone build.+ *+ * @api public+ */++ exports.Manager = require('./manager');+ exports.Socket = require('./socket');+-},{"./manager":87,"./socket":89,"./url":90,"debug":94,"socket.io-parser":130}],87:[function(require,module,exports){++},{"./manager":84,"./socket":86,"./url":87,"debug":91,"socket.io-parser":127}],84:[function(require,module,exports){++ /**+ * Module dependencies.+ */++ var url = require('./url');+ var eio = require('engine.io-client');+ var Socket = require('./socket');+ var Emitter = require('component-emitter');+ var parser = require('socket.io-parser');+ var on = require('./on');+ var bind = require('component-bind');+ var object = require('object-component');+ var debug = require('debug')('socket.io-client:manager');+ var indexOf = require('indexof');+ var Backoff = require('backo2');++ /**+ * Module exports+ */++ module.exports = Manager;++ /**+ * `Manager` constructor.+ *+ * @param {String} engine instance or engine uri/opts+ * @param {Object} options+ * @api public+ */++ function Manager(uri, opts){+ if (!(this instanceof Manager)) return new Manager(uri, opts);+ if (uri && ('object' == typeof uri)) {+ opts = uri;+ uri = undefined;+ }+ opts = opts || {};++ opts.path = opts.path || '/socket.io';+ this.nsps = {};+ this.subs = [];+ this.opts = opts;+ this.reconnection(opts.reconnection !== false);+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);+ this.reconnectionDelay(opts.reconnectionDelay || 1000);+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);+ this.randomizationFactor(opts.randomizationFactor || 0.5);+ this.backoff = new Backoff({+ min: this.reconnectionDelay(),+ max: this.reconnectionDelayMax(),+ jitter: this.randomizationFactor()+ });+ this.timeout(null == opts.timeout ? 20000 : opts.timeout);+ this.readyState = 'closed';+ this.uri = uri;+ this.connected = [];+ this.encoding = false;+ this.packetBuffer = [];+ this.encoder = new parser.Encoder();+ this.decoder = new parser.Decoder();+ this.autoConnect = opts.autoConnect !== false;+ if (this.autoConnect) this.open();+ }++ /**+ * Propagate given event to sockets and emit on `this`+ *+ * @api private+ */++ Manager.prototype.emitAll = function() {+ this.emit.apply(this, arguments);+ for (var nsp in this.nsps) {+ this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);+ }+ };++ /**+ * Update `socket.id` of all sockets+ *+ * @api private+ */++ Manager.prototype.updateSocketIds = function(){+ for (var nsp in this.nsps) {+ this.nsps[nsp].id = this.engine.id;+ }+ };++ /**+ * Mix in `Emitter`.+ */- switch ((hold & 0x03)/*BITS(2)*/) {- case 0: /* stored block */- //Tracev((stderr, "inflate: stored block%s\n",- // state.last ? " (last)" : ""));- state.mode = STORED;- break;- case 1: /* fixed block */- fixedtables(state);- //Tracev((stderr, "inflate: fixed codes block%s\n",- // state.last ? " (last)" : ""));- state.mode = LEN_; /* decode codes */- if (flush === Z_TREES) {- //--- DROPBITS(2) ---//- hold >>>= 2;- bits -= 2;- //---//- break inf_leave;- }- break;- case 2: /* dynamic block */- //Tracev((stderr, "inflate: dynamic codes block%s\n",- // state.last ? " (last)" : ""));- state.mode = TABLE;- break;- case 3:- strm.msg = 'invalid block type';- state.mode = BAD;- }- //--- DROPBITS(2) ---//- hold >>>= 2;- bits -= 2;- //---//- break;- case STORED:- //--- BYTEBITS() ---// /* go to byte boundary */- hold >>>= bits & 7;- bits -= bits & 7;- //---//- //=== NEEDBITS(32); */- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {- strm.msg = 'invalid stored block lengths';- state.mode = BAD;- break;- }- state.length = hold & 0xffff;- //Tracev((stderr, "inflate: stored length %u\n",- // state.length));- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = COPY_;- if (flush === Z_TREES) { break inf_leave; }- /* falls through */- case COPY_:- state.mode = COPY;- /* falls through */- case COPY:- copy = state.length;- if (copy) {- if (copy > have) { copy = have; }- if (copy > left) { copy = left; }- if (copy === 0) { break inf_leave; }- //--- zmemcpy(put, next, copy); ---- utils.arraySet(output, input, next, copy, put);- //---//- have -= copy;- next += copy;- left -= copy;- put += copy;- state.length -= copy;- break;- }- //Tracev((stderr, "inflate: stored end\n"));- state.mode = TYPE;- break;- case TABLE:- //=== NEEDBITS(14); */- while (bits < 14) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;- //--- DROPBITS(5) ---//- hold >>>= 5;- bits -= 5;- //---//- state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;- //--- DROPBITS(5) ---//- hold >>>= 5;- bits -= 5;- //---//- state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;- //--- DROPBITS(4) ---//- hold >>>= 4;- bits -= 4;- //---//- //#ifndef PKZIP_BUG_WORKAROUND- if (state.nlen > 286 || state.ndist > 30) {- strm.msg = 'too many length or distance symbols';- state.mode = BAD;- break;- }- //#endif- //Tracev((stderr, "inflate: table sizes ok\n"));- state.have = 0;- state.mode = LENLENS;- /* falls through */- case LENLENS:- while (state.have < state.ncode) {- //=== NEEDBITS(3);- while (bits < 3) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);- //--- DROPBITS(3) ---//- hold >>>= 3;- bits -= 3;- //---//- }- while (state.have < 19) {- state.lens[order[state.have++]] = 0;- }- // We have separate tables & no pointers. 2 commented lines below not needed.- //state.next = state.codes;- //state.lencode = state.next;- // Switch to use dynamic table- state.lencode = state.lendyn;- state.lenbits = 7;+ Emitter(Manager.prototype);++ /**+ * Sets the `reconnection` config.+ *+ * @param {Boolean} true/false if it should automatically reconnect+ * @return {Manager} self or value+ * @api public+ */++ Manager.prototype.reconnection = function(v){+ if (!arguments.length) return this._reconnection;+ this._reconnection = !!v;+ return this;+ };++ /**+ * Sets the reconnection attempts config.+ *+ * @param {Number} max reconnection attempts before giving up+ * @return {Manager} self or value+ * @api public+ */++ Manager.prototype.reconnectionAttempts = function(v){+ if (!arguments.length) return this._reconnectionAttempts;+ this._reconnectionAttempts = v;+ return this;+ };++ /**+ * Sets the delay between reconnections.+ *+ * @param {Number} delay+ * @return {Manager} self or value+ * @api public+ */++ Manager.prototype.reconnectionDelay = function(v){+ if (!arguments.length) return this._reconnectionDelay;+ this._reconnectionDelay = v;+ this.backoff && this.backoff.setMin(v);+ return this;+ };++ Manager.prototype.randomizationFactor = function(v){+ if (!arguments.length) return this._randomizationFactor;+ this._randomizationFactor = v;+ this.backoff && this.backoff.setJitter(v);+ return this;+ };++ /**+ * Sets the maximum delay between reconnections.+ *+ * @param {Number} delay+ * @return {Manager} self or value+ * @api public+ */++ Manager.prototype.reconnectionDelayMax = function(v){+ if (!arguments.length) return this._reconnectionDelayMax;+ this._reconnectionDelayMax = v;+ this.backoff && this.backoff.setMax(v);+ return this;+ };++ /**+ * Sets the connection timeout. `false` to disable+ *+ * @return {Manager} self or value+ * @api public+ */++ Manager.prototype.timeout = function(v){+ if (!arguments.length) return this._timeout;+ this._timeout = v;+ return this;+ };++ /**+ * Starts trying to reconnect if reconnection is enabled and we have not+ * started reconnecting yet+ *+ * @api private+ */++ Manager.prototype.maybeReconnectOnOpen = function() {+ // Only try to reconnect if it's the first time we're connecting+ if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {+ // keeps reconnection from firing twice for the same reconnection loop+ this.reconnect();+ }+ };+++ /**+ * Sets the current transport `socket`.+ *+ * @param {Function} optional, callback+ * @return {Manager} self+ * @api public+ */++ Manager.prototype.open =+ Manager.prototype.connect = function(fn){+ debug('readyState %s', this.readyState);+ if (~this.readyState.indexOf('open')) return this;++ debug('opening %s', this.uri);+ this.engine = eio(this.uri, this.opts);+ var socket = this.engine;+ var self = this;+ this.readyState = 'opening';+ this.skipReconnect = false;- opts = {bits: state.lenbits};- ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);- state.lenbits = opts.bits;+ // emit `open`+ var openSub = on(socket, 'open', function() {+ self.onopen();+ fn && fn();+ });- if (ret) {- strm.msg = 'invalid code lengths set';- state.mode = BAD;- break;- }- //Tracev((stderr, "inflate: code lengths ok\n"));- state.have = 0;- state.mode = CODELENS;- /* falls through */- case CODELENS:- while (state.have < state.nlen + state.ndist) {- for (;;) {- here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ // emit `connect_error`+ var errorSub = on(socket, 'error', function(data){+ debug('connect_error');+ self.cleanup();+ self.readyState = 'closed';+ self.emitAll('connect_error', data);+ if (fn) {+ var err = new Error('Connection error');+ err.data = data;+ fn(err);+ } else {+ // Only do this if there is no fn to handle the error+ self.maybeReconnectOnOpen();+ }+ });- if ((here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- if (here_val < 16) {- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- state.lens[state.have++] = here_val;- }- else {- if (here_val === 16) {- //=== NEEDBITS(here.bits + 2);- n = here_bits + 2;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- if (state.have === 0) {- strm.msg = 'invalid bit length repeat';- state.mode = BAD;- break;- }- len = state.lens[state.have - 1];- copy = 3 + (hold & 0x03);//BITS(2);- //--- DROPBITS(2) ---//- hold >>>= 2;- bits -= 2;- //---//- }- else if (here_val === 17) {- //=== NEEDBITS(here.bits + 3);- n = here_bits + 3;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- len = 0;- copy = 3 + (hold & 0x07);//BITS(3);- //--- DROPBITS(3) ---//- hold >>>= 3;- bits -= 3;- //---//- }- else {- //=== NEEDBITS(here.bits + 7);- n = here_bits + 7;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- len = 0;- copy = 11 + (hold & 0x7f);//BITS(7);- //--- DROPBITS(7) ---//- hold >>>= 7;- bits -= 7;- //---//- }- if (state.have + copy > state.nlen + state.ndist) {- strm.msg = 'invalid bit length repeat';- state.mode = BAD;- break;- }- while (copy--) {- state.lens[state.have++] = len;- }- }- }+ // emit `connect_timeout`+ if (false !== this._timeout) {+ var timeout = this._timeout;+ debug('connect attempt will timeout after %d', timeout);- /* handle error breaks in while */- if (state.mode === BAD) { break; }+ // set timer+ var timer = setTimeout(function(){+ debug('connect attempt timed out after %d', timeout);+ openSub.destroy();+ socket.close();+ socket.emit('error', 'timeout');+ self.emitAll('connect_timeout', timeout);+ }, timeout);- /* check for end-of-block code (better have one) */- if (state.lens[256] === 0) {- strm.msg = 'invalid code -- missing end-of-block';- state.mode = BAD;- break;+ this.subs.push({+ destroy: function(){+ clearTimeout(timer);}+ });+ }- /* build code tables -- note: do not change the lenbits or distbits- values here (9 and 6) without reading the comments in inftrees.h- concerning the ENOUGH constants, which depend on those values */- state.lenbits = 9;+ this.subs.push(openSub);+ this.subs.push(errorSub);- opts = {bits: state.lenbits};- ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);- // We have separate tables & no pointers. 2 commented lines below not needed.- // state.next_index = opts.table_index;- state.lenbits = opts.bits;- // state.lencode = state.next;+ return this;+ };- if (ret) {- strm.msg = 'invalid literal/lengths set';- state.mode = BAD;- break;- }+ /**+ * Called upon transport open.+ *+ * @api private+ */- state.distbits = 6;- //state.distcode.copy(state.codes);- // Switch to use dynamic table- state.distcode = state.distdyn;- opts = {bits: state.distbits};- ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);- // We have separate tables & no pointers. 2 commented lines below not needed.- // state.next_index = opts.table_index;- state.distbits = opts.bits;- // state.distcode = state.next;+ Manager.prototype.onopen = function(){+ debug('open');- if (ret) {- strm.msg = 'invalid distances set';- state.mode = BAD;- break;- }- //Tracev((stderr, 'inflate: codes ok\n'));- state.mode = LEN_;- if (flush === Z_TREES) { break inf_leave; }- /* falls through */- case LEN_:- state.mode = LEN;- /* falls through */- case LEN:- if (have >= 6 && left >= 258) {- //--- RESTORE() ---- strm.next_out = put;- strm.avail_out = left;- strm.next_in = next;- strm.avail_in = have;- state.hold = hold;- state.bits = bits;- //---- inflate_fast(strm, _out);- //--- LOAD() ---- put = strm.next_out;- output = strm.output;- left = strm.avail_out;- next = strm.next_in;- input = strm.input;- have = strm.avail_in;- hold = state.hold;- bits = state.bits;- //---+ // clear old subs+ this.cleanup();- if (state.mode === TYPE) {- state.back = -1;- }- break;- }- state.back = 0;- for (;;) {- here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ // mark as open+ this.readyState = 'open';+ this.emit('open');++ // add new subs+ var socket = this.engine;+ this.subs.push(on(socket, 'data', bind(this, 'ondata')));+ this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));+ this.subs.push(on(socket, 'error', bind(this, 'onerror')));+ this.subs.push(on(socket, 'close', bind(this, 'onclose')));+ };++ /**+ * Called with data.+ *+ * @api private+ */- if (here_bits <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- if (here_op && (here_op & 0xf0) === 0) {- last_bits = here_bits;- last_op = here_op;- last_val = here_val;- for (;;) {- here = state.lencode[last_val +- ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ Manager.prototype.ondata = function(data){+ this.decoder.add(data);+ };- if ((last_bits + here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- //--- DROPBITS(last.bits) ---//- hold >>>= last_bits;- bits -= last_bits;- //---//- state.back += last_bits;- }- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- state.back += here_bits;- state.length = here_val;- if (here_op === 0) {- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?- // "inflate: literal '%c'\n" :- // "inflate: literal 0x%02x\n", here.val));- state.mode = LIT;- break;- }- if (here_op & 32) {- //Tracevv((stderr, "inflate: end of block\n"));- state.back = -1;- state.mode = TYPE;- break;- }- if (here_op & 64) {- strm.msg = 'invalid literal/length code';- state.mode = BAD;- break;- }- state.extra = here_op & 15;- state.mode = LENEXT;- /* falls through */- case LENEXT:- if (state.extra) {- //=== NEEDBITS(state.extra);- n = state.extra;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;- //--- DROPBITS(state.extra) ---//- hold >>>= state.extra;- bits -= state.extra;- //---//- state.back += state.extra;- }- //Tracevv((stderr, "inflate: length %u\n", state.length));- state.was = state.length;- state.mode = DIST;- /* falls through */- case DIST:- for (;;) {- here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ /**+ * Called when parser fully decodes a packet.+ *+ * @api private+ */- if ((here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- if ((here_op & 0xf0) === 0) {- last_bits = here_bits;- last_op = here_op;- last_val = here_val;- for (;;) {- here = state.distcode[last_val +- ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ Manager.prototype.ondecoded = function(packet) {+ this.emit('packet', packet);+ };- if ((last_bits + here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- //--- DROPBITS(last.bits) ---//- hold >>>= last_bits;- bits -= last_bits;- //---//- state.back += last_bits;- }- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- state.back += here_bits;- if (here_op & 64) {- strm.msg = 'invalid distance code';- state.mode = BAD;- break;- }- state.offset = here_val;- state.extra = (here_op) & 15;- state.mode = DISTEXT;- /* falls through */- case DISTEXT:- if (state.extra) {- //=== NEEDBITS(state.extra);- n = state.extra;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;- //--- DROPBITS(state.extra) ---//- hold >>>= state.extra;- bits -= state.extra;- //---//- state.back += state.extra;- }- //#ifdef INFLATE_STRICT- if (state.offset > state.dmax) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break;- }- //#endif- //Tracevv((stderr, "inflate: distance %u\n", state.offset));- state.mode = MATCH;- /* falls through */- case MATCH:- if (left === 0) { break inf_leave; }- copy = _out - left;- if (state.offset > copy) { /* copy from window */- copy = state.offset - copy;- if (copy > state.whave) {- if (state.sane) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break;- }- // (!) This block is disabled in zlib defailts,- // don't enable it for binary compatibility- //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR- // Trace((stderr, "inflate.c too far\n"));- // copy -= state.whave;- // if (copy > state.length) { copy = state.length; }- // if (copy > left) { copy = left; }- // left -= copy;- // state.length -= copy;- // do {- // output[put++] = 0;- // } while (--copy);- // if (state.length === 0) { state.mode = LEN; }- // break;- //#endif- }- if (copy > state.wnext) {- copy -= state.wnext;- from = state.wsize - copy;- }- else {- from = state.wnext - copy;- }- if (copy > state.length) { copy = state.length; }- from_source = state.window;- }- else { /* copy from output */- from_source = output;- from = put - state.offset;- copy = state.length;- }- if (copy > left) { copy = left; }- left -= copy;- state.length -= copy;- do {- output[put++] = from_source[from++];- } while (--copy);- if (state.length === 0) { state.mode = LEN; }- break;- case LIT:- if (left === 0) { break inf_leave; }- output[put++] = state.length;- left--;- state.mode = LEN;- break;- case CHECK:- if (state.wrap) {- //=== NEEDBITS(32);- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- // Use '|' insdead of '+' to make sure that result is signed- hold |= input[next++] << bits;- bits += 8;- }- //===//- _out -= left;- strm.total_out += _out;- state.total += _out;- if (_out) {- strm.adler = state.check =- /*UPDATE(state.check, put - _out, _out);*/- (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));+ /**+ * Called upon socket error.+ *+ * @api private+ */- }- _out = left;- // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too- if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {- strm.msg = 'incorrect data check';- state.mode = BAD;- break;- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- //Tracev((stderr, "inflate: check matches trailer\n"));- }- state.mode = LENGTH;- /* falls through */- case LENGTH:- if (state.wrap && state.flags) {- //=== NEEDBITS(32);- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if (hold !== (state.total & 0xffffffff)) {- strm.msg = 'incorrect length check';- state.mode = BAD;- break;- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- //Tracev((stderr, "inflate: length matches trailer\n"));+ Manager.prototype.onerror = function(err){+ debug('error', err);+ this.emitAll('error', err);+ };++ /**+ * Creates a new socket for the given `nsp`.+ *+ * @return {Socket}+ * @api public+ */++ Manager.prototype.socket = function(nsp){+ var socket = this.nsps[nsp];+ if (!socket) {+ socket = new Socket(this, nsp);+ this.nsps[nsp] = socket;+ var self = this;+ socket.on('connect', function(){+ socket.id = self.engine.id;+ if (!~indexOf(self.connected, socket)) {+ self.connected.push(socket);}- state.mode = DONE;- /* falls through */- case DONE:- ret = Z_STREAM_END;- break inf_leave;- case BAD:- ret = Z_DATA_ERROR;- break inf_leave;- case MEM:- return Z_MEM_ERROR;- case SYNC:- /* falls through */- default:- return Z_STREAM_ERROR;- }+ });}+ return socket;+ };- // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"+ /**+ * Called upon a socket close.+ *+ * @param {Socket} socket+ */- /*- Return from inflate(), updating the total counts and the check value.- If there was no progress during the inflate() call, return a buffer- error. Call updatewindow() to create and/or update the window state.- Note: a memory error from inflate() is non-recoverable.- */+ Manager.prototype.destroy = function(socket){+ var index = indexOf(this.connected, socket);+ if (~index) this.connected.splice(index, 1);+ if (this.connected.length) return;- //--- RESTORE() ---- strm.next_out = put;- strm.avail_out = left;- strm.next_in = next;- strm.avail_in = have;- state.hold = hold;- state.bits = bits;- //---+ this.close();+ };- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&- (state.mode < CHECK || flush !== Z_FINISH))) {- if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {- state.mode = MEM;- return Z_MEM_ERROR;- }+ /**+ * Writes a packet.+ *+ * @param {Object} packet+ * @api private+ */++ Manager.prototype.packet = function(packet){+ debug('writing packet %j', packet);+ var self = this;++ if (!self.encoding) {+ // encode, then write to engine with result+ self.encoding = true;+ this.encoder.encode(packet, function(encodedPackets) {+ for (var i = 0; i < encodedPackets.length; i++) {+ self.engine.write(encodedPackets[i]);+ }+ self.encoding = false;+ self.processPacketQueue();+ });+ } else { // add packet to the queue+ self.packetBuffer.push(packet);}- _in -= strm.avail_in;- _out -= strm.avail_out;- strm.total_in += _in;- strm.total_out += _out;- state.total += _out;- if (state.wrap && _out) {- strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/- (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));+ };++ /**+ * If packet buffer is non-empty, begins encoding the+ * next packet in line.+ *+ * @api private+ */++ Manager.prototype.processPacketQueue = function() {+ if (this.packetBuffer.length > 0 && !this.encoding) {+ var pack = this.packetBuffer.shift();+ this.packet(pack);}- strm.data_type = state.bits + (state.last ? 64 : 0) +- (state.mode === TYPE ? 128 : 0) +- (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);- if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {- ret = Z_BUF_ERROR;+ };++ /**+ * Clean up transport subscriptions and packet buffer.+ *+ * @api private+ */++ Manager.prototype.cleanup = function(){+ var sub;+ while (sub = this.subs.shift()) sub.destroy();++ this.packetBuffer = [];+ this.encoding = false;++ this.decoder.destroy();+ };++ /**+ * Close the current socket.+ *+ * @api private+ */++ Manager.prototype.close =+ Manager.prototype.disconnect = function(){+ this.skipReconnect = true;+ this.backoff.reset();+ this.readyState = 'closed';+ this.engine && this.engine.close();+ };++ /**+ * Called upon engine close.+ *+ * @api private+ */++ Manager.prototype.onclose = function(reason){+ debug('close');+ this.cleanup();+ this.backoff.reset();+ this.readyState = 'closed';+ this.emit('close', reason);+ if (this._reconnection && !this.skipReconnect) {+ this.reconnect();}- return ret;- }+ };++ /**+ * Attempt a reconnection.+ *+ * @api private+ */++ Manager.prototype.reconnect = function(){+ if (this.reconnecting || this.skipReconnect) return this;++ var self = this;++ if (this.backoff.attempts >= this._reconnectionAttempts) {+ debug('reconnect failed');+ this.backoff.reset();+ this.emitAll('reconnect_failed');+ this.reconnecting = false;+ } else {+ var delay = this.backoff.duration();+ debug('will wait %dms before reconnect attempt', delay);++ this.reconnecting = true;+ var timer = setTimeout(function(){+ if (self.skipReconnect) return;++ debug('attempting reconnect');+ self.emitAll('reconnect_attempt', self.backoff.attempts);+ self.emitAll('reconnecting', self.backoff.attempts);++ // check again for the case socket closed in above events+ if (self.skipReconnect) return;++ self.open(function(err){+ if (err) {+ debug('reconnect attempt error');+ self.reconnecting = false;+ self.reconnect();+ self.emitAll('reconnect_error', err.data);+ } else {+ debug('reconnect success');+ self.onreconnect();+ }+ });+ }, delay);++ this.subs.push({+ destroy: function(){+ clearTimeout(timer);+ }+ });+ }+ };- function inflateEnd(strm) {+ /**+ * Called upon successful reconnect.+ *+ * @api private+ */- if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {- return Z_STREAM_ERROR;- }+ Manager.prototype.onreconnect = function(){+ var attempt = this.backoff.attempts;+ this.reconnecting = false;+ this.backoff.reset();+ this.updateSocketIds();+ this.emitAll('reconnect', attempt);+ };- var state = strm.state;- if (state.window) {- state.window = null;- }- strm.state = null;- return Z_OK;- }-},{"./on":88,"./socket":89,"./url":90,"backo2":91,"component-bind":92,"component-emitter":93,"debug":94,"engine.io-client":95,"indexof":126,"object-component":127,"socket.io-parser":130}],88:[function(require,module,exports){++},{"./on":85,"./socket":86,"./url":87,"backo2":88,"component-bind":89,"component-emitter":90,"debug":91,"engine.io-client":92,"indexof":123,"object-component":124,"socket.io-parser":127}],85:[function(require,module,exports){- function inflateGetHeader(strm, head) {- var state;+ /**+ * Module exports.+ */- /* check state */- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;- if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }+ module.exports = on;- /* save header structure */- state.head = head;- head.done = false;- return Z_OK;+ /**+ * Helper for subscriptions.+ *+ * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`+ * @param {String} event name+ * @param {Function} callback+ * @api public+ */++ function on(obj, ev, fn) {+ obj.on(ev, fn);+ return {+ destroy: function(){+ obj.removeListener(ev, fn);+ }+ };}-},{}],89:[function(require,module,exports){++},{}],86:[function(require,module,exports){- exports.inflateReset = inflateReset;- exports.inflateReset2 = inflateReset2;- exports.inflateResetKeep = inflateResetKeep;- exports.inflateInit = inflateInit;- exports.inflateInit2 = inflateInit2;- exports.inflate = inflate;- exports.inflateEnd = inflateEnd;- exports.inflateGetHeader = inflateGetHeader;- exports.inflateInfo = 'pako inflate (from Nodeca project)';+ /**+ * Module dependencies.+ */- /* Not implemented- exports.inflateCopy = inflateCopy;- exports.inflateGetDictionary = inflateGetDictionary;- exports.inflateMark = inflateMark;- exports.inflatePrime = inflatePrime;- exports.inflateSetDictionary = inflateSetDictionary;- exports.inflateSync = inflateSync;- exports.inflateSyncPoint = inflateSyncPoint;- exports.inflateUndermine = inflateUndermine;- */+ var parser = require('socket.io-parser');+ var Emitter = require('component-emitter');+ var toArray = require('to-array');+ var on = require('./on');+ var bind = require('component-bind');+ var debug = require('debug')('socket.io-client:socket');+ var hasBin = require('has-binary');- },{"../utils/common":87,"./adler32":89,"./crc32":91,"./inffast":94,"./inftrees":96}],96:[function(require,module,exports){- 'use strict';+ /**+ * Module exports.+ */+ module.exports = exports = Socket;- var utils = require('../utils/common');+ /**+ * Internal events (blacklisted).+ * These events can't be emitted by the user.+ *+ * @api private+ */- var MAXBITS = 15;- var ENOUGH_LENS = 852;- var ENOUGH_DISTS = 592;- //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);+ var events = {+ connect: 1,+ connect_error: 1,+ connect_timeout: 1,+ disconnect: 1,+ error: 1,+ reconnect: 1,+ reconnect_attempt: 1,+ reconnect_failed: 1,+ reconnect_error: 1,+ reconnecting: 1+ };- var CODES = 0;- var LENS = 1;- var DISTS = 2;+ /**+ * Shortcut to `Emitter#emit`.+ */- var lbase = [ /* Length codes 257..285 base */- 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,- 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0- ];+ var emit = Emitter.prototype.emit;- var lext = [ /* Length codes 257..285 extra */- 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78- ];+ /**+ * `Socket` constructor.+ *+ * @api public+ */- var dbase = [ /* Distance codes 0..29 base */- 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,- 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,- 8193, 12289, 16385, 24577, 0, 0- ];+ function Socket(io, nsp){+ this.io = io;+ this.nsp = nsp;+ this.json = this; // compat+ this.ids = 0;+ this.acks = {};+ if (this.io.autoConnect) this.open();+ this.receiveBuffer = [];+ this.sendBuffer = [];+ this.connected = false;+ this.disconnected = true;+ }- var dext = [ /* Distance codes 0..29 extra */- 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,- 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,- 28, 28, 29, 29, 64, 64- ];+ /**+ * Mix in `Emitter`.+ */- module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)- {- var bits = opts.bits;- //here = opts.here; /* table entry for duplication */+ Emitter(Socket.prototype);- var len = 0; /* a code's length in bits */- var sym = 0; /* index of code symbols */- var min = 0, max = 0; /* minimum and maximum code lengths */- var root = 0; /* number of index bits for root table */- var curr = 0; /* number of index bits for current table */- var drop = 0; /* code bits to drop for sub-table */- var left = 0; /* number of prefix codes available */- var used = 0; /* code entries in table used */- var huff = 0; /* Huffman code */- var incr; /* for incrementing code, index */- var fill; /* index for replicating entries */- var low; /* low bits for current root entry */- var mask; /* mask for low root bits */- var next; /* next available space in table */- var base = null; /* base value table to use */- var base_index = 0;- // var shoextra; /* extra bits table to use */- var end; /* use base and extra for symbol > end */- var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */- var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */- var extra = null;- var extra_index = 0;+ /**+ * Subscribe to open, close and packet events+ *+ * @api private+ */- var here_bits, here_op, here_val;+ Socket.prototype.subEvents = function() {+ if (this.subs) return;- /*- Process a set of code lengths to create a canonical Huffman code. The- code lengths are lens[0..codes-1]. Each length corresponds to the- symbols 0..codes-1. The Huffman code is generated by first sorting the- symbols by length from short to long, and retaining the symbol order- for codes with equal lengths. Then the code starts with all zero bits- for the first code of the shortest length, and the codes are integer- increments for the same length, and zeros are appended as the length- increases. For the deflate format, these bits are stored backwards- from their more natural integer increment ordering, and so when the- decoding tables are built in the large loop below, the integer codes- are incremented backwards.+ var io = this.io;+ this.subs = [+ on(io, 'open', bind(this, 'onopen')),+ on(io, 'packet', bind(this, 'onpacket')),+ on(io, 'close', bind(this, 'onclose'))+ ];+ };- This routine assumes, but does not check, that all of the entries in- lens[] are in the range 0..MAXBITS. The caller must assure this.- 1..MAXBITS is interpreted as that code length. zero means that that- symbol does not occur in this code.+ /**+ * "Opens" the socket.+ *+ * @api public+ */- The codes are sorted by computing a count of codes for each length,- creating from that a table of starting indices for each length in the- sorted table, and then entering the symbols in order in the sorted- table. The sorted table is work[], with that space being provided by- the caller.+ Socket.prototype.open =+ Socket.prototype.connect = function(){+ if (this.connected) return this;- The length counts are used for other purposes as well, i.e. finding- the minimum and maximum length codes, determining if there are any- codes at all, checking for a valid set of lengths, and looking ahead- at length counts to determine sub-table sizes when building the- decoding tables.- */+ this.subEvents();+ this.io.open(); // ensure open+ if ('open' == this.io.readyState) this.onopen();+ return this;+ };++ /**+ * Sends a `message` event.+ *+ * @return {Socket} self+ * @api public+ */++ Socket.prototype.send = function(){+ var args = toArray(arguments);+ args.unshift('message');+ this.emit.apply(this, args);+ return this;+ };++ /**+ * Override `emit`.+ * If the event is in `events`, it's emitted normally.+ *+ * @param {String} event name+ * @return {Socket} self+ * @api public+ */- /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */- for (len = 0; len <= MAXBITS; len++) {- count[len] = 0;- }- for (sym = 0; sym < codes; sym++) {- count[lens[lens_index + sym]]++;+ Socket.prototype.emit = function(ev){+ if (events.hasOwnProperty(ev)) {+ emit.apply(this, arguments);+ return this;}- /* bound code lengths, force root to be within code lengths */- root = bits;- for (max = MAXBITS; max >= 1; max--) {- if (count[max] !== 0) { break; }+ var args = toArray(arguments);+ var parserType = parser.EVENT; // default+ if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary+ var packet = { type: parserType, data: args };++ // event ack callback+ if ('function' == typeof args[args.length - 1]) {+ debug('emitting packet with ack id %d', this.ids);+ this.acks[this.ids] = args.pop();+ packet.id = this.ids++;}- if (root > max) {- root = max;++ if (this.connected) {+ this.packet(packet);+ } else {+ this.sendBuffer.push(packet);}- if (max === 0) { /* no symbols to code at all */- //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */- //table.bits[opts.table_index] = 1; //here.bits = (var char)1;- //table.val[opts.table_index++] = 0; //here.val = (var short)0;- table[table_index++] = (1 << 24) | (64 << 16) | 0;+ return this;+ };- //table.op[opts.table_index] = 64;- //table.bits[opts.table_index] = 1;- //table.val[opts.table_index++] = 0;- table[table_index++] = (1 << 24) | (64 << 16) | 0;+ /**+ * Sends a packet.+ *+ * @param {Object} packet+ * @api private+ */- opts.bits = 1;- return 0; /* no symbols, but wait for decoding to report error */- }- for (min = 1; min < max; min++) {- if (count[min] !== 0) { break; }- }- if (root < min) {- root = min;- }+ Socket.prototype.packet = function(packet){+ packet.nsp = this.nsp;+ this.io.packet(packet);+ };- /* check for an over-subscribed or incomplete set of lengths */- left = 1;- for (len = 1; len <= MAXBITS; len++) {- left <<= 1;- left -= count[len];- if (left < 0) {- return -1;- } /* over-subscribed */- }- if (left > 0 && (type === CODES || max !== 1)) {- return -1; /* incomplete set */- }+ /**+ * Called upon engine `open`.+ *+ * @api private+ */- /* generate offsets into symbol table for each length for sorting */- offs[1] = 0;- for (len = 1; len < MAXBITS; len++) {- offs[len + 1] = offs[len] + count[len];- }+ Socket.prototype.onopen = function(){+ debug('transport is open - connecting');- /* sort symbols by length, by symbol order within each length */- for (sym = 0; sym < codes; sym++) {- if (lens[lens_index + sym] !== 0) {- work[offs[lens[lens_index + sym]]++] = sym;- }+ // write connect packet if necessary+ if ('/' != this.nsp) {+ this.packet({ type: parser.CONNECT });}+ };- /*- Create and fill in decoding tables. In this loop, the table being- filled is at next and has curr index bits. The code being used is huff- with length len. That code is converted to an index by dropping drop- bits off of the bottom. For codes where len is less than drop + curr,- those top drop + curr - len bits are incremented through all values to- fill the table with replicated entries.+ /**+ * Called upon engine `close`.+ *+ * @param {String} reason+ * @api private+ */- root is the number of index bits for the root table. When len exceeds- root, sub-tables are created pointed to by the root entry with an index- of the low root bits of huff. This is saved in low to check for when a- new sub-table should be started. drop is zero when the root table is- being filled, and drop is root when sub-tables are being filled.+ Socket.prototype.onclose = function(reason){+ debug('close (%s)', reason);+ this.connected = false;+ this.disconnected = true;+ delete this.id;+ this.emit('disconnect', reason);+ };- When a new sub-table is needed, it is necessary to look ahead in the- code lengths to determine what size sub-table is needed. The length- counts are used for this, and so count[] is decremented as codes are- entered in the tables.+ /**+ * Called with socket packet.+ *+ * @param {Object} packet+ * @api private+ */- used keeps track of how many table entries have been allocated from the- provided *table space. It is checked for LENS and DIST tables against- the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in- the initial root table size constants. See the comments in inftrees.h- for more information.+ Socket.prototype.onpacket = function(packet){+ if (packet.nsp != this.nsp) return;- sym increments through all symbols, and the loop terminates when- all codes of length max, i.e. all codes, have been processed. This- routine permits incomplete codes, so another loop after this one fills- in the rest of the decoding tables with invalid code markers.- */+ switch (packet.type) {+ case parser.CONNECT:+ this.onconnect();+ break;- /* set up for code type */- // poor man optimization - use if-else instead of switch,- // to avoid deopts in old v8- if (type === CODES) {- base = extra = work; /* dummy value--not used */- end = 19;+ case parser.EVENT:+ this.onevent(packet);+ break;- } else if (type === LENS) {- base = lbase;- base_index -= 257;- extra = lext;- extra_index -= 257;- end = 256;+ case parser.BINARY_EVENT:+ this.onevent(packet);+ break;- } else { /* DISTS */- base = dbase;- extra = dext;- end = -1;+ case parser.ACK:+ this.onack(packet);+ break;++ case parser.BINARY_ACK:+ this.onack(packet);+ break;++ case parser.DISCONNECT:+ this.ondisconnect();+ break;++ case parser.ERROR:+ this.emit('error', packet.data);+ break;}+ };- /* initialize opts for loop */- huff = 0; /* starting code */- sym = 0; /* starting code symbol */- len = min; /* starting code length */- next = table_index; /* current table to fill in */- curr = root; /* current table index bits */- drop = 0; /* current bits to drop from code for index */- low = -1; /* trigger new sub-table when len > root */- used = 1 << root; /* use root table entries */- mask = used - 1; /* mask for comparing low */+ /**+ * Called upon a server event.+ *+ * @param {Object} packet+ * @api private+ */- /* check available table space */- if ((type === LENS && used > ENOUGH_LENS) ||- (type === DISTS && used > ENOUGH_DISTS)) {- return 1;+ Socket.prototype.onevent = function(packet){+ var args = packet.data || [];+ debug('emitting event %j', args);++ if (null != packet.id) {+ debug('attaching ack callback to event');+ args.push(this.ack(packet.id));}- var i=0;- /* process all codes and make table entries */- for (;;) {- i++;- /* create table entry */- here_bits = len - drop;- if (work[sym] < end) {- here_op = 0;- here_val = work[sym];- }- else if (work[sym] > end) {- here_op = extra[extra_index + work[sym]];- here_val = base[base_index + work[sym]];- }- else {- here_op = 32 + 64; /* end of block */- here_val = 0;- }+ if (this.connected) {+ emit.apply(this, args);+ } else {+ this.receiveBuffer.push(args);+ }+ };- /* replicate for those indices with low len bits equal to huff */- incr = 1 << (len - drop);- fill = 1 << curr;- min = fill; /* save offset to next table */- do {- fill -= incr;- table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;- } while (fill !== 0);+ /**+ * Produces an ack callback to emit with an event.+ *+ * @api private+ */++ Socket.prototype.ack = function(id){+ var self = this;+ var sent = false;+ return function(){+ // prevent double callbacks+ if (sent) return;+ sent = true;+ var args = toArray(arguments);+ debug('sending ack %j', args);- /* backwards increment the len-bit code huff */- incr = 1 << (len - 1);- while (huff & incr) {- incr >>= 1;- }- if (incr !== 0) {- huff &= incr - 1;- huff += incr;- } else {- huff = 0;- }+ var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;+ self.packet({+ type: type,+ id: id,+ data: args+ });+ };+ };- /* go to next symbol, update count, len */- sym++;- if (--count[len] === 0) {- if (len === max) { break; }- len = lens[lens_index + work[sym]];- }+ /**+ * Called upon a server acknowlegement.+ *+ * @param {Object} packet+ * @api private+ */- /* create new sub-table if needed */- if (len > root && (huff & mask) !== low) {- /* if first time, transition to sub-tables */- if (drop === 0) {- drop = root;- }+ Socket.prototype.onack = function(packet){+ debug('calling ack %s with %j', packet.id, packet.data);+ var fn = this.acks[packet.id];+ fn.apply(this, packet.data);+ delete this.acks[packet.id];+ };- /* increment past last table */- next += min; /* here min is 1 << curr */+ /**+ * Called upon server connect.+ *+ * @api private+ */- /* determine length of next table */- curr = len - drop;- left = 1 << curr;- while (curr + drop < max) {- left -= count[curr + drop];- if (left <= 0) { break; }- curr++;- left <<= 1;- }+ Socket.prototype.onconnect = function(){+ this.connected = true;+ this.disconnected = false;+ this.emit('connect');+ this.emitBuffered();+ };- /* check for enough space */- used += 1 << curr;- if ((type === LENS && used > ENOUGH_LENS) ||- (type === DISTS && used > ENOUGH_DISTS)) {- return 1;- }+ /**+ * Emit buffered events (received and emitted).+ *+ * @api private+ */- /* point entry in root table to sub-table */- low = huff & mask;- /*table.op[low] = curr;- table.bits[low] = root;- table.val[low] = next - opts.table_index;*/- table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;- }+ Socket.prototype.emitBuffered = function(){+ var i;+ for (i = 0; i < this.receiveBuffer.length; i++) {+ emit.apply(this, this.receiveBuffer[i]);}+ this.receiveBuffer = [];- /* fill in remaining table entry if code is incomplete (guaranteed to have- at most one remaining entry, since if the code is incomplete, the- maximum code length that was allowed to get this far is one bit) */- if (huff !== 0) {- //table.op[next + huff] = 64; /* invalid code marker */- //table.bits[next + huff] = len - drop;- //table.val[next + huff] = 0;- table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;+ for (i = 0; i < this.sendBuffer.length; i++) {+ this.packet(this.sendBuffer[i]);}-- /* set return parameters */- //opts.table_index += used;- opts.bits = root;- return 0;+ this.sendBuffer = [];};- },{"../utils/common":87}],97:[function(require,module,exports){- 'use strict';+ /**+ * Called upon server disconnect.+ *+ * @api private+ */- module.exports = {- '2': 'need dictionary', /* Z_NEED_DICT 2 */- '1': 'stream end', /* Z_STREAM_END 1 */- '0': '', /* Z_OK 0 */- '-1': 'file error', /* Z_ERRNO (-1) */- '-2': 'stream error', /* Z_STREAM_ERROR (-2) */- '-3': 'data error', /* Z_DATA_ERROR (-3) */- '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */- '-5': 'buffer error', /* Z_BUF_ERROR (-5) */- '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */+ Socket.prototype.ondisconnect = function(){+ debug('server disconnect (%s)', this.nsp);+ this.destroy();+ this.onclose('io server disconnect');};- },{}],98:[function(require,module,exports){- 'use strict';-+ /**+ * Called upon forced client/server side disconnections,+ * this method ensures the manager stops tracking us and+ * that reconnections don't get triggered for this.+ *+ * @api private.+ */- var utils = require('../utils/common');+ Socket.prototype.destroy = function(){+ if (this.subs) {+ // clean subscriptions to avoid reconnections+ for (var i = 0; i < this.subs.length; i++) {+ this.subs[i].destroy();+ }+ this.subs = null;+ }- /* Public constants ==========================================================*/- /* ===========================================================================*/+ this.io.destroy(this);+ };+ /**+ * Disconnects the socket manually.+ *+ * @return {Socket} self+ * @api public+ */- //var Z_FILTERED = 1;- //var Z_HUFFMAN_ONLY = 2;- //var Z_RLE = 3;- var Z_FIXED = 4;- //var Z_DEFAULT_STRATEGY = 0;+ Socket.prototype.close =+ Socket.prototype.disconnect = function(){+ if (this.connected) {+ debug('performing disconnect (%s)', this.nsp);+ this.packet({ type: parser.DISCONNECT });+ }- /* Possible values of the data_type field (though see inflate()) */- var Z_BINARY = 0;- var Z_TEXT = 1;- //var Z_ASCII = 1; // = Z_TEXT- var Z_UNKNOWN = 2;+ // remove socket from pool+ this.destroy();- /*============================================================================*/+ if (this.connected) {+ // fire events+ this.onclose('io client disconnect');+ }+ return this;+ };-},{"./on":88,"component-bind":92,"component-emitter":93,"debug":94,"has-binary":124,"socket.io-parser":130,"to-array":134}],90:[function(require,module,exports){++},{"./on":85,"component-bind":89,"component-emitter":90,"debug":91,"has-binary":121,"socket.io-parser":127,"to-array":131}],87:[function(require,module,exports){+ (function (global){- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }+ /**+ * Module dependencies.+ */- // From zutil.h+ var parseuri = require('parseuri');+ var debug = require('debug')('socket.io-client:url');- var STORED_BLOCK = 0;- var STATIC_TREES = 1;- var DYN_TREES = 2;- /* The three kinds of block type */+ /**+ * Module exports.+ */- var MIN_MATCH = 3;- var MAX_MATCH = 258;- /* The minimum and maximum match lengths */+ module.exports = url;- // From deflate.h- /* ===========================================================================- * Internal compression state.+ /**+ * URL parser.+ *+ * @param {String} url+ * @param {Object} An object meant to mimic window.location.+ * Defaults to window.location.+ * @api public*/- var LENGTH_CODES = 29;- /* number of length codes, not counting the special END_BLOCK code */+ function url(uri, loc){+ var obj = uri;- var LITERALS = 256;- /* number of literal bytes 0..255 */+ // default to window.location+ var loc = loc || global.location;+ if (null == uri) uri = loc.protocol + '//' + loc.host;- var L_CODES = LITERALS + 1 + LENGTH_CODES;- /* number of Literal or Length codes, including the END_BLOCK code */+ // relative path support+ if ('string' == typeof uri) {+ if ('/' == uri.charAt(0)) {+ if ('/' == uri.charAt(1)) {+ uri = loc.protocol + uri;+ } else {+ uri = loc.hostname + uri;+ }+ }++ if (!/^(https?|wss?):\/\//.test(uri)) {+ debug('protocol-less url %s', uri);+ if ('undefined' != typeof loc) {+ uri = loc.protocol + '//' + uri;+ } else {+ uri = 'https://' + uri;+ }+ }++ // parse+ debug('parse %s', uri);+ obj = parseuri(uri);+ }++ // make sure we treat `localhost:80` and `localhost` equally+ if (!obj.port) {+ if (/^(http|ws)$/.test(obj.protocol)) {+ obj.port = '80';+ }+ else if (/^(http|ws)s$/.test(obj.protocol)) {+ obj.port = '443';+ }+ }- var D_CODES = 30;- /* number of distance codes */+ obj.path = obj.path || '/';- var BL_CODES = 19;- /* number of codes used to transfer the bit lengths */+ // define unique id+ obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;+ // define href+ obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));- var HEAP_SIZE = 2*L_CODES + 1;- /* maximum heap size */+ return obj;+ }- var MAX_BITS = 15;- /* All codes must not exceed MAX_BITS bits */+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"debug":94,"parseuri":128}],91:[function(require,module,exports){++},{"debug":91,"parseuri":125}],88:[function(require,module,exports){- var Buf_size = 16;- /* size of bit buffer in bi_buf */+ /**+ * Expose `Backoff`.+ */+ module.exports = Backoff;- /* ===========================================================================- * Constants+ /**+ * Initialize backoff timer with `opts`.+ *+ * - `min` initial timeout in milliseconds [100]+ * - `max` max timeout [10000]+ * - `jitter` [0]+ * - `factor` [2]+ *+ * @param {Object} opts+ * @api public*/- var MAX_BL_BITS = 7;- /* Bit length codes must not exceed MAX_BL_BITS bits */-- var END_BLOCK = 256;- /* end of block literal code */+ function Backoff(opts) {+ opts = opts || {};+ this.ms = opts.min || 100;+ this.max = opts.max || 10000;+ this.factor = opts.factor || 2;+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;+ this.attempts = 0;+ }- var REP_3_6 = 16;- /* repeat previous bit length 3-6 times (2 bits of repeat count) */+ /**+ * Return the backoff duration.+ *+ * @return {Number}+ * @api public+ */- var REPZ_3_10 = 17;- /* repeat a zero length 3-10 times (3 bits of repeat count) */+ Backoff.prototype.duration = function(){+ var ms = this.ms * Math.pow(this.factor, this.attempts++);+ if (this.jitter) {+ var rand = Math.random();+ var deviation = Math.floor(rand * this.jitter * ms);+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;+ }+ return Math.min(ms, this.max) | 0;+ };- var REPZ_11_138 = 18;- /* repeat a zero length 11-138 times (7 bits of repeat count) */+ /**+ * Reset the number of attempts.+ *+ * @api public+ */- var extra_lbits = /* extra bits for each length code */- [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];+ Backoff.prototype.reset = function(){+ this.attempts = 0;+ };- var extra_dbits = /* extra bits for each distance code */- [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];+ /**+ * Set the minimum duration+ *+ * @api public+ */- var extra_blbits = /* extra bits for each bit length code */- [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];+ Backoff.prototype.setMin = function(min){+ this.ms = min;+ };- var bl_order =- [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];- /* The lengths of the bit length codes are sent in order of decreasing- * probability, to avoid transmitting the lengths for unused bit length codes.+ /**+ * Set the maximum duration+ *+ * @api public*/- /* ===========================================================================- * Local data. These are initialized only once.+ Backoff.prototype.setMax = function(max){+ this.max = max;+ };++ /**+ * Set the jitter+ *+ * @api public*/- // We pre-fill arrays with 0 to avoid uninitialized gaps+ Backoff.prototype.setJitter = function(jitter){+ this.jitter = jitter;+ };- var DIST_CODE_LEN = 512; /* see definition of array dist_code below */- // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1- var static_ltree = new Array((L_CODES+2) * 2);- zero(static_ltree);- /* The static literal tree. Since the bit lengths are imposed, there is no- * need for the L_CODES extra codes used during heap construction. However- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init- * below).-},{}],92:[function(require,module,exports){++},{}],89:[function(require,module,exports){+ /**+ * Slice reference.*/- var static_dtree = new Array(D_CODES * 2);- zero(static_dtree);- /* The static distance tree. (Actually a trivial tree since all codes use- * 5 bits.)- */+ var slice = [].slice;- var _dist_code = new Array(DIST_CODE_LEN);- zero(_dist_code);- /* Distance codes. The first 256 values correspond to the distances- * 3 .. 258, the last 256 values correspond to the top 8 bits of- * the 15 bit distances.+ /**+ * Bind `obj` to `fn`.+ *+ * @param {Object} obj+ * @param {Function|String} fn or string+ * @return {Function}+ * @api public*/- var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);- zero(_length_code);- /* length code for each normalized match length (0 == MIN_MATCH) */-- var base_length = new Array(LENGTH_CODES);- zero(base_length);- /* First normalized length for each code (0 = MIN_MATCH) */+ module.exports = function(obj, fn){+ if ('string' == typeof fn) fn = obj[fn];+ if ('function' != typeof fn) throw new Error('bind() requires a function');+ var args = slice.call(arguments, 2);+ return function(){+ return fn.apply(obj, args.concat(slice.call(arguments)));+ }+ };- var base_dist = new Array(D_CODES);- zero(base_dist);- /* First normalized distance for each code (0 = distance of 1) */-},{}],93:[function(require,module,exports){++},{}],90:[function(require,module,exports){+ /**+ * Expose `Emitter`.+ */- var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {+ module.exports = Emitter;- this.static_tree = static_tree; /* static tree or NULL */- this.extra_bits = extra_bits; /* extra bits for each code or NULL */- this.extra_base = extra_base; /* base index for extra_bits */- this.elems = elems; /* max number of elements in the tree */- this.max_length = max_length; /* max bit length for the codes */+ /**+ * Initialize a new `Emitter`.+ *+ * @api public+ */- // show if `static_tree` has data or dummy - needed for monomorphic objects- this.has_stree = static_tree && static_tree.length;+ function Emitter(obj) {+ if (obj) return mixin(obj);};+ /**+ * Mixin the emitter properties.+ *+ * @param {Object} obj+ * @return {Object}+ * @api private+ */- var static_l_desc;- var static_d_desc;- var static_bl_desc;+ function mixin(obj) {+ for (var key in Emitter.prototype) {+ obj[key] = Emitter.prototype[key];+ }+ return obj;+ }+ /**+ * Listen on the given `event` with `fn`.+ *+ * @param {String} event+ * @param {Function} fn+ * @return {Emitter}+ * @api public+ */- var TreeDesc = function(dyn_tree, stat_desc) {- this.dyn_tree = dyn_tree; /* the dynamic tree */- this.max_code = 0; /* largest code with non zero frequency */- this.stat_desc = stat_desc; /* the corresponding static tree */+ Emitter.prototype.on =+ Emitter.prototype.addEventListener = function(event, fn){+ this._callbacks = this._callbacks || {};+ (this._callbacks[event] = this._callbacks[event] || [])+ .push(fn);+ return this;};--- function d_code(dist) {- return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];- }--- /* ===========================================================================- * Output a short LSB first on the stream.- * IN assertion: there is enough room in pendingBuf.+ /**+ * Adds an `event` listener that will be invoked a single+ * time then automatically removed.+ *+ * @param {String} event+ * @param {Function} fn+ * @return {Emitter}+ * @api public*/- function put_short (s, w) {- // put_byte(s, (uch)((w) & 0xff));- // put_byte(s, (uch)((ush)(w) >> 8));- s.pending_buf[s.pending++] = (w) & 0xff;- s.pending_buf[s.pending++] = (w >>> 8) & 0xff;- }+ Emitter.prototype.once = function(event, fn){+ var self = this;+ this._callbacks = this._callbacks || {};- /* ===========================================================================- * Send a value on a given number of bits.- * IN assertion: length <= 16 and value fits in length bits.- */- function send_bits(s, value, length) {- if (s.bi_valid > (Buf_size - length)) {- s.bi_buf |= (value << s.bi_valid) & 0xffff;- put_short(s, s.bi_buf);- s.bi_buf = value >> (Buf_size - s.bi_valid);- s.bi_valid += length - Buf_size;- } else {- s.bi_buf |= (value << s.bi_valid) & 0xffff;- s.bi_valid += length;+ function on() {+ self.off(event, on);+ fn.apply(this, arguments);}- }--- function send_code(s, c, tree) {- send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);- }+ on.fn = fn;+ this.on(event, on);+ return this;+ };- /* ===========================================================================- * Reverse the first len bits of a code, using straightforward code (a faster- * method would use a table)- * IN assertion: 1 <= len <= 15+ /**+ * Remove the given callback for `event` or all+ * registered callbacks.+ *+ * @param {String} event+ * @param {Function} fn+ * @return {Emitter}+ * @api public*/- function bi_reverse(code, len) {- var res = 0;- do {- res |= code & 1;- code >>>= 1;- res <<= 1;- } while (--len > 0);- return res >>> 1;- }+ Emitter.prototype.off =+ Emitter.prototype.removeListener =+ Emitter.prototype.removeAllListeners =+ Emitter.prototype.removeEventListener = function(event, fn){+ this._callbacks = this._callbacks || {};++ // all+ if (0 == arguments.length) {+ this._callbacks = {};+ return this;+ }- /* ===========================================================================- * Flush the bit buffer, keeping at most 7 bits in it.- */- function bi_flush(s) {- if (s.bi_valid === 16) {- put_short(s, s.bi_buf);- s.bi_buf = 0;- s.bi_valid = 0;+ // specific event+ var callbacks = this._callbacks[event];+ if (!callbacks) return this;- } else if (s.bi_valid >= 8) {- s.pending_buf[s.pending++] = s.bi_buf & 0xff;- s.bi_buf >>= 8;- s.bi_valid -= 8;+ // remove all handlers+ if (1 == arguments.length) {+ delete this._callbacks[event];+ return this;}- }+ // remove specific handler+ var cb;+ for (var i = 0; i < callbacks.length; i++) {+ cb = callbacks[i];+ if (cb === fn || cb.fn === fn) {+ callbacks.splice(i, 1);+ break;+ }+ }+ return this;+ };- /* ===========================================================================- * Compute the optimal bit lengths for a tree and update the total bit length- * for the current block.- * IN assertion: the fields freq and dad are set, heap[heap_max] and- * above are the tree nodes sorted by increasing frequency.- * OUT assertions: the field len is set to the optimal bit length, the- * array bl_count contains the frequencies for each bit length.- * The length opt_len is updated; static_len is also updated if stree is- * not null.+ /**+ * Emit `event` with the given args.+ *+ * @param {String} event+ * @param {Mixed} ...+ * @return {Emitter}*/- function gen_bitlen(s, desc)- // deflate_state *s;- // tree_desc *desc; /* the tree descriptor */- {- var tree = desc.dyn_tree;- var max_code = desc.max_code;- var stree = desc.stat_desc.static_tree;- var has_stree = desc.stat_desc.has_stree;- var extra = desc.stat_desc.extra_bits;- var base = desc.stat_desc.extra_base;- var max_length = desc.stat_desc.max_length;- var h; /* heap index */- var n, m; /* iterate over the tree elements */- var bits; /* bit length */- var xbits; /* extra bits */- var f; /* frequency */- var overflow = 0; /* number of elements with bit length too large */- for (bits = 0; bits <= MAX_BITS; bits++) {- s.bl_count[bits] = 0;+ Emitter.prototype.emit = function(event){+ this._callbacks = this._callbacks || {};+ var args = [].slice.call(arguments, 1)+ , callbacks = this._callbacks[event];++ if (callbacks) {+ callbacks = callbacks.slice(0);+ for (var i = 0, len = callbacks.length; i < len; ++i) {+ callbacks[i].apply(this, args);+ }}- /* In a first pass, compute the optimal bit lengths (which may- * overflow in the case of the bit length tree).- */- tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */+ return this;+ };- for (h = s.heap_max+1; h < HEAP_SIZE; h++) {- n = s.heap[h];- bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;- if (bits > max_length) {- bits = max_length;- overflow++;- }- tree[n*2 + 1]/*.Len*/ = bits;- /* We overwrite tree[n].Dad which is no longer needed */+ /**+ * Return array of callbacks for `event`.+ *+ * @param {String} event+ * @return {Array}+ * @api public+ */- if (n > max_code) { continue; } /* not a leaf node */+ Emitter.prototype.listeners = function(event){+ this._callbacks = this._callbacks || {};+ return this._callbacks[event] || [];+ };- s.bl_count[bits]++;- xbits = 0;- if (n >= base) {- xbits = extra[n-base];- }- f = tree[n * 2]/*.Freq*/;- s.opt_len += f * (bits + xbits);- if (has_stree) {- s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);- }- }- if (overflow === 0) { return; }+ /**+ * Check if this emitter has `event` handlers.+ *+ * @param {String} event+ * @return {Boolean}+ * @api public+ */- // Trace((stderr,"\nbit length overflow\n"));- /* This happens for example on obj2 and pic of the Calgary corpus */+ Emitter.prototype.hasListeners = function(event){+ return !! this.listeners(event).length;+ };- /* Find the first bit length which could increase: */- do {- bits = max_length-1;- while (s.bl_count[bits] === 0) { bits--; }- s.bl_count[bits]--; /* move one leaf down the tree */- s.bl_count[bits+1] += 2; /* move one overflow item as its brother */- s.bl_count[max_length]--;- /* The brother of the overflow item also moves one step up,- * but this does not affect bl_count[max_length]- */- overflow -= 2;- } while (overflow > 0);-},{}],94:[function(require,module,exports){++},{}],91:[function(require,module,exports){- /* Now recompute all bit lengths, scanning in increasing frequency.- * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all- * lengths instead of fixing only the wrong ones. This idea is taken- * from 'ar' written by Haruhiko Okumura.)- */- for (bits = max_length; bits !== 0; bits--) {- n = s.bl_count[bits];- while (n !== 0) {- m = s.heap[--h];- if (m > max_code) { continue; }- if (tree[m*2 + 1]/*.Len*/ !== bits) {- // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));- s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;- tree[m*2 + 1]/*.Len*/ = bits;- }- n--;- }- }- }+ /**+ * Expose `debug()` as the module.+ */+ module.exports = debug;- /* ===========================================================================- * Generate the codes for a given tree and bit counts (which need not be- * optimal).- * IN assertion: the array bl_count contains the bit length statistics for- * the given tree and the field len is set for all tree elements.- * OUT assertion: the field code is set for all tree elements of non- * zero code length.+ /**+ * Create a debugger with the given `name`.+ *+ * @param {String} name+ * @return {Type}+ * @api public*/- function gen_codes(tree, max_code, bl_count)- // ct_data *tree; /* the tree to decorate */- // int max_code; /* largest code with non zero frequency */- // ushf *bl_count; /* number of codes at each bit length */- {- var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */- var code = 0; /* running code value */- var bits; /* bit index */- var n; /* code index */- /* The distribution counts are first used to generate the code values- * without bit reversal.- */- for (bits = 1; bits <= MAX_BITS; bits++) {- next_code[bits] = code = (code + bl_count[bits-1]) << 1;- }- /* Check that the bit counts in bl_count are consistent. The last code- * must be all ones.- */- //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,- // "inconsistent bit counts");- //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));+ function debug(name) {+ if (!debug.enabled(name)) return function(){};- for (n = 0; n <= max_code; n++) {- var len = tree[n*2 + 1]/*.Len*/;- if (len === 0) { continue; }- /* Now reverse the bits */- tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);+ return function(fmt){+ fmt = coerce(fmt);++ var curr = new Date;+ var ms = curr - (debug[name] || curr);+ debug[name] = curr;++ fmt = name+ + ' '+ + fmt+ + ' +' + debug.humanize(ms);- //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",- // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));+ // This hackery is required for IE8+ // where `console.log` doesn't have 'apply'+ window.console+ && console.log+ && Function.prototype.apply.call(console.log, console, arguments);}}+ /**+ * The currently active debug mode names.+ */++ debug.names = [];+ debug.skips = [];- /* ===========================================================================- * Initialize the various 'constant' tables.+ /**+ * Enables a debug mode by name. This can include modes+ * separated by a colon and wildcards.+ *+ * @param {String} name+ * @api public*/- function tr_static_init() {- var n; /* iterates over tree elements */- var bits; /* bit counter */- var length; /* length value */- var code; /* code value */- var dist; /* distance index */- var bl_count = new Array(MAX_BITS+1);- /* number of codes at each bit length for an optimal tree */- // do check in _tr_init()- //if (static_init_done) return;+ debug.enable = function(name) {+ try {+ localStorage.debug = name;+ } catch(e){}- /* For some embedded targets, global variables are not initialized: */- /*#ifdef NO_INIT_GLOBAL_POINTERS- static_l_desc.static_tree = static_ltree;- static_l_desc.extra_bits = extra_lbits;- static_d_desc.static_tree = static_dtree;- static_d_desc.extra_bits = extra_dbits;- static_bl_desc.extra_bits = extra_blbits;- #endif*/+ var split = (name || '').split(/[\s,]+/)+ , len = split.length;- /* Initialize the mapping length (0..255) -> length code (0..28) */- length = 0;- for (code = 0; code < LENGTH_CODES-1; code++) {- base_length[code] = length;- for (n = 0; n < (1<<extra_lbits[code]); n++) {- _length_code[length++] = code;+ for (var i = 0; i < len; i++) {+ name = split[i].replace('*', '.*?');+ if (name[0] === '-') {+ debug.skips.push(new RegExp('^' + name.substr(1) + '$'));+ }+ else {+ debug.names.push(new RegExp('^' + name + '$'));}}- //Assert (length == 256, "tr_static_init: length != 256");- /* Note that the length 255 (match length 258) can be represented- * in two different ways: code 284 + 5 bits or code 285, so we- * overwrite length_code[255] to use the best encoding:- */- _length_code[length-1] = code;+ };- /* Initialize the mapping dist (0..32K) -> dist code (0..29) */- dist = 0;- for (code = 0 ; code < 16; code++) {- base_dist[code] = dist;- for (n = 0; n < (1<<extra_dbits[code]); n++) {- _dist_code[dist++] = code;+ /**+ * Disable debug output.+ *+ * @api public+ */++ debug.disable = function(){+ debug.enable('');+ };++ /**+ * Humanize the given `ms`.+ *+ * @param {Number} m+ * @return {String}+ * @api private+ */++ debug.humanize = function(ms) {+ var sec = 1000+ , min = 60 * 1000+ , hour = 60 * min;++ if (ms >= hour) return (ms / hour).toFixed(1) + 'h';+ if (ms >= min) return (ms / min).toFixed(1) + 'm';+ if (ms >= sec) return (ms / sec | 0) + 's';+ return ms + 'ms';+ };++ /**+ * Returns true if the given mode name is enabled, false otherwise.+ *+ * @param {String} name+ * @return {Boolean}+ * @api public+ */++ debug.enabled = function(name) {+ for (var i = 0, len = debug.skips.length; i < len; i++) {+ if (debug.skips[i].test(name)) {+ return false;}}- //Assert (dist == 256, "tr_static_init: dist != 256");- dist >>= 7; /* from now on, all distances are divided by 128 */- for (; code < D_CODES; code++) {- base_dist[code] = dist << 7;- for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {- _dist_code[256 + dist++] = code;+ for (var i = 0, len = debug.names.length; i < len; i++) {+ if (debug.names[i].test(name)) {+ return true;}}- //Assert (dist == 256, "tr_static_init: 256+dist != 512");+ return false;+ };- /* Construct the codes of the static literal tree */- for (bits = 0; bits <= MAX_BITS; bits++) {- bl_count[bits] = 0;- }+ /**+ * Coerce `val`.+ */- n = 0;- while (n <= 143) {- static_ltree[n*2 + 1]/*.Len*/ = 8;- n++;- bl_count[8]++;- }- while (n <= 255) {- static_ltree[n*2 + 1]/*.Len*/ = 9;- n++;- bl_count[9]++;- }- while (n <= 279) {- static_ltree[n*2 + 1]/*.Len*/ = 7;- n++;- bl_count[7]++;- }- while (n <= 287) {- static_ltree[n*2 + 1]/*.Len*/ = 8;- n++;- bl_count[8]++;- }- /* Codes 286 and 287 do not exist, but we must include them in the- * tree construction to get a canonical Huffman tree (longest code- * all ones)- */- gen_codes(static_ltree, L_CODES+1, bl_count);+ function coerce(val) {+ if (val instanceof Error) return val.stack || val.message;+ return val;+ }- /* The static distance tree is trivial: */- for (n = 0; n < D_CODES; n++) {- static_dtree[n*2 + 1]/*.Len*/ = 5;- static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);- }+ // persist- // Now data ready and we can init static trees- static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);- static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);- static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);+ try {+ if (window.localStorage) debug.enable(localStorage.debug);+ } catch(e){}- //static_init_done = true;- }-},{}],95:[function(require,module,exports){++},{}],92:[function(require,module,exports){+ module.exports = require('./lib/');- /* ===========================================================================- * Initialize a new block.-},{"./lib/":96}],96:[function(require,module,exports){++},{"./lib/":93}],93:[function(require,module,exports){++ module.exports = require('./socket');++ /**+ * Exports parser+ *+ * @api public+ **/- function init_block(s) {- var n; /* iterates over tree elements */+ module.exports.parser = require('engine.io-parser');- /* Initialize the trees. */- for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }- for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }- for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }-},{"./socket":97,"engine.io-parser":109}],97:[function(require,module,exports){++},{"./socket":94,"engine.io-parser":106}],94:[function(require,module,exports){+ (function (global){+ /**+ * Module dependencies.+ */- s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;- s.opt_len = s.static_len = 0;- s.last_lit = s.matches = 0;- }+ var transports = require('./transports');+ var Emitter = require('component-emitter');+ var debug = require('debug')('engine.io-client:socket');+ var index = require('indexof');+ var parser = require('engine.io-parser');+ var parseuri = require('parseuri');+ var parsejson = require('parsejson');+ var parseqs = require('parseqs');+ /**+ * Module exports.+ */- /* ===========================================================================- * Flush the bit buffer and align the output on a byte boundary+ module.exports = Socket;++ /**+ * Noop function.+ *+ * @api private*/- function bi_windup(s)- {- if (s.bi_valid > 8) {- put_short(s, s.bi_buf);- } else if (s.bi_valid > 0) {- //put_byte(s, (Byte)s->bi_buf);- s.pending_buf[s.pending++] = s.bi_buf;- }- s.bi_buf = 0;- s.bi_valid = 0;- }- /* ===========================================================================- * Copy a stored block, storing first the length and its- * one's complement if requested.+ function noop(){}++ /**+ * Socket constructor.+ *+ * @param {String|Object} uri or options+ * @param {Object} options+ * @api public*/- function copy_block(s, buf, len, header)- //DeflateState *s;- //charf *buf; /* the input data */- //unsigned len; /* its length */- //int header; /* true if block header must be written */- {- bi_windup(s); /* align on byte boundary */- if (header) {- put_short(s, len);- put_short(s, ~len);+ function Socket(uri, opts){+ if (!(this instanceof Socket)) return new Socket(uri, opts);++ opts = opts || {};++ if (uri && 'object' == typeof uri) {+ opts = uri;+ uri = null;}- // while (len--) {- // put_byte(s, *buf++);- // }- utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);- s.pending += len;- }- /* ===========================================================================- * Compares to subtrees, using the tree depth as tie breaker when- * the subtrees have equal frequency. This minimizes the worst case length.- */- function smaller(tree, n, m, depth) {- var _n2 = n*2;- var _m2 = m*2;- return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||- (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));- }+ if (uri) {+ uri = parseuri(uri);+ opts.host = uri.host;+ opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';+ opts.port = uri.port;+ if (uri.query) opts.query = uri.query;+ }- /* ===========================================================================- * Restore the heap property by moving down the tree starting at node k,- * exchanging a node with the smallest of its two sons if necessary, stopping- * when the heap property is re-established (each father smaller than its- * two sons).- */- function pqdownheap(s, tree, k)- // deflate_state *s;- // ct_data *tree; /* the tree to restore */- // int k; /* node to move down */- {- var v = s.heap[k];- var j = k << 1; /* left son of k */- while (j <= s.heap_len) {- /* Set j to the smallest of the two sons: */- if (j < s.heap_len &&- smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {- j++;+ this.secure = null != opts.secure ? opts.secure :+ (global.location && 'https:' == location.protocol);++ if (opts.host) {+ var pieces = opts.host.split(':');+ opts.hostname = pieces.shift();+ if (pieces.length) {+ opts.port = pieces.pop();+ } else if (!opts.port) {+ // if no port is specified manually, use the protocol default+ opts.port = this.secure ? '443' : '80';}- /* Exit if v is smaller than both sons */- if (smaller(tree, v, s.heap[j], s.depth)) { break; }+ }- /* Exchange v with the smallest son */- s.heap[k] = s.heap[j];- k = j;+ this.agent = opts.agent || false;+ this.hostname = opts.hostname ||+ (global.location ? location.hostname : 'localhost');+ this.port = opts.port || (global.location && location.port ?+ location.port :+ (this.secure ? 443 : 80));+ this.query = opts.query || {};+ if ('string' == typeof this.query) this.query = parseqs.decode(this.query);+ this.upgrade = false !== opts.upgrade;+ this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';+ this.forceJSONP = !!opts.forceJSONP;+ this.jsonp = false !== opts.jsonp;+ this.forceBase64 = !!opts.forceBase64;+ this.enablesXDR = !!opts.enablesXDR;+ this.timestampParam = opts.timestampParam || 't';+ this.timestampRequests = opts.timestampRequests;+ this.transports = opts.transports || ['polling', 'websocket'];+ this.readyState = '';+ this.writeBuffer = [];+ this.callbackBuffer = [];+ this.policyPort = opts.policyPort || 843;+ this.rememberUpgrade = opts.rememberUpgrade || false;+ this.binaryType = null;+ this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;- /* And continue down the tree, setting j to the left son of k */- j <<= 1;- }- s.heap[k] = v;- }+ // SSL options for Node.js client+ this.pfx = opts.pfx || null;+ this.key = opts.key || null;+ this.passphrase = opts.passphrase || null;+ this.cert = opts.cert || null;+ this.ca = opts.ca || null;+ this.ciphers = opts.ciphers || null;+ this.rejectUnauthorized = opts.rejectUnauthorized || null;+ this.open();+ }- // inlined manually- // var SMALLEST = 1;+ Socket.priorWebsocketSuccess = false;- /* ===========================================================================- * Send the block data compressed using the given Huffman trees+ /**+ * Mix in `Emitter`.*/- function compress_block(s, ltree, dtree)- // deflate_state *s;- // const ct_data *ltree; /* literal tree */- // const ct_data *dtree; /* distance tree */- {- var dist; /* distance of matched string */- var lc; /* match length or unmatched char (if dist == 0) */- var lx = 0; /* running index in l_buf */- var code; /* the code to send */- var extra; /* number of extra bits to send */- if (s.last_lit !== 0) {- do {- dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);- lc = s.pending_buf[s.l_buf + lx];- lx++;+ Emitter(Socket.prototype);- if (dist === 0) {- send_code(s, lc, ltree); /* send a literal byte */- //Tracecv(isgraph(lc), (stderr," '%c' ", lc));- } else {- /* Here, lc is the match length - MIN_MATCH */- code = _length_code[lc];- send_code(s, code+LITERALS+1, ltree); /* send the length code */- extra = extra_lbits[code];- if (extra !== 0) {- lc -= base_length[code];- send_bits(s, lc, extra); /* send the extra length bits */- }- dist--; /* dist is now the match distance - 1 */- code = d_code(dist);- //Assert (code < D_CODES, "bad d_code");+ /**+ * Protocol version.+ *+ * @api public+ */- send_code(s, code, dtree); /* send the distance code */- extra = extra_dbits[code];- if (extra !== 0) {- dist -= base_dist[code];- send_bits(s, dist, extra); /* send the extra distance bits */- }- } /* literal or match pair ? */+ Socket.protocol = parser.protocol; // this is an int- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */- //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,- // "pendingBuf overflow");+ /**+ * Expose deps for legacy compatibility+ * and standalone browser access.+ */- } while (lx < s.last_lit);- }+ Socket.Socket = Socket;+ Socket.Transport = require('./transport');+ Socket.transports = require('./transports');+ Socket.parser = require('engine.io-parser');- send_code(s, END_BLOCK, ltree);- }+ /**+ * Creates transport of the given type.+ *+ * @param {String} transport name+ * @return {Transport}+ * @api private+ */+ Socket.prototype.createTransport = function (name) {+ debug('creating transport "%s"', name);+ var query = clone(this.query);- /* ===========================================================================- * Construct one Huffman tree and assigns the code bit strings and lengths.- * Update the total bit length for the current block.- * IN assertion: the field freq is set for all tree elements.- * OUT assertions: the fields len and code are set to the optimal bit length- * and corresponding code. The length opt_len is updated; static_len is- * also updated if stree is not null. The field max_code is set.- */- function build_tree(s, desc)- // deflate_state *s;- // tree_desc *desc; /* the tree descriptor */- {- var tree = desc.dyn_tree;- var stree = desc.stat_desc.static_tree;- var has_stree = desc.stat_desc.has_stree;- var elems = desc.stat_desc.elems;- var n, m; /* iterate over heap elements */- var max_code = -1; /* largest code with non zero frequency */- var node; /* new node being created */+ // append engine.io protocol identifier+ query.EIO = parser.protocol;- /* Construct the initial heap, with least frequent element in- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].- * heap[0] is not used.- */- s.heap_len = 0;- s.heap_max = HEAP_SIZE;+ // transport name+ query.transport = name;- for (n = 0; n < elems; n++) {- if (tree[n * 2]/*.Freq*/ !== 0) {- s.heap[++s.heap_len] = max_code = n;- s.depth[n] = 0;+ // session id if we already have one+ if (this.id) query.sid = this.id;- } else {- tree[n*2 + 1]/*.Len*/ = 0;- }- }+ var transport = new transports[name]({+ agent: this.agent,+ hostname: this.hostname,+ port: this.port,+ secure: this.secure,+ path: this.path,+ query: query,+ forceJSONP: this.forceJSONP,+ jsonp: this.jsonp,+ forceBase64: this.forceBase64,+ enablesXDR: this.enablesXDR,+ timestampRequests: this.timestampRequests,+ timestampParam: this.timestampParam,+ policyPort: this.policyPort,+ socket: this,+ pfx: this.pfx,+ key: this.key,+ passphrase: this.passphrase,+ cert: this.cert,+ ca: this.ca,+ ciphers: this.ciphers,+ rejectUnauthorized: this.rejectUnauthorized+ });- /* The pkzip format requires that at least one distance code exists,- * and that at least one bit should be sent even if there is only one- * possible code. So to avoid special checks later on we force at least- * two codes of non zero frequency.- */- while (s.heap_len < 2) {- node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);- tree[node * 2]/*.Freq*/ = 1;- s.depth[node] = 0;- s.opt_len--;+ return transport;+ };- if (has_stree) {- s.static_len -= stree[node*2 + 1]/*.Len*/;+ function clone (obj) {+ var o = {};+ for (var i in obj) {+ if (obj.hasOwnProperty(i)) {+ o[i] = obj[i];}- /* node is 0 or 1 so it does not have extra bits */}- desc.max_code = max_code;+ return o;+ }- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,- * establish sub-heaps of increasing lengths:- */- for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }+ /**+ * Initializes transport to use and starts probe.+ *+ * @api private+ */+ Socket.prototype.open = function () {+ var transport;+ if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {+ transport = 'websocket';+ } else if (0 == this.transports.length) {+ // Emit error on next tick so it can be listened to+ var self = this;+ setTimeout(function() {+ self.emit('error', 'No transports available');+ }, 0);+ return;+ } else {+ transport = this.transports[0];+ }+ this.readyState = 'opening';- /* Construct the Huffman tree by repeatedly combining the least two- * frequent nodes.- */- node = elems; /* next internal node of the tree */- do {- //pqremove(s, tree, n); /* n = node of least frequency */- /*** pqremove ***/- n = s.heap[1/*SMALLEST*/];- s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];- pqdownheap(s, tree, 1/*SMALLEST*/);- /***/+ // Retry with the next transport if the transport is disabled (jsonp: false)+ var transport;+ try {+ transport = this.createTransport(transport);+ } catch (e) {+ this.transports.shift();+ this.open();+ return;+ }- m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */+ transport.open();+ this.setTransport(transport);+ };- s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */- s.heap[--s.heap_max] = m;+ /**+ * Sets the current transport. Disables the existing one (if any).+ *+ * @api private+ */- /* Create a new node father of n and m */- tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;- s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;- tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;+ Socket.prototype.setTransport = function(transport){+ debug('setting transport %s', transport.name);+ var self = this;- /* and insert the new node in the heap */- s.heap[1/*SMALLEST*/] = node++;- pqdownheap(s, tree, 1/*SMALLEST*/);+ if (this.transport) {+ debug('clearing existing transport %s', this.transport.name);+ this.transport.removeAllListeners();+ }- } while (s.heap_len >= 2);+ // set up transport+ this.transport = transport;- s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];+ // set up transport listeners+ transport+ .on('drain', function(){+ self.onDrain();+ })+ .on('packet', function(packet){+ self.onPacket(packet);+ })+ .on('error', function(e){+ self.onError(e);+ })+ .on('close', function(){+ self.onClose('transport close');+ });+ };- /* At this point, the fields freq and dad are set. We can now- * generate the bit lengths.- */- gen_bitlen(s, desc);+ /**+ * Probes a transport.+ *+ * @param {String} transport name+ * @api private+ */- /* The field len is now set, we can generate the bit codes */- gen_codes(tree, max_code, s.bl_count);- }+ Socket.prototype.probe = function (name) {+ debug('probing transport "%s"', name);+ var transport = this.createTransport(name, { probe: 1 })+ , failed = false+ , self = this;+ Socket.priorWebsocketSuccess = false;- /* ===========================================================================- * Scan a literal or distance tree to determine the frequencies of the codes- * in the bit length tree.- */- function scan_tree(s, tree, max_code)- // deflate_state *s;- // ct_data *tree; /* the tree to be scanned */- // int max_code; /* and its largest code of non zero frequency */- {- var n; /* iterates over all tree elements */- var prevlen = -1; /* last emitted length */- var curlen; /* length of current code */+ function onTransportOpen(){+ if (self.onlyBinaryUpgrades) {+ var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;+ failed = failed || upgradeLosesBinary;+ }+ if (failed) return;- var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */+ debug('probe transport "%s" opened', name);+ transport.send([{ type: 'ping', data: 'probe' }]);+ transport.once('packet', function (msg) {+ if (failed) return;+ if ('pong' == msg.type && 'probe' == msg.data) {+ debug('probe transport "%s" pong', name);+ self.upgrading = true;+ self.emit('upgrading', transport);+ if (!transport) return;+ Socket.priorWebsocketSuccess = 'websocket' == transport.name;- var count = 0; /* repeat count of the current code */- var max_count = 7; /* max repeat count */- var min_count = 4; /* min repeat count */+ debug('pausing current transport "%s"', self.transport.name);+ self.transport.pause(function () {+ if (failed) return;+ if ('closed' == self.readyState) return;+ debug('changing transport and sending upgrade packet');- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ cleanup();++ self.setTransport(transport);+ transport.send([{ type: 'upgrade' }]);+ self.emit('upgrade', transport);+ transport = null;+ self.upgrading = false;+ self.flush();+ });+ } else {+ debug('probe transport "%s" failed', name);+ var err = new Error('probe error');+ err.transport = transport.name;+ self.emit('upgradeError', err);+ }+ });}- tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */- for (n = 0; n <= max_code; n++) {- curlen = nextlen;- nextlen = tree[(n+1)*2 + 1]/*.Len*/;+ function freezeTransport() {+ if (failed) return;- if (++count < max_count && curlen === nextlen) {- continue;+ // Any callback called by transport should be ignored since now+ failed = true;- } else if (count < min_count) {- s.bl_tree[curlen * 2]/*.Freq*/ += count;+ cleanup();- } else if (curlen !== 0) {+ transport.close();+ transport = null;+ }- if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }- s.bl_tree[REP_3_6*2]/*.Freq*/++;+ //Handle any error that happens while probing+ function onerror(err) {+ var error = new Error('probe error: ' + err);+ error.transport = transport.name;- } else if (count <= 10) {- s.bl_tree[REPZ_3_10*2]/*.Freq*/++;+ freezeTransport();- } else {- s.bl_tree[REPZ_11_138*2]/*.Freq*/++;- }+ debug('probe transport "%s" failed because of error: %s', name, err);- count = 0;- prevlen = curlen;+ self.emit('upgradeError', error);+ }- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ function onTransportClose(){+ onerror("transport closed");+ }- } else if (curlen === nextlen) {- max_count = 6;- min_count = 3;+ //When the socket is closed while we're probing+ function onclose(){+ onerror("socket closed");+ }- } else {- max_count = 7;- min_count = 4;+ //When the socket is upgraded while we're probing+ function onupgrade(to){+ if (transport && to.name != transport.name) {+ debug('"%s" works - aborting "%s"', to.name, transport.name);+ freezeTransport();}}- }--- /* ===========================================================================- * Send a literal or distance tree in compressed form, using the codes in- * bl_tree.- */- function send_tree(s, tree, max_code)- // deflate_state *s;- // ct_data *tree; /* the tree to be scanned */- // int max_code; /* and its largest code of non zero frequency */- {- var n; /* iterates over all tree elements */- var prevlen = -1; /* last emitted length */- var curlen; /* length of current code */-- var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */-- var count = 0; /* repeat count of the current code */- var max_count = 7; /* max repeat count */- var min_count = 4; /* min repeat count */- /* tree[max_code+1].Len = -1; */ /* guard already set */- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ //Remove all listeners on the transport and on self+ function cleanup(){+ transport.removeListener('open', onTransportOpen);+ transport.removeListener('error', onerror);+ transport.removeListener('close', onTransportClose);+ self.removeListener('close', onclose);+ self.removeListener('upgrading', onupgrade);}- for (n = 0; n <= max_code; n++) {- curlen = nextlen;- nextlen = tree[(n+1)*2 + 1]/*.Len*/;+ transport.once('open', onTransportOpen);+ transport.once('error', onerror);+ transport.once('close', onTransportClose);- if (++count < max_count && curlen === nextlen) {- continue;+ this.once('close', onclose);+ this.once('upgrading', onupgrade);- } else if (count < min_count) {- do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);+ transport.open();- } else if (curlen !== 0) {- if (curlen !== prevlen) {- send_code(s, curlen, s.bl_tree);- count--;- }- //Assert(count >= 3 && count <= 6, " 3_6?");- send_code(s, REP_3_6, s.bl_tree);- send_bits(s, count-3, 2);+ };- } else if (count <= 10) {- send_code(s, REPZ_3_10, s.bl_tree);- send_bits(s, count-3, 3);+ /**+ * Called when connection is deemed open.+ *+ * @api public+ */- } else {- send_code(s, REPZ_11_138, s.bl_tree);- send_bits(s, count-11, 7);+ Socket.prototype.onOpen = function () {+ debug('socket open');+ this.readyState = 'open';+ Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;+ this.emit('open');+ this.flush();++ // we check for `readyState` in case an `open`+ // listener already closed the socket+ if ('open' == this.readyState && this.upgrade && this.transport.pause) {+ debug('starting upgrade probes');+ for (var i = 0, l = this.upgrades.length; i < l; i++) {+ this.probe(this.upgrades[i]);}+ }+ };- count = 0;- prevlen = curlen;- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ /**+ * Handles a packet.+ *+ * @api private+ */- } else if (curlen === nextlen) {- max_count = 6;- min_count = 3;+ Socket.prototype.onPacket = function (packet) {+ if ('opening' == this.readyState || 'open' == this.readyState) {+ debug('socket receive: type "%s", data "%s"', packet.type, packet.data);- } else {- max_count = 7;- min_count = 4;- }- }- }+ this.emit('packet', packet);+ // Socket is live - any packet counts+ this.emit('heartbeat');- /* ===========================================================================- * Construct the Huffman tree for the bit lengths and return the index in- * bl_order of the last bit length code to send.- */- function build_bl_tree(s) {- var max_blindex; /* index of last bit length code of non zero freq */+ switch (packet.type) {+ case 'open':+ this.onHandshake(parsejson(packet.data));+ break;- /* Determine the bit length frequencies for literal and distance trees */- scan_tree(s, s.dyn_ltree, s.l_desc.max_code);- scan_tree(s, s.dyn_dtree, s.d_desc.max_code);+ case 'pong':+ this.setPing();+ break;- /* Build the bit length tree: */- build_tree(s, s.bl_desc);- /* opt_len now includes the length of the tree representations, except- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.- */+ case 'error':+ var err = new Error('server error');+ err.code = packet.data;+ this.emit('error', err);+ break;- /* Determine the number of bit length codes to send. The pkzip format- * requires that at least 4 bit length codes be sent. (appnote.txt says- * 3 but the actual value used is 4.)- */- for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {- if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {- break;+ case 'message':+ this.emit('data', packet.data);+ this.emit('message', packet.data);+ break;}+ } else {+ debug('packet received with socket readyState "%s"', this.readyState);}- /* Update opt_len to include the bit length tree and counts */- s.opt_len += 3*(max_blindex+1) + 5+5+4;- //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",- // s->opt_len, s->static_len));+ };- return max_blindex;- }+ /**+ * Called upon handshake completion.+ *+ * @param {Object} handshake obj+ * @api private+ */++ Socket.prototype.onHandshake = function (data) {+ this.emit('handshake', data);+ this.id = data.sid;+ this.transport.query.sid = data.sid;+ this.upgrades = this.filterUpgrades(data.upgrades);+ this.pingInterval = data.pingInterval;+ this.pingTimeout = data.pingTimeout;+ this.onOpen();+ // In case open handler closes socket+ if ('closed' == this.readyState) return;+ this.setPing();+ // Prolong liveness of socket on heartbeat+ this.removeListener('heartbeat', this.onHeartbeat);+ this.on('heartbeat', this.onHeartbeat);+ };- /* ===========================================================================- * Send the header for a block using dynamic Huffman trees: the counts, the- * lengths of the bit length codes, the literal tree and the distance tree.- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.+ /**+ * Resets ping timeout.+ *+ * @api private*/- function send_all_trees(s, lcodes, dcodes, blcodes)- // deflate_state *s;- // int lcodes, dcodes, blcodes; /* number of codes for each tree */- {- var rank; /* index in bl_order */- //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");- //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,- // "too many codes");- //Tracev((stderr, "\nbl counts: "));- send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */- send_bits(s, dcodes-1, 5);- send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */- for (rank = 0; rank < blcodes; rank++) {- //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));- send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);- }- //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));+ Socket.prototype.onHeartbeat = function (timeout) {+ clearTimeout(this.pingTimeoutTimer);+ var self = this;+ self.pingTimeoutTimer = setTimeout(function () {+ if ('closed' == self.readyState) return;+ self.onClose('ping timeout');+ }, timeout || (self.pingInterval + self.pingTimeout));+ };- send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */- //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));+ /**+ * Pings server every `this.pingInterval` and expects response+ * within `this.pingTimeout` or closes connection.+ *+ * @api private+ */- send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */- //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));- }+ Socket.prototype.setPing = function () {+ var self = this;+ clearTimeout(self.pingIntervalTimer);+ self.pingIntervalTimer = setTimeout(function () {+ debug('writing ping packet - expecting pong within %sms', self.pingTimeout);+ self.ping();+ self.onHeartbeat(self.pingTimeout);+ }, self.pingInterval);+ };+ /**+ * Sends a ping packet.+ *+ * @api public+ */- /* ===========================================================================- * Check if the data type is TEXT or BINARY, using the following algorithm:- * - TEXT if the two conditions below are satisfied:- * a) There are no non-portable control characters belonging to the- * "black list" (0..6, 14..25, 28..31).- * b) There is at least one printable character belonging to the- * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).- * - BINARY otherwise.- * - The following partially-portable control characters form a- * "gray list" that is ignored in this detection algorithm:- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).- * IN assertion: the fields Freq of dyn_ltree are set.- */- function detect_data_type(s) {- /* black_mask is the bit mask of black-listed bytes- * set bits 0..6, 14..25, and 28..31- * 0xf3ffc07f = binary 11110011111111111100000001111111- */- var black_mask = 0xf3ffc07f;- var n;+ Socket.prototype.ping = function () {+ this.sendPacket('ping');+ };- /* Check for non-textual ("black-listed") bytes. */- for (n = 0; n <= 31; n++, black_mask >>>= 1) {- if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {- return Z_BINARY;- }- }+ /**+ * Called on `drain` event+ *+ * @api private+ */- /* Check for textual ("white-listed") bytes. */- if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||- s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {- return Z_TEXT;- }- for (n = 32; n < LITERALS; n++) {- if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {- return Z_TEXT;+ Socket.prototype.onDrain = function() {+ for (var i = 0; i < this.prevBufferLen; i++) {+ if (this.callbackBuffer[i]) {+ this.callbackBuffer[i]();}}- /* There are no "black-listed" or "white-listed" bytes:- * this stream either is empty or has tolerated ("gray-listed") bytes only.- */- return Z_BINARY;- }+ this.writeBuffer.splice(0, this.prevBufferLen);+ this.callbackBuffer.splice(0, this.prevBufferLen);+ // setting prevBufferLen = 0 is very important+ // for example, when upgrading, upgrade packet is sent over,+ // and a nonzero prevBufferLen could cause problems on `drain`+ this.prevBufferLen = 0;- var static_init_done = false;+ if (this.writeBuffer.length == 0) {+ this.emit('drain');+ } else {+ this.flush();+ }+ };- /* ===========================================================================- * Initialize the tree data structures for a new zlib stream.+ /**+ * Flush write buffers.+ *+ * @api private*/- function _tr_init(s)- {- if (!static_init_done) {- tr_static_init();- static_init_done = true;+ Socket.prototype.flush = function () {+ if ('closed' != this.readyState && this.transport.writable &&+ !this.upgrading && this.writeBuffer.length) {+ debug('flushing %d packets in socket', this.writeBuffer.length);+ this.transport.send(this.writeBuffer);+ // keep track of current length of writeBuffer+ // splice writeBuffer and callbackBuffer on `drain`+ this.prevBufferLen = this.writeBuffer.length;+ this.emit('flush');}+ };- s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);- s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);- s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);+ /**+ * Sends a message.+ *+ * @param {String} message.+ * @param {Function} callback function.+ * @return {Socket} for chaining.+ * @api public+ */- s.bi_buf = 0;- s.bi_valid = 0;+ Socket.prototype.write =+ Socket.prototype.send = function (msg, fn) {+ this.sendPacket('message', msg, fn);+ return this;+ };- /* Initialize the first block of the first file: */- init_block(s);- }+ /**+ * Sends a packet.+ *+ * @param {String} packet type.+ * @param {String} data.+ * @param {Function} callback function.+ * @api private+ */+ Socket.prototype.sendPacket = function (type, data, fn) {+ if ('closing' == this.readyState || 'closed' == this.readyState) {+ return;+ }- /* ===========================================================================- * Send a stored block+ var packet = { type: type, data: data };+ this.emit('packetCreate', packet);+ this.writeBuffer.push(packet);+ this.callbackBuffer.push(fn);+ this.flush();+ };++ /**+ * Closes the connection.+ *+ * @api private*/- function _tr_stored_block(s, buf, stored_len, last)- //DeflateState *s;- //charf *buf; /* input block */- //ulg stored_len; /* length of input block */- //int last; /* one if this is the last block for a file */- {- send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */- copy_block(s, buf, stored_len, true); /* with header */- }+ Socket.prototype.close = function () {+ if ('opening' == this.readyState || 'open' == this.readyState) {+ this.readyState = 'closing';- /* ===========================================================================- * Send one empty static block to give enough lookahead for inflate.- * This takes 10 bits, of which 7 may remain in the bit buffer.- */- function _tr_align(s) {- send_bits(s, STATIC_TREES<<1, 3);- send_code(s, END_BLOCK, static_ltree);- bi_flush(s);- }+ var self = this;+ function close() {+ self.onClose('forced close');+ debug('socket closing - telling transport to close');+ self.transport.close();+ }- /* ===========================================================================- * Determine the best encoding for the current block: dynamic trees, static- * trees or store, and output the encoded block to the zip file.- */- function _tr_flush_block(s, buf, stored_len, last)- //DeflateState *s;- //charf *buf; /* input block, or NULL if too old */- //ulg stored_len; /* length of input block */- //int last; /* one if this is the last block for a file */- {- var opt_lenb, static_lenb; /* opt_len and static_len in bytes */- var max_blindex = 0; /* index of last bit length code of non zero freq */+ function cleanupAndClose() {+ self.removeListener('upgrade', cleanupAndClose);+ self.removeListener('upgradeError', cleanupAndClose);+ close();+ }- /* Build the Huffman trees unless a stored block is forced */- if (s.level > 0) {+ function waitForUpgrade() {+ // wait for upgrade to finish since we can't send packets while pausing a transport+ self.once('upgrade', cleanupAndClose);+ self.once('upgradeError', cleanupAndClose);+ }- /* Check if the file is binary or text */- if (s.strm.data_type === Z_UNKNOWN) {- s.strm.data_type = detect_data_type(s);+ if (this.writeBuffer.length) {+ this.once('drain', function() {+ if (this.upgrading) {+ waitForUpgrade();+ } else {+ close();+ }+ });+ } else if (this.upgrading) {+ waitForUpgrade();+ } else {+ close();}+ }- /* Construct the literal and distance trees */- build_tree(s, s.l_desc);- // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,- // s->static_len));+ return this;+ };- build_tree(s, s.d_desc);- // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,- // s->static_len));- /* At this point, opt_len and static_len are the total bit lengths of- * the compressed block data, excluding the tree representations.- */+ /**+ * Called upon transport error+ *+ * @api private+ */- /* Build the bit length tree for the above two trees, and get the index- * in bl_order of the last bit length code to send.- */- max_blindex = build_bl_tree(s);+ Socket.prototype.onError = function (err) {+ debug('socket error %j', err);+ Socket.priorWebsocketSuccess = false;+ this.emit('error', err);+ this.onClose('transport error', err);+ };- /* Determine the best encoding. Compute the block lengths in bytes. */- opt_lenb = (s.opt_len+3+7) >>> 3;- static_lenb = (s.static_len+3+7) >>> 3;+ /**+ * Called upon transport close.+ *+ * @api private+ */- // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",- // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,- // s->last_lit));+ Socket.prototype.onClose = function (reason, desc) {+ if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {+ debug('socket close with reason: "%s"', reason);+ var self = this;- if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }+ // clear timers+ clearTimeout(this.pingIntervalTimer);+ clearTimeout(this.pingTimeoutTimer);- } else {- // Assert(buf != (char*)0, "lost buf");- opt_lenb = static_lenb = stored_len + 5; /* force a stored block */- }+ // clean buffers in next tick, so developers can still+ // grab the buffers on `close` event+ setTimeout(function() {+ self.writeBuffer = [];+ self.callbackBuffer = [];+ self.prevBufferLen = 0;+ }, 0);- if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {- /* 4: two words for the lengths */+ // stop event from firing again for transport+ this.transport.removeAllListeners('close');- /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.- * Otherwise we can't have processed more than WSIZE input bytes since- * the last block flush, because compression would have been- * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to- * transform a block into a stored block.- */- _tr_stored_block(s, buf, stored_len, last);+ // ensure transport won't stay open+ this.transport.close();- } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {+ // ignore further transport communication+ this.transport.removeAllListeners();- send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);- compress_block(s, static_ltree, static_dtree);+ // set ready state+ this.readyState = 'closed';- } else {- send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);- send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);- compress_block(s, s.dyn_ltree, s.dyn_dtree);+ // clear session id+ this.id = null;++ // emit close event+ this.emit('close', reason, desc);}- // Assert (s->compressed_len == s->bits_sent, "bad compressed size");- /* The above check is made mod 2^32, for files larger than 512 MB- * and uLong implemented on 32 bits.- */- init_block(s);+ };- if (last) {- bi_windup(s);+ /**+ * Filters upgrades, returning only those matching client transports.+ *+ * @param {Array} server upgrades+ * @api private+ *+ */++ Socket.prototype.filterUpgrades = function (upgrades) {+ var filteredUpgrades = [];+ for (var i = 0, j = upgrades.length; i<j; i++) {+ if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);}- // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,- // s->compressed_len-7*last));- }+ return filteredUpgrades;+ };++ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"./transport":98,"./transports":99,"component-emitter":93,"debug":106,"engine.io-parser":109,"indexof":126,"parsejson":120,"parseqs":121,"parseuri":122}],98:[function(require,module,exports){++},{"./transport":95,"./transports":96,"component-emitter":90,"debug":103,"engine.io-parser":106,"indexof":123,"parsejson":117,"parseqs":118,"parseuri":119}],95:[function(require,module,exports){+ /**+ * Module dependencies.+ */- /* ===========================================================================- * Save the match info and tally the frequency counts. Return true if- * the current block must be flushed.+ var parser = require('engine.io-parser');+ var Emitter = require('component-emitter');++ /**+ * Module exports.*/- function _tr_tally(s, dist, lc)- // deflate_state *s;- // unsigned dist; /* distance of matched string */- // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */- {- //var out_length, in_length, dcode;- s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;- s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;+ module.exports = Transport;- s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;- s.last_lit++;+ /**+ * Transport abstract constructor.+ *+ * @param {Object} options.+ * @api private+ */- if (dist === 0) {- /* lc is the unmatched char */- s.dyn_ltree[lc*2]/*.Freq*/++;- } else {- s.matches++;- /* Here, lc is the match length - MIN_MATCH */- dist--; /* dist = match distance - 1 */- //Assert((ush)dist < (ush)MAX_DIST(s) &&- // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&- // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");+ function Transport (opts) {+ this.path = opts.path;+ this.hostname = opts.hostname;+ this.port = opts.port;+ this.secure = opts.secure;+ this.query = opts.query;+ this.timestampParam = opts.timestampParam;+ this.timestampRequests = opts.timestampRequests;+ this.readyState = '';+ this.agent = opts.agent || false;+ this.socket = opts.socket;+ this.enablesXDR = opts.enablesXDR;- s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;- s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;- }+ // SSL options for Node.js client+ this.pfx = opts.pfx;+ this.key = opts.key;+ this.passphrase = opts.passphrase;+ this.cert = opts.cert;+ this.ca = opts.ca;+ this.ciphers = opts.ciphers;+ this.rejectUnauthorized = opts.rejectUnauthorized;+ }- // (!) This block is disabled in zlib defailts,- // don't enable it for binary compatibility+ /**+ * Mix in `Emitter`.+ */- //#ifdef TRUNCATE_BLOCK- // /* Try to guess if it is profitable to stop the current block here */- // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {- // /* Compute an upper bound for the compressed length */- // out_length = s.last_lit*8;- // in_length = s.strstart - s.block_start;- //- // for (dcode = 0; dcode < D_CODES; dcode++) {- // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);- // }- // out_length >>>= 3;- // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",- // // s->last_lit, in_length, out_length,- // // 100L - out_length*100L/in_length));- // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {- // return true;- // }- // }- //#endif+ Emitter(Transport.prototype);- return (s.last_lit === s.lit_bufsize-1);- /* We avoid equality with lit_bufsize because of wraparound at 64K- * on 16 bit machines and because stored blocks are restricted to- * 64K-1 bytes.- */- }+ /**+ * A counter used to prevent collisions in the timestamps used+ * for cache busting.+ */- exports._tr_init = _tr_init;- exports._tr_stored_block = _tr_stored_block;- exports._tr_flush_block = _tr_flush_block;- exports._tr_tally = _tr_tally;- exports._tr_align = _tr_align;+ Transport.timestamps = 0;- },{"../utils/common":87}],99:[function(require,module,exports){- 'use strict';+ /**+ * Emits an error.+ *+ * @param {String} str+ * @return {Transport} for chaining+ * @api public+ */+ Transport.prototype.onError = function (msg, desc) {+ var err = new Error(msg);+ err.type = 'TransportError';+ err.description = desc;+ this.emit('error', err);+ return this;+ };- function ZStream() {- /* next input byte */- this.input = null; // JS specific, because we have no pointers- this.next_in = 0;- /* number of bytes available at input */- this.avail_in = 0;- /* total number of input bytes read so far */- this.total_in = 0;- /* next output byte should be put there */- this.output = null; // JS specific, because we have no pointers- this.next_out = 0;- /* remaining free space at output */- this.avail_out = 0;- /* total number of bytes output so far */- this.total_out = 0;- /* last error message, NULL if no error */- this.msg = ''/*Z_NULL*/;- /* not visible by applications */- this.state = null;- /* best guess about the data type: binary or text */- this.data_type = 2/*Z_UNKNOWN*/;- /* adler32 value of the uncompressed data */- this.adler = 0;- }+ /**+ * Opens the transport.+ *+ * @api public+ */- module.exports = ZStream;+ Transport.prototype.open = function () {+ if ('closed' == this.readyState || '' == this.readyState) {+ this.readyState = 'opening';+ this.doOpen();+ }++ return this;+ };- },{}],100:[function(require,module,exports){- (function (global){/**- * JSON parse.+ * Closes the transport.*- * @see Based on jQuery#parseJSON (MIT) and JSON2* @api private*/@@@ -27442,1899 -26736,1964 +26812,1964 @@@ Transport.prototype.onPacket = functio* @api private*/- exports.decode = function(qs){- var qry = {};- var pairs = qs.split('&');- for (var i = 0, l = pairs.length; i < l; i++) {- var pair = pairs[i].split('=');- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);- }- return qry;+ Transport.prototype.onClose = function () {+ this.readyState = 'closed';+ this.emit('close');};- },{}],102:[function(require,module,exports){-},{"component-emitter":93,"engine.io-parser":109}],99:[function(require,module,exports){++},{"component-emitter":90,"engine.io-parser":106}],96:[function(require,module,exports){+ (function (global){+ /**+ * Module dependencies+ */++ var XMLHttpRequest = require('xmlhttprequest');+ var XHR = require('./polling-xhr');+ var JSONP = require('./polling-jsonp');+ var websocket = require('./websocket');+/**- * Parses an URI+ * Export transports.+ */++ exports.polling = polling;+ exports.websocket = websocket;++ /**+ * Polling transport polymorphic constructor.+ * Decides on xhr vs jsonp based on feature detection.*- * @author Steven Levithan <stevenlevithan.com> (MIT license)* @api private*/- var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;+ function polling(opts){+ var xhr;+ var xd = false;+ var xs = false;+ var jsonp = false !== opts.jsonp;- var parts = [- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'- , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'- ];+ if (global.location) {+ var isSSL = 'https:' == location.protocol;+ var port = location.port;- module.exports = function parseuri(str) {- var m = re.exec(str || '')- , uri = {}- , i = 14;+ // some user agents have empty `location.port`+ if (!port) {+ port = isSSL ? 443 : 80;+ }- while (i--) {- uri[parts[i]] = m[i] || '';+ xd = opts.hostname != location.hostname || port != opts.port;+ xs = opts.secure != isSSL;}- return uri;- };+ opts.xdomain = xd;+ opts.xscheme = xs;+ xhr = new XMLHttpRequest(opts);- },{}],103:[function(require,module,exports){- // shim for using process in browser+ if ('open' in xhr && !opts.forceJSONP) {+ return new XHR(opts);+ } else {+ if (!jsonp) throw new Error('JSONP disabled');+ return new JSONP(opts);+ }+ }- var process = module.exports = {};- var queue = [];- var draining = false;- var currentQueue;- var queueIndex = -1;+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"./polling-jsonp":100,"./polling-xhr":101,"./websocket":103,"xmlhttprequest":104}],100:[function(require,module,exports){++},{"./polling-jsonp":97,"./polling-xhr":98,"./websocket":100,"xmlhttprequest":101}],97:[function(require,module,exports){+ (function (global){- function cleanUpNextTick() {- draining = false;- if (currentQueue.length) {- queue = currentQueue.concat(queue);- } else {- queueIndex = -1;- }- if (queue.length) {- drainQueue();- }- }+ /**+ * Module requirements.+ */- function drainQueue() {- if (draining) {- return;- }- var timeout = setTimeout(cleanUpNextTick);- draining = true;+ var Polling = require('./polling');+ var inherit = require('component-inherit');- var len = queue.length;- while(len) {- currentQueue = queue;- queue = [];- while (++queueIndex < len) {- if (currentQueue) {- currentQueue[queueIndex].run();- }- }- queueIndex = -1;- len = queue.length;- }- currentQueue = null;- draining = false;- clearTimeout(timeout);- }+ /**+ * Module exports.+ */- process.nextTick = function (fun) {- var args = new Array(arguments.length - 1);- if (arguments.length > 1) {- for (var i = 1; i < arguments.length; i++) {- args[i - 1] = arguments[i];- }- }- queue.push(new Item(fun, args));- if (queue.length === 1 && !draining) {- setTimeout(drainQueue, 0);- }- };+ module.exports = JSONPPolling;- // v8 likes predictible objects- function Item(fun, array) {- this.fun = fun;- this.array = array;- }- Item.prototype.run = function () {- this.fun.apply(null, this.array);- };- process.title = 'browser';- process.browser = true;- process.env = {};- process.argv = [];- process.version = ''; // empty string to avoid regexp issues- process.versions = {};+ /**+ * Cached regular expressions.+ */- function noop() {}+ var rNewline = /\n/g;+ var rEscapedNewline = /\\n/g;- process.on = noop;- process.addListener = noop;- process.once = noop;- process.off = noop;- process.removeListener = noop;- process.removeAllListeners = noop;- process.emit = noop;+ /**+ * Global JSONP callbacks.+ */- process.binding = function (name) {- throw new Error('process.binding is not supported');- };+ var callbacks;- process.cwd = function () { return '/' };- process.chdir = function (dir) {- throw new Error('process.chdir is not supported');- };- process.umask = function() { return 0; };+ /**+ * Callbacks count.+ */- },{}],104:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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+ var index = 0;++ /**+ * Noop.+ */++ function empty () { }++ /**+ * JSONP Polling constructor.*- * 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.+ * @param {Object} opts.+ * @api public*/- module.exports = function arrayEquals(array) {- // if the other array is a falsy value, return- if (!array)- return false;+ function JSONPPolling (opts) {+ Polling.call(this, opts);- // compare lengths - can save a lot of time- if (this.length != array.length)- return false;+ this.query = this.query || {};- for (var i = 0, l = this.length; i < l; i++) {- // Check if we have nested arrays- if (this[i] instanceof Array && array[i] instanceof Array) {- // recurse into the nested arrays- if (!arrayEquals.apply(this[i], [array[i]]))- return false;- } else if (this[i] != array[i]) {- // Warning - two different object instances will never be equal:- // {x:20} != {x:20}- return false;- }- }- return true;- };+ // define global callbacks array if not present+ // we do this here (lazily) to avoid unneeded global pollution+ if (!callbacks) {+ // we need to consider multiple engines in the same page+ if (!global.___eio) global.___eio = [];+ callbacks = global.___eio;+ }+ // callback identifier+ this.index = callbacks.length;- },{}],105:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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.- */+ // add callback to jsonp global+ var self = this;+ callbacks.push(function (msg) {+ self.onData(msg);+ });- exports.Interop = require('./interop');+ // append to query string+ this.query.j = this.index;- },{"./interop":106}],106:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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.+ // prevent spurious errors from being emitted when the window is unloaded+ if (global.document && global.addEventListener) {+ global.addEventListener('beforeunload', function () {+ if (self.script) self.script.onerror = empty;+ }, false);+ }+ }++ /**+ * Inherits from Polling.*/- /* global RTCSessionDescription */- /* jshint -W097 */- "use strict";+ inherit(JSONPPolling, Polling);- var transform = require('./transform');- var arrayEquals = require('./array-equals');+ /*+ * JSONP only supports binary as base64 encoded strings+ */- function Interop() {+ JSONPPolling.prototype.supportsBinary = false;- /**- * This map holds the most recent Unified Plan offer/answer SDP that was- * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and- * the SDP string as values.- *- * @type {{}}- */- this.cache = {};- }+ /**+ * Closes the socket.+ *+ * @api private+ */- module.exports = Interop;+ JSONPPolling.prototype.doClose = function () {+ if (this.script) {+ this.script.parentNode.removeChild(this.script);+ this.script = null;+ }++ if (this.form) {+ this.form.parentNode.removeChild(this.form);+ this.form = null;+ this.iframe = null;+ }++ Polling.prototype.doClose.call(this);+ };/**- * Returns the index of the first m-line with the given media type and with a- * direction which allows sending, in the last Unified Plan description with- * type "answer" converted to Plan B. Returns {null} if there is no saved- * answer, or if none of its m-lines with the given type allow sending.- * @param type the media type ("audio" or "video").- * @returns {*}+ * Starts a poll cycle.+ *+ * @api private*/- Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {- if (!this.cache.answer) {- return null;- }- var session = transform.parse(this.cache.answer);- if (session && session.media && Array.isArray(session.media)){- for (var i = 0; i < session.media.length; i++) {- if (session.media[i].type == type &&- (!session.media[i].direction /* default to sendrecv */ ||- session.media[i].direction === 'sendrecv' ||- session.media[i].direction === 'sendonly')){- return i;- }- }- }+ JSONPPolling.prototype.doPoll = function () {+ var self = this;+ var script = document.createElement('script');- return null;+ if (this.script) {+ this.script.parentNode.removeChild(this.script);+ this.script = null;+ }++ script.async = true;+ script.src = this.uri();+ script.onerror = function(e){+ self.onError('jsonp poll error',e);+ };++ var insertAt = document.getElementsByTagName('script')[0];+ insertAt.parentNode.insertBefore(script, insertAt);+ this.script = script;++ var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);++ if (isUAgecko) {+ setTimeout(function () {+ var iframe = document.createElement('iframe');+ document.body.appendChild(iframe);+ document.body.removeChild(iframe);+ }, 100);+ }};/**- * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A- * PeerConnection wrapper transforms the SDP to Plan B before passing it to the- * application.+ * Writes with a hidden iframe.*- * @param desc- * @returns {*}+ * @param {String} data to send+ * @param {Function} called upon flush.+ * @api private*/- Interop.prototype.toPlanB = function(desc) {- var self = this;- //#region Preliminary input validation.- if (typeof desc !== 'object' || desc === null ||- typeof desc.sdp !== 'string') {- console.warn('An empty description was passed as an argument.');- return desc;- }+ JSONPPolling.prototype.doWrite = function (data, fn) {+ var self = this;- // Objectify the SDP for easier manipulation.- var session = transform.parse(desc.sdp);+ if (!this.form) {+ var form = document.createElement('form');+ var area = document.createElement('textarea');+ var id = this.iframeId = 'eio_iframe_' + this.index;+ var iframe;- // If the SDP contains no media, there's nothing to transform.- if (typeof session.media === 'undefined' ||- !Array.isArray(session.media) || session.media.length === 0) {- console.warn('The description has no media.');- return desc;+ form.className = 'socketio';+ form.style.position = 'absolute';+ form.style.top = '-1000px';+ form.style.left = '-1000px';+ form.target = id;+ form.method = 'POST';+ form.setAttribute('accept-charset', 'utf-8');+ area.name = 'd';+ form.appendChild(area);+ document.body.appendChild(form);++ this.form = form;+ this.area = area;+ }++ this.form.action = this.uri();++ function complete () {+ initIframe();+ fn();+ }++ function initIframe () {+ if (self.iframe) {+ try {+ self.form.removeChild(self.iframe);+ } catch (e) {+ self.onError('jsonp polling iframe removal error', e);+ }}- // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B- // SDP has a video, an audio and a data "channel" at most.- if (session.media.length <= 3 && session.media.every(function(m) {- return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;- })) {- console.warn('This description does not look like Unified Plan.');- return desc;+ try {+ // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)+ var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';+ iframe = document.createElement(html);+ } catch (e) {+ iframe = document.createElement('iframe');+ iframe.name = self.iframeId;+ iframe.src = 'javascript:0';}- //#endregion+ iframe.id = self.iframeId;- // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443- var sdp = desc.sdp;- var rewrite = false;- for (var i = 0; i < session.media.length; i++) {- var uLine = session.media[i];- uLine.rtp.forEach(function(rtp) {- if (rtp.codec === 'NULL')- {- rewrite = true;- var offer = transform.parse(self.cache['offer']);- rtp.codec = offer.media[i].rtp[0].codec;- }- });- };- if (rewrite) {- sdp = transform.write(session);- }+ self.form.appendChild(iframe);+ self.iframe = iframe;+ }- // Unified Plan SDP is our "precious". Cache it for later use in the Plan B- // -> Unified Plan transformation.- this.cache[desc.type] = sdp;+ initIframe();- //#region Convert from Unified Plan to Plan B.+ // escape \n to prevent it from being converted into \r\n by some UAs+ // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side+ data = data.replace(rEscapedNewline, '\\\n');+ this.area.value = data.replace(rNewline, '\\n');- // We rebuild the session.media array.- var media = session.media;- session.media = [];+ try {+ this.form.submit();+ } catch(e) {}- // Associative array that maps channel types to channel objects for fast- // access to channel objects by their type, e.g. type2bl['audio']->channel- // obj.- var type2bl = {};+ if (this.iframe.attachEvent) {+ this.iframe.onreadystatechange = function(){+ if (self.iframe.readyState == 'complete') {+ complete();+ }+ };+ } else {+ this.iframe.onload = complete;+ }+ };- // Used to build the group:BUNDLE value after the channels construction- // loop.- var types = [];+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"./polling":102,"component-inherit":105}],101:[function(require,module,exports){++},{"./polling":99,"component-inherit":102}],98:[function(require,module,exports){+ (function (global){+ /**+ * Module requirements.+ */- // Implode the Unified Plan m-lines/tracks into Plan B channels.- media.forEach(function(uLine) {+ var XMLHttpRequest = require('xmlhttprequest');+ var Polling = require('./polling');+ var Emitter = require('component-emitter');+ var inherit = require('component-inherit');+ var debug = require('debug')('engine.io-client:polling-xhr');- // rtcp-mux is required in the Plan B SDP.- if ((typeof uLine.rtcpMux !== 'string' ||- uLine.rtcpMux !== 'rtcp-mux') &&- uLine.direction !== 'inactive') {- throw new Error('Cannot convert to Plan B because m-lines ' +- 'without the rtcp-mux attribute were found.');- }+ /**+ * Module exports.+ */- if (uLine.type === 'application') {- session.media.push(uLine);- types.push(uLine.mid);- return;- }+ module.exports = XHR;+ module.exports.Request = Request;- // If we don't have a channel for this uLine.type, then use this- // uLine as the channel basis.- if (typeof type2bl[uLine.type] === 'undefined') {- type2bl[uLine.type] = uLine;- }+ /**+ * Empty function+ */- // Add sources to the channel and handle a=msid.- if (typeof uLine.sources === 'object') {- Object.keys(uLine.sources).forEach(function(ssrc) {- if (typeof type2bl[uLine.type].sources !== 'object')- type2bl[uLine.type].sources = {};+ function empty(){}- // Assign the sources to the channel.- type2bl[uLine.type].sources[ssrc] =- uLine.sources[ssrc];+ /**+ * XHR Polling constructor.+ *+ * @param {Object} opts+ * @api public+ */- if (typeof uLine.msid !== 'undefined') {- // In Plan B the msid is an SSRC attribute. Also, we don't- // care about the obsolete label and mslabel attributes.- //- // Note that it is not guaranteed that the uLine will- // have an msid. recvonly channels in particular don't have- // one.- type2bl[uLine.type].sources[ssrc].msid =- uLine.msid;- }- // NOTE ssrcs in ssrc groups will share msids, as- // draft-uberti-rtcweb-plan-00 mandates.- });- }+ function XHR(opts){+ Polling.call(this, opts);- // Add ssrc groups to the channel.- if (typeof uLine.ssrcGroups !== 'undefined' &&- Array.isArray(uLine.ssrcGroups)) {+ if (global.location) {+ var isSSL = 'https:' == location.protocol;+ var port = location.port;- // Create the ssrcGroups array, if it's not defined.- if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||- !Array.isArray(type2bl[uLine.type].ssrcGroups)) {- type2bl[uLine.type].ssrcGroups = [];- }+ // some user agents have empty `location.port`+ if (!port) {+ port = isSSL ? 443 : 80;+ }- type2bl[uLine.type].ssrcGroups =- type2bl[uLine.type].ssrcGroups.concat(- uLine.ssrcGroups);- }+ this.xd = opts.hostname != global.location.hostname ||+ port != opts.port;+ this.xs = opts.secure != isSSL;+ }+ }- if (type2bl[uLine.type] === uLine) {- // Copy ICE related stuff from the principal media line.- uLine.candidates = media[0].candidates;- uLine.iceUfrag = media[0].iceUfrag;- uLine.icePwd = media[0].icePwd;- uLine.fingerprint = media[0].fingerprint;+ /**+ * Inherits from Polling.+ */- // Plan B mids are in ['audio', 'video', 'data']- uLine.mid = uLine.type;+ inherit(XHR, Polling);- // Plan B doesn't support/need the bundle-only attribute.- delete uLine.bundleOnly;+ /**+ * XHR supports binary+ */- // In Plan B the msid is an SSRC attribute.- delete uLine.msid;+ XHR.prototype.supportsBinary = true;- // Used to build the group:BUNDLE value after this loop.- types.push(uLine.type);+ /**+ * Creates a request.+ *+ * @param {String} method+ * @api private+ */- // Add the channel to the new media array.- session.media.push(uLine);- }- });+ XHR.prototype.request = function(opts){+ opts = opts || {};+ opts.uri = this.uri();+ opts.xd = this.xd;+ opts.xs = this.xs;+ opts.agent = this.agent || false;+ opts.supportsBinary = this.supportsBinary;+ opts.enablesXDR = this.enablesXDR;- // We regenerate the BUNDLE group with the new mids.- session.groups.some(function(group) {- if (group.type === 'BUNDLE') {- group.mids = types.join(' ');- return true;- }- });+ // SSL options for Node.js client+ opts.pfx = this.pfx;+ opts.key = this.key;+ opts.passphrase = this.passphrase;+ opts.cert = this.cert;+ opts.ca = this.ca;+ opts.ciphers = this.ciphers;+ opts.rejectUnauthorized = this.rejectUnauthorized;- // msid semantic- session.msidSemantic = {- semantic: 'WMS',- token: '*'- };+ return new Request(opts);+ };- var resStr = transform.write(session);+ /**+ * Sends data.+ *+ * @param {String} data to send.+ * @param {Function} called upon flush.+ * @api private+ */- return new RTCSessionDescription({- type: desc.type,- sdp: resStr- });+ XHR.prototype.doWrite = function(data, fn){+ var isBinary = typeof data !== 'string' && data !== undefined;+ var req = this.request({ method: 'POST', data: data, isBinary: isBinary });+ var self = this;+ req.on('success', fn);+ req.on('error', function(err){+ self.onError('xhr post error', err);+ });+ this.sendXhr = req;+ };- //#endregion+ /**+ * Starts a poll cycle.+ *+ * @api private+ */++ XHR.prototype.doPoll = function(){+ debug('xhr poll');+ var req = this.request();+ var self = this;+ req.on('data', function(data){+ self.onData(data);+ });+ req.on('error', function(err){+ self.onError('xhr poll error', err);+ });+ this.pollXhr = req;};/**- * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A- * PeerConnection wrapper transforms the SDP to Unified Plan before passing it- * to FF.+ * Request constructor*- * @param desc- * @returns {*}+ * @param {Object} options+ * @api public*/- Interop.prototype.toUnifiedPlan = function(desc) {- var self = this;- //#region Preliminary input validation.- if (typeof desc !== 'object' || desc === null ||- typeof desc.sdp !== 'string') {- console.warn('An empty description was passed as an argument.');- return desc;- }+ function Request(opts){+ this.method = opts.method || 'GET';+ this.uri = opts.uri;+ this.xd = !!opts.xd;+ this.xs = !!opts.xs;+ this.async = false !== opts.async;+ this.data = undefined != opts.data ? opts.data : null;+ this.agent = opts.agent;+ this.isBinary = opts.isBinary;+ this.supportsBinary = opts.supportsBinary;+ this.enablesXDR = opts.enablesXDR;- var session = transform.parse(desc.sdp);+ // SSL options for Node.js client+ this.pfx = opts.pfx;+ this.key = opts.key;+ this.passphrase = opts.passphrase;+ this.cert = opts.cert;+ this.ca = opts.ca;+ this.ciphers = opts.ciphers;+ this.rejectUnauthorized = opts.rejectUnauthorized;- // If the SDP contains no media, there's nothing to transform.- if (typeof session.media === 'undefined' ||- !Array.isArray(session.media) || session.media.length === 0) {- console.warn('The description has no media.');- return desc;- }+ this.create();+ }- // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has- // a video, an audio and a data "channel" at most.- if (session.media.length > 3 || !session.media.every(function(m) {- return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;- })) {- console.warn('This description does not look like Plan B.');- return desc;- }+ /**+ * Mix in `Emitter`.+ */- // Make sure this Plan B SDP can be converted to a Unified Plan SDP.- var mids = [];- session.media.forEach(function(m) {- mids.push(m.mid);- });+ Emitter(Request.prototype);- var hasBundle = false;- if (typeof session.groups !== 'undefined' &&- Array.isArray(session.groups)) {- hasBundle = session.groups.every(function(g) {- return g.type !== 'BUNDLE' ||- arrayEquals.apply(g.mids.sort(), [mids.sort()]);- });- }+ /**+ * Creates the XHR object and sends the request.+ *+ * @api private+ */- if (!hasBundle) {- throw new Error("Cannot convert to Unified Plan because m-lines that" +- " are not bundled were found.");+ Request.prototype.create = function(){+ var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };++ // SSL options for Node.js client+ opts.pfx = this.pfx;+ opts.key = this.key;+ opts.passphrase = this.passphrase;+ opts.cert = this.cert;+ opts.ca = this.ca;+ opts.ciphers = this.ciphers;+ opts.rejectUnauthorized = this.rejectUnauthorized;++ var xhr = this.xhr = new XMLHttpRequest(opts);+ var self = this;++ try {+ debug('xhr open %s: %s', this.method, this.uri);+ xhr.open(this.method, this.uri, this.async);+ if (this.supportsBinary) {+ // This has to be done after open because Firefox is stupid+ // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension+ xhr.responseType = 'arraybuffer';}- //#endregion--- //#region Convert from Plan B to Unified Plan.+ if ('POST' == this.method) {+ try {+ if (this.isBinary) {+ xhr.setRequestHeader('Content-type', 'application/octet-stream');+ } else {+ xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');+ }+ } catch (e) {}+ }- // Unfortunately, a Plan B offer/answer doesn't have enough information to- // rebuild an equivalent Unified Plan offer/answer.- //- // For example, if this is a local answer (in Unified Plan style) that we- // convert to Plan B prior to handing it over to the application (the- // PeerConnection wrapper called us, for instance, after a successful- // createAnswer), we want to remember the m-line at which we've seen the- // (local) SSRC. That's because when the application wants to do call the- // SLD method, forcing us to do the inverse transformation (from Plan B to- // Unified Plan), we need to know to which m-line to assign the (local)- // SSRC. We also need to know all the other m-lines that the original- // answer had and include them in the transformed answer as well.- //- // Another example is if this is a remote offer that we convert to Plan B- // prior to giving it to the application, we want to remember the mid at- // which we've seen the (remote) SSRC.- //- // In the iteration that follows, we use the cached Unified Plan (if it- // exists) to assign mids to ssrcs.+ // ie6 check+ if ('withCredentials' in xhr) {+ xhr.withCredentials = true;+ }- var cached;- if (typeof this.cache[desc.type] !== 'undefined') {- cached = transform.parse(this.cache[desc.type]);+ if (this.hasXDR()) {+ xhr.onload = function(){+ self.onLoad();+ };+ xhr.onerror = function(){+ self.onError(xhr.responseText);+ };+ } else {+ xhr.onreadystatechange = function(){+ if (4 != xhr.readyState) return;+ if (200 == xhr.status || 1223 == xhr.status) {+ self.onLoad();+ } else {+ // make sure the `error` event handler that's user-set+ // does not throw in the same tick and gets caught here+ setTimeout(function(){+ self.onError(xhr.status);+ }, 0);+ }+ };}- var recvonlySsrcs = {- audio: {},- video: {}- };+ debug('xhr data %s', this.data);+ xhr.send(this.data);+ } catch (e) {+ // Need to defer since .create() is called directly fhrom the constructor+ // and thus the 'error' event can only be only bound *after* this exception+ // occurs. Therefore, also, we cannot throw here at all.+ setTimeout(function() {+ self.onError(e);+ }, 0);+ return;+ }- // A helper map that sends mids to m-line objects. We use it later to- // rebuild the Unified Plan style session.media array.- var mid2ul = {};- session.media.forEach(function(bLine) {- if ((typeof bLine.rtcpMux !== 'string' ||- bLine.rtcpMux !== 'rtcp-mux') &&- bLine.direction !== 'inactive') {- throw new Error("Cannot convert to Unified Plan because m-lines " +- "without the rtcp-mux attribute were found.");- }+ if (global.document) {+ this.index = Request.requestsCount++;+ Request.requests[this.index] = this;+ }+ };- if (bLine.type === 'application') {- mid2ul[bLine.mid] = bLine;- return;- }+ /**+ * Called upon successful response.+ *+ * @api private+ */- // With rtcp-mux and bundle all the channels should have the same ICE- // stuff.- var sources = bLine.sources;- var ssrcGroups = bLine.ssrcGroups;- var candidates = bLine.candidates;- var iceUfrag = bLine.iceUfrag;- var icePwd = bLine.icePwd;- var fingerprint = bLine.fingerprint;- var port = bLine.port;+ Request.prototype.onSuccess = function(){+ this.emit('success');+ this.cleanup();+ };- // We'll use the "bLine" object as a prototype for each new "mLine"- // that we create, but first we need to clean it up a bit.- delete bLine.sources;- delete bLine.ssrcGroups;- delete bLine.candidates;- delete bLine.iceUfrag;- delete bLine.icePwd;- delete bLine.fingerprint;- delete bLine.port;- delete bLine.mid;+ /**+ * Called if we have data.+ *+ * @api private+ */- // inverted ssrc group map- var ssrc2group = {};- if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {- ssrcGroups.forEach(function (ssrcGroup) {+ Request.prototype.onData = function(data){+ this.emit('data', data);+ this.onSuccess();+ };- // TODO(gp) find out how to receive simulcast with FF. For the- // time being, hide it.- if (ssrcGroup.semantics === 'SIM') {- return;- }+ /**+ * Called upon error.+ *+ * @api private+ */- // XXX This might brake if an SSRC is in more than one group- // for some reason.- if (typeof ssrcGroup.ssrcs !== 'undefined' &&- Array.isArray(ssrcGroup.ssrcs)) {- ssrcGroup.ssrcs.forEach(function (ssrc) {- if (typeof ssrc2group[ssrc] === 'undefined') {- ssrc2group[ssrc] = [];- }+ Request.prototype.onError = function(err){+ this.emit('error', err);+ this.cleanup(true);+ };- ssrc2group[ssrc].push(ssrcGroup);- });- }- });- }+ /**+ * Cleans up house.+ *+ * @api private+ */- // ssrc to m-line index.- var ssrc2ml = {};+ Request.prototype.cleanup = function(fromError){+ if ('undefined' == typeof this.xhr || null === this.xhr) {+ return;+ }+ // xmlhttprequest+ if (this.hasXDR()) {+ this.xhr.onload = this.xhr.onerror = empty;+ } else {+ this.xhr.onreadystatechange = empty;+ }- if (typeof sources === 'object') {+ if (fromError) {+ try {+ this.xhr.abort();+ } catch(e) {}+ }- // Explode the Plan B channel sources with one m-line per source.- Object.keys(sources).forEach(function(ssrc) {+ if (global.document) {+ delete Request.requests[this.index];+ }- // The (unified) m-line for this SSRC. We either create it from- // scratch or, if it's a grouped SSRC, we re-use a related- // mline. In other words, if the source is grouped with another- // source, put the two together in the same m-line.- var uLine;+ this.xhr = null;+ };- // We assume here that we are the answerer in the O/A, so any- // offers which we translate come from the remote side, while- // answers are local. So the check below is to make that we- // handle receive-only SSRCs in a special way only if they come- // from the remote side.- if (desc.type==='offer') {- // We want to detect SSRCs which are used by a remote peer- // in an m-line with direction=recvonly (i.e. they are- // being used for RTCP only).- // This information would have gotten lost if the remote- // peer used Unified Plan and their local description was- // translated to Plan B. So we use the lack of an MSID- // attribute to deduce a "receive only" SSRC.- if (!sources[ssrc].msid) {- recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];- // Receive-only SSRCs must not create new m-lines. We- // will assign them to an existing m-line later.- return;- }- }+ /**+ * Called upon load.+ *+ * @api private+ */- if (typeof ssrc2group[ssrc] !== 'undefined' &&- Array.isArray(ssrc2group[ssrc])) {- ssrc2group[ssrc].some(function (ssrcGroup) {- // ssrcGroup.ssrcs *is* an Array, no need to check- // again here.- return ssrcGroup.ssrcs.some(function (related) {- if (typeof ssrc2ml[related] === 'object') {- uLine = ssrc2ml[related];- return true;- }- });- });- }+ Request.prototype.onLoad = function(){+ var data;+ try {+ var contentType;+ try {+ contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];+ } catch (e) {}+ if (contentType === 'application/octet-stream') {+ data = this.xhr.response;+ } else {+ if (!this.supportsBinary) {+ data = this.xhr.responseText;+ } else {+ data = 'ok';+ }+ }+ } catch (e) {+ this.onError(e);+ }+ if (null != data) {+ this.onData(data);+ }+ };- if (typeof uLine === 'object') {- // the m-line already exists. Just add the source.- uLine.sources[ssrc] = sources[ssrc];- delete sources[ssrc].msid;- } else {- // Use the "bLine" as a prototype for the "uLine".- uLine = Object.create(bLine);- ssrc2ml[ssrc] = uLine;+ /**+ * Check if it has XDomainRequest.+ *+ * @api private+ */- if (typeof sources[ssrc].msid !== 'undefined') {- // Assign the msid of the source to the m-line. Note- // that it is not guaranteed that the source will have- // msid. In particular "recvonly" sources don't have an- // msid. Note that "recvonly" is a term only defined- // for m-lines.- uLine.msid = sources[ssrc].msid;- uLine.direction = 'sendrecv';- delete sources[ssrc].msid;- }+ Request.prototype.hasXDR = function(){+ return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;+ };- // We assign one SSRC per media line.- uLine.sources = {};- uLine.sources[ssrc] = sources[ssrc];- uLine.ssrcGroups = ssrc2group[ssrc];+ /**+ * Aborts the request.+ *+ * @api public+ */- // Use the cached Unified Plan SDP (if it exists) to assign- // SSRCs to mids.- if (typeof cached !== 'undefined' &&- typeof cached.media !== 'undefined' &&- Array.isArray(cached.media)) {+ Request.prototype.abort = function(){+ this.cleanup();+ };- cached.media.forEach(function (m) {- if (typeof m.sources === 'object') {- Object.keys(m.sources).forEach(function (s) {- if (s === ssrc) {- uLine.mid = m.mid;- }- });- }- });- }+ /**+ * Aborts pending requests when unloading the window. This is needed to prevent+ * memory leaks (e.g. when using IE) and to ensure that no spurious error is+ * emitted.+ */- if (typeof uLine.mid === 'undefined') {+ if (global.document) {+ Request.requestsCount = 0;+ Request.requests = {};+ if (global.attachEvent) {+ global.attachEvent('onunload', unloadHandler);+ } else if (global.addEventListener) {+ global.addEventListener('beforeunload', unloadHandler, false);+ }+ }- // If this is an SSRC that we see for the first time- // assign it a new mid. This is typically the case when- // this method is called to transform a remote- // description for the first time or when there is a- // new SSRC in the remote description because a new- // peer has joined the conference. Local SSRCs should- // have already been added to the map in the toPlanB- // method.- //- // Because FF generates answers in Unified Plan style,- // we MUST already have a cached answer with all the- // local SSRCs mapped to some m-line/mid.+ function unloadHandler() {+ for (var i in Request.requests) {+ if (Request.requests.hasOwnProperty(i)) {+ Request.requests[i].abort();+ }+ }+ }- if (desc.type === 'answer') {- throw new Error("An unmapped SSRC was found.");- }+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"./polling":102,"component-emitter":93,"component-inherit":105,"debug":106,"xmlhttprequest":104}],102:[function(require,module,exports){++},{"./polling":99,"component-emitter":90,"component-inherit":102,"debug":103,"xmlhttprequest":101}],99:[function(require,module,exports){+ /**+ * Module dependencies.+ */- uLine.mid = [bLine.type, '-', ssrc].join('');- }+ var Transport = require('../transport');+ var parseqs = require('parseqs');+ var parser = require('engine.io-parser');+ var inherit = require('component-inherit');+ var debug = require('debug')('engine.io-client:polling');- // Include the candidates in the 1st media line.- uLine.candidates = candidates;- uLine.iceUfrag = iceUfrag;- uLine.icePwd = icePwd;- uLine.fingerprint = fingerprint;- uLine.port = port;+ /**+ * Module exports.+ */- mid2ul[uLine.mid] = uLine;- }- });- }- });+ module.exports = Polling;- // Rebuild the media array in the right order and add the missing mLines- // (missing from the Plan B SDP).- session.media = [];- mids = []; // reuse+ /**+ * Is XHR2 supported?+ */- if (desc.type === 'answer') {+ var hasXHR2 = (function() {+ var XMLHttpRequest = require('xmlhttprequest');+ var xhr = new XMLHttpRequest({ xdomain: false });+ return null != xhr.responseType;+ })();- // The media lines in the answer must match the media lines in the- // offer. The order is important too. Here we assume that Firefox is- // the answerer, so we merely have to use the reconstructed (unified)- // answer to update the cached (unified) answer accordingly.- //- // In the general case, one would have to use the cached (unified)- // offer to find the m-lines that are missing from the reconstructed- // answer, potentially grabbing them from the cached (unified) answer.- // One has to be careful with this approach because inactive m-lines do- // not always have an mid, making it tricky (impossible?) to find where- // exactly and which m-lines are missing from the reconstructed answer.+ /**+ * Polling interface.+ *+ * @param {Object} opts+ * @api private+ */- for (var i = 0; i < cached.media.length; i++) {- var uLine = cached.media[i];+ function Polling(opts){+ var forceBase64 = (opts && opts.forceBase64);+ if (!hasXHR2 || forceBase64) {+ this.supportsBinary = false;+ }+ Transport.call(this, opts);+ }- if (typeof mid2ul[uLine.mid] === 'undefined') {+ /**+ * Inherits from Transport.+ */- // The mid isn't in the reconstructed (unified) answer.- // This is either a (unified) m-line containing a remote- // track only, or a (unified) m-line containing a remote- // track and a local track that has been removed.- // In either case, it MUST exist in the cached- // (unified) answer.- //- // In case this is a removed local track, clean-up- // the (unified) m-line and make sure it's 'recvonly' or- // 'inactive'.+ inherit(Polling, Transport);- delete uLine.msid;- delete uLine.sources;- delete uLine.ssrcGroups;- if (!uLine.direction- || uLine.direction === 'sendrecv')- uLine.direction = 'recvonly';- else if (uLine.direction === 'sendonly')- uLine.direction = 'inactive';- } else {- // This is an (unified) m-line/channel that contains a local- // track (sendrecv or sendonly channel) or it's a unified- // recvonly m-line/channel. In either case, since we're- // going from PlanB -> Unified Plan this m-line MUST- // exist in the cached answer.- }+ /**+ * Transport name.+ */- session.media.push(uLine);+ Polling.prototype.name = 'polling';- if (typeof uLine.mid === 'string') {- // inactive lines don't/may not have an mid.- mids.push(uLine.mid);- }- }- } else {+ /**+ * Opens the socket (triggers polling). We write a PING message to determine+ * when the transport is open.+ *+ * @api private+ */- // SDP offer/answer (and the JSEP spec) forbids removing an m-section- // under any circumstances. If we are no longer interested in sending a- // track, we just remove the msid and ssrc attributes and set it to- // either a=recvonly (as the reofferer, we must use recvonly if the- // other side was previously sending on the m-section, but we can also- // leave the possibility open if it wasn't previously in use), or- // a=inactive.+ Polling.prototype.doOpen = function(){+ this.poll();+ };- if (typeof cached !== 'undefined' &&- typeof cached.media !== 'undefined' &&- Array.isArray(cached.media)) {- cached.media.forEach(function(uLine) {- mids.push(uLine.mid);- if (typeof mid2ul[uLine.mid] !== 'undefined') {- session.media.push(mid2ul[uLine.mid]);- } else {- delete uLine.msid;- delete uLine.sources;- delete uLine.ssrcGroups;- if (!uLine.direction- || uLine.direction === 'sendrecv')- uLine.direction = 'recvonly';- if (!uLine.direction- || uLine.direction === 'sendonly')- uLine.direction = 'inactive';- session.media.push(uLine);- }- });- }+ /**+ * Pauses polling.+ *+ * @param {Function} callback upon buffers are flushed and transport is paused+ * @api private+ */- // Add all the remaining (new) m-lines of the transformed SDP.- Object.keys(mid2ul).forEach(function(mid) {- if (mids.indexOf(mid) === -1) {- mids.push(mid);- if (mid2ul[mid].direction === 'recvonly') {- // This is a remote recvonly channel. Add its SSRC to the- // appropriate sendrecv or sendonly channel.- // TODO(gp) what if we don't have sendrecv/sendonly- // channel?+ Polling.prototype.pause = function(onPause){+ var pending = 0;+ var self = this;++ this.readyState = 'pausing';- session.media.some(function (uLine) {- if ((uLine.direction === 'sendrecv' ||- uLine.direction === 'sendonly') &&- uLine.type === mid2ul[mid].type) {+ function pause(){+ debug('paused');+ self.readyState = 'paused';+ onPause();+ }- // mid2ul[mid] shouldn't have any ssrc-groups- Object.keys(mid2ul[mid].sources).forEach(- function (ssrc) {- uLine.sources[ssrc] =- mid2ul[mid].sources[ssrc];- });+ if (this.polling || !this.writable) {+ var total = 0;- return true;- }- });- } else {- session.media.push(mid2ul[mid]);- }- }- });+ if (this.polling) {+ debug('we are currently polling - waiting to pause');+ total++;+ this.once('pollComplete', function(){+ debug('pre-pause polling complete');+ --total || pause();+ });}- // After we have constructed the Plan Unified m-lines we can figure out- // where (in which m-line) to place the 'recvonly SSRCs'.- // Note: we assume here that we are the answerer in the O/A, so any offers- // which we translate come from the remote side, while answers are local- // (and so our last local description is cached as an 'answer').- ["audio", "video"].forEach(function (type) {- if (!session || !session.media || !Array.isArray(session.media))- return;-- var idx = null;- if (Object.keys(recvonlySsrcs[type]).length > 0) {- idx = self.getFirstSendingIndexFromAnswer(type);- if (idx === null){- // If this is the first offer we receive, we don't have a- // cached answer. Assume that we will be sending media using- // the first m-line for each media type.+ if (!this.writable) {+ debug('we are currently writing - waiting to pause');+ total++;+ this.once('drain', function(){+ debug('pre-pause writing complete');+ --total || pause();+ });+ }+ } else {+ pause();+ }+ };- for (var i = 0; i < session.media.length; i++) {- if (session.media[i].type === type) {- idx = i;- break;- }- }- }- }+ /**+ * Starts polling cycle.+ *+ * @api public+ */- if (idx && session.media.length > idx) {- var mLine = session.media[idx];- Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {- if (mLine.sources && mLine.sources[ssrc]) {- console.warn("Replacing an existing SSRC.");- }- if (!mLine.sources) {- mLine.sources = {};- }+ Polling.prototype.poll = function(){+ debug('polling');+ this.polling = true;+ this.doPoll();+ this.emit('poll');+ };- mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];- });- }- });+ /**+ * Overloads onData to detect payloads.+ *+ * @api private+ */- // We regenerate the BUNDLE group (since we regenerated the mids)- session.groups.some(function(group) {- if (group.type === 'BUNDLE') {- group.mids = mids.join(' ');- return true;- }- });+ Polling.prototype.onData = function(data){+ var self = this;+ debug('polling got data %s', data);+ var callback = function(packet, index, total) {+ // if its the first message we consider the transport open+ if ('opening' == self.readyState) {+ self.onOpen();+ }- // msid semantic- session.msidSemantic = {- semantic: 'WMS',- token: '*'- };+ // if its a close packet, we close the ongoing requests+ if ('close' == packet.type) {+ self.onClose();+ return false;+ }- var resStr = transform.write(session);+ // otherwise bypass onData and handle the message+ self.onPacket(packet);+ };- // Cache the transformed SDP (Unified Plan) for later re-use in this- // function.- this.cache[desc.type] = resStr;+ // decode payload+ parser.decodePayload(data, this.socket.binaryType, callback);- return new RTCSessionDescription({- type: desc.type,- sdp: resStr- });+ // if an event did not trigger closing+ if ('closed' != this.readyState) {+ // if we got data we're not polling+ this.polling = false;+ this.emit('pollComplete');- //#endregion+ if ('open' == this.readyState) {+ this.poll();+ } else {+ debug('ignoring poll - transport state "%s"', this.readyState);+ }+ }};- },{"./array-equals":104,"./transform":107}],107:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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+ /**+ * For polling, send a close packet.*- * http://www.apache.org/licenses/LICENSE-2.0+ * @api private+ */++ Polling.prototype.doClose = function(){+ var self = this;++ function close(){+ debug('writing close packet');+ self.write([{ type: 'close' }]);+ }++ if ('open' == this.readyState) {+ debug('transport open - closing');+ close();+ } else {+ // in case we're trying to close while+ // handshaking is in progress (GH-164)+ debug('transport not open - deferring close');+ this.once('open', close);+ }+ };++ /**+ * Writes a packets payload.*- * 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.+ * @param {Array} data packets+ * @param {Function} drain callback+ * @api private*/- var transform = require('sdp-transform');+ Polling.prototype.write = function(packets){+ var self = this;+ this.writable = false;+ var callbackfn = function() {+ self.writable = true;+ self.emit('drain');+ };- exports.write = function(session, opts) {+ var self = this;+ parser.encodePayload(packets, this.supportsBinary, function(data) {+ self.doWrite(data, callbackfn);+ });+ };- if (typeof session !== 'undefined' &&- typeof session.media !== 'undefined' &&- Array.isArray(session.media)) {+ /**+ * Generates uri for connection.+ *+ * @api private+ */- session.media.forEach(function (mLine) {- // expand sources to ssrcs- if (typeof mLine.sources !== 'undefined' &&- Object.keys(mLine.sources).length !== 0) {- mLine.ssrcs = [];- Object.keys(mLine.sources).forEach(function (ssrc) {- var source = mLine.sources[ssrc];- Object.keys(source).forEach(function (attribute) {- mLine.ssrcs.push({- id: ssrc,- attribute: attribute,- value: source[attribute]- });- });- });- delete mLine.sources;- }+ Polling.prototype.uri = function(){+ var query = this.query || {};+ var schema = this.secure ? 'https' : 'http';+ var port = '';- // join ssrcs in ssrc groups- if (typeof mLine.ssrcGroups !== 'undefined' &&- Array.isArray(mLine.ssrcGroups)) {- mLine.ssrcGroups.forEach(function (ssrcGroup) {- if (typeof ssrcGroup.ssrcs !== 'undefined' &&- Array.isArray(ssrcGroup.ssrcs)) {- ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');- }- });- }- });+ // cache busting is forced+ if (false !== this.timestampRequests) {+ query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;}- // join group mids- if (typeof session !== 'undefined' &&- typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {+ if (!this.supportsBinary && !query.sid) {+ query.b64 = 1;+ }++ query = parseqs.encode(query);++ // avoid port if default for schema+ if (this.port && (('https' == schema && this.port != 443) ||+ ('http' == schema && this.port != 80))) {+ port = ':' + this.port;+ }- session.groups.forEach(function (g) {- if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {- g.mids = g.mids.join(' ');- }- });+ // prepend ? to query+ if (query.length) {+ query = '?' + query;}- return transform.write(session, opts);+ return schema + '://' + this.hostname + port + this.path + query;};- exports.parse = function(sdp) {- var session = transform.parse(sdp);-- if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&- Array.isArray(session.media)) {-},{"../transport":98,"component-inherit":105,"debug":106,"engine.io-parser":109,"parseqs":121,"xmlhttprequest":104}],103:[function(require,module,exports){++},{"../transport":95,"component-inherit":102,"debug":103,"engine.io-parser":106,"parseqs":118,"xmlhttprequest":101}],100:[function(require,module,exports){+ /**+ * Module dependencies.+ */- session.media.forEach(function (mLine) {- // group sources attributes by ssrc- if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {- mLine.sources = {};- mLine.ssrcs.forEach(function (ssrc) {- if (!mLine.sources[ssrc.id])- mLine.sources[ssrc.id] = {};- mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;- });+ var Transport = require('../transport');+ var parser = require('engine.io-parser');+ var parseqs = require('parseqs');+ var inherit = require('component-inherit');+ var debug = require('debug')('engine.io-client:websocket');- delete mLine.ssrcs;- }+ /**+ * `ws` exposes a WebSocket-compatible interface in+ * Node, or the `WebSocket` or `MozWebSocket` globals+ * in the browser.+ */- // split ssrcs in ssrc groups- if (typeof mLine.ssrcGroups !== 'undefined' &&- Array.isArray(mLine.ssrcGroups)) {- mLine.ssrcGroups.forEach(function (ssrcGroup) {- if (typeof ssrcGroup.ssrcs === 'string') {- ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');- }- });- }- });- }- // split group mids- if (typeof session !== 'undefined' &&- typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {+ var WebSocket = require('ws');- session.groups.forEach(function (g) {- if (typeof g.mids === 'string') {- g.mids = g.mids.split(' ');- }- });- }+ /**+ * Module exports.+ */- return session;- };+ module.exports = WS;+ /**+ * WebSocket transport constructor.+ *+ * @api {Object} connection options+ * @api public+ */- },{"sdp-transform":109}],108:[function(require,module,exports){- var grammar = module.exports = {- v: [{- name: 'version',- reg: /^(\d*)$/- }],- o: [{ //o=- 20518 0 IN IP4 203.0.113.1- // NB: sessionId will be a String in most cases because it is huge- name: 'origin',- reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,- names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],- format: "%s %s %d %s IP%d %s"- }],- // default parsing of these only (though some of these feel outdated)- s: [{ name: 'name' }],- i: [{ name: 'description' }],- u: [{ name: 'uri' }],- e: [{ name: 'email' }],- p: [{ name: 'phone' }],- z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..- r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly- //k: [{}], // outdated thing ignored- t: [{ //t=0 0- name: 'timing',- reg: /^(\d*) (\d*)/,- names: ['start', 'stop'],- format: "%d %d"- }],- c: [{ //c=IN IP4 10.47.197.26- name: 'connection',- reg: /^IN IP(\d) (\S*)/,- names: ['version', 'ip'],- format: "IN IP%d %s"- }],- b: [{ //b=AS:4000- push: 'bandwidth',- reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,- names: ['type', 'limit'],- format: "%s:%s"- }],- m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31- // NB: special - pushes to session- // TODO: rtp/fmtp should be filtered by the payloads found here?- reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,- names: ['type', 'port', 'protocol', 'payloads'],- format: "%s %d %s %s"- }],- a: [- { //a=rtpmap:110 opus/48000/2- push: 'rtp',- reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,- names: ['payload', 'codec', 'rate', 'encoding'],- format: function (o) {- return (o.encoding) ?- "rtpmap:%d %s/%s/%s":- o.rate ?- "rtpmap:%d %s/%s":- "rtpmap:%d %s";- }- },- {- //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000- //a=fmtp:111 minptime=10; useinbandfec=1- push: 'fmtp',- reg: /^fmtp:(\d*) ([\S| ]*)/,- names: ['payload', 'config'],- format: "fmtp:%d %s"- },- { //a=control:streamid=0- name: 'control',- reg: /^control:(.*)/,- format: "control:%s"- },- { //a=rtcp:65179 IN IP4 193.84.77.194- name: 'rtcp',- reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,- names: ['port', 'netType', 'ipVer', 'address'],- format: function (o) {- return (o.address != null) ?- "rtcp:%d %s IP%d %s":- "rtcp:%d";- }- },- { //a=rtcp-fb:98 trr-int 100- push: 'rtcpFbTrrInt',- reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,- names: ['payload', 'value'],- format: "rtcp-fb:%d trr-int %d"- },- { //a=rtcp-fb:98 nack rpsi- push: 'rtcpFb',- reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,- names: ['payload', 'type', 'subtype'],- format: function (o) {- return (o.subtype != null) ?- "rtcp-fb:%s %s %s":- "rtcp-fb:%s %s";- }- },- { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset- //a=extmap:1/recvonly URI-gps-string- push: 'ext',- reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,- names: ['value', 'uri', 'config'], // value may include "/direction" suffix- format: function (o) {- return (o.config != null) ?- "extmap:%s %s %s":- "extmap:%s %s";- }- },- {- //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32- push: 'crypto',- reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,- names: ['id', 'suite', 'config', 'sessionConfig'],- format: function (o) {- return (o.sessionConfig != null) ?- "crypto:%d %s %s %s":- "crypto:%d %s %s";- }- },- { //a=setup:actpass- name: 'setup',- reg: /^setup:(\w*)/,- format: "setup:%s"- },- { //a=mid:1- name: 'mid',- reg: /^mid:([^\s]*)/,- format: "mid:%s"- },- { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a- name: 'msid',- reg: /^msid:(.*)/,- format: "msid:%s"- },- { //a=ptime:20- name: 'ptime',- reg: /^ptime:(\d*)/,- format: "ptime:%d"- },- { //a=maxptime:60- name: 'maxptime',- reg: /^maxptime:(\d*)/,- format: "maxptime:%d"- },- { //a=sendrecv- name: 'direction',- reg: /^(sendrecv|recvonly|sendonly|inactive)/- },- { //a=ice-lite- name: 'icelite',- reg: /^(ice-lite)/- },- { //a=ice-ufrag:F7gI- name: 'iceUfrag',- reg: /^ice-ufrag:(\S*)/,- format: "ice-ufrag:%s"- },- { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g- name: 'icePwd',- reg: /^ice-pwd:(\S*)/,- format: "ice-pwd:%s"- },- { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33- name: 'fingerprint',- reg: /^fingerprint:(\S*) (\S*)/,- names: ['type', 'hash'],- format: "fingerprint:%s %s"- },- {- //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host- //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0- //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0- //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0- //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0- push:'candidates',- reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,- names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],- format: function (o) {- var str = "candidate:%s %d %s %d %s %d typ %s";+ function WS(opts){+ var forceBase64 = (opts && opts.forceBase64);+ if (forceBase64) {+ this.supportsBinary = false;+ }+ Transport.call(this, opts);+ }- str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";+ /**+ * Inherits from Transport.+ */- // NB: candidate has three optional chunks, so %void middles one if it's missing- str += (o.tcptype != null) ? " tcptype %s" : "%v";+ inherit(WS, Transport);- if (o.generation != null) {- str += " generation %d";- }- return str;+ /**+ * Transport name.+ *+ * @api public+ */++ WS.prototype.name = 'websocket';++ /*+ * WebSockets support binary+ */++ WS.prototype.supportsBinary = true;++ /**+ * Opens socket.+ *+ * @api private+ */++ WS.prototype.doOpen = function(){+ if (!this.check()) {+ // let probe timeout+ return;+ }++ var self = this;+ var uri = this.uri();+ var protocols = void(0);+ var opts = { agent: this.agent };++ // SSL options for Node.js client+ opts.pfx = this.pfx;+ opts.key = this.key;+ opts.passphrase = this.passphrase;+ opts.cert = this.cert;+ opts.ca = this.ca;+ opts.ciphers = this.ciphers;+ opts.rejectUnauthorized = this.rejectUnauthorized;++ this.ws = new WebSocket(uri, protocols, opts);++ if (this.ws.binaryType === undefined) {+ this.supportsBinary = false;+ }++ this.ws.binaryType = 'arraybuffer';+ this.addEventListeners();+ };++ /**+ * Adds event listeners to the socket+ *+ * @api private+ */++ WS.prototype.addEventListeners = function(){+ var self = this;++ this.ws.onopen = function(){+ self.onOpen();+ };+ this.ws.onclose = function(){+ self.onClose();+ };+ this.ws.onmessage = function(ev){+ self.onData(ev.data);+ };+ this.ws.onerror = function(e){+ self.onError('websocket error', e);+ };+ };++ /**+ * Override `onData` to use a timer on iOS.+ * See: https://gist.github.com/mloughran/2052006+ *+ * @api private+ */++ if ('undefined' != typeof navigator+ && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {+ WS.prototype.onData = function(data){+ var self = this;+ setTimeout(function(){+ Transport.prototype.onData.call(self, data);+ }, 0);+ };+ }++ /**+ * Writes data to socket.+ *+ * @param {Array} array of packets.+ * @api private+ */++ WS.prototype.write = function(packets){+ var self = this;+ this.writable = false;+ // encodePacket efficient as it uses WS framing+ // no need for encodePayload+ for (var i = 0, l = packets.length; i < l; i++) {+ parser.encodePacket(packets[i], this.supportsBinary, function(data) {+ //Sometimes the websocket has already been closed but the browser didn't+ //have a chance of informing us about it yet, in that case send will+ //throw an error+ try {+ self.ws.send(data);+ } catch (e){+ debug('websocket closed before onclose event');}- },- { //a=end-of-candidates (keep after the candidates line for readability)- name: 'endOfCandidates',- reg: /^(end-of-candidates)/- },- { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...- name: 'remoteCandidates',- reg: /^remote-candidates:(.*)/,- format: "remote-candidates:%s"- },- { //a=ice-options:google-ice- name: 'iceOptions',- reg: /^ice-options:(\S*)/,- format: "ice-options:%s"- },- { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1- push: "ssrcs",- reg: /^ssrc:(\d*) ([\w_]*):(.*)/,- names: ['id', 'attribute', 'value'],- format: "ssrc:%d %s:%s"- },- { //a=ssrc-group:FEC 1 2- push: "ssrcGroups",- reg: /^ssrc-group:(\w*) (.*)/,- names: ['semantics', 'ssrcs'],- format: "ssrc-group:%s %s"- },- { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV- name: "msidSemantic",- reg: /^msid-semantic:\s?(\w*) (\S*)/,- names: ['semantic', 'token'],- format: "msid-semantic: %s %s" // space after ":" is not accidental- },- { //a=group:BUNDLE audio video- push: 'groups',- reg: /^group:(\w*) (.*)/,- names: ['type', 'mids'],- format: "group:%s %s"- },- { //a=rtcp-mux- name: 'rtcpMux',- reg: /^(rtcp-mux)/- },- { //a=rtcp-rsize- name: 'rtcpRsize',- reg: /^(rtcp-rsize)/- },- { // any a= that we don't understand is kepts verbatim on media.invalid- push: 'invalid',- names: ["value"]- }- ]+ });+ }++ function ondrain() {+ self.writable = true;+ self.emit('drain');+ }+ // fake drain+ // defer to next tick to allow Socket to clear writeBuffer+ setTimeout(ondrain, 0);};- // set sensible defaults to avoid polluting the grammar with boring details- Object.keys(grammar).forEach(function (key) {- var objs = grammar[key];- objs.forEach(function (obj) {- if (!obj.reg) {- obj.reg = /(.*)/;- }- if (!obj.format) {- obj.format = "%s";- }- });- });+ /**+ * Called upon close+ *+ * @api private+ */- },{}],109:[function(require,module,exports){- var parser = require('./parser');- var writer = require('./writer');+ WS.prototype.onClose = function(){+ Transport.prototype.onClose.call(this);+ };- exports.write = writer;- exports.parse = parser.parse;- exports.parseFmtpConfig = parser.parseFmtpConfig;- exports.parsePayloads = parser.parsePayloads;- exports.parseRemoteCandidates = parser.parseRemoteCandidates;+ /**+ * Closes socket.+ *+ * @api private+ */- },{"./parser":110,"./writer":111}],110:[function(require,module,exports){- var toIntIfInt = function (v) {- return String(Number(v)) === v ? Number(v) : v;+ WS.prototype.doClose = function(){+ if (typeof this.ws !== 'undefined') {+ this.ws.close();+ }};- var attachProperties = function (match, location, names, rawName) {- if (rawName && !names) {- location[rawName] = toIntIfInt(match[1]);+ /**+ * Generates uri for connection.+ *+ * @api private+ */++ WS.prototype.uri = function(){+ var query = this.query || {};+ var schema = this.secure ? 'wss' : 'ws';+ var port = '';++ // avoid port if default for schema+ if (this.port && (('wss' == schema && this.port != 443)+ || ('ws' == schema && this.port != 80))) {+ port = ':' + this.port;}- else {- for (var i = 0; i < names.length; i += 1) {- if (match[i+1] != null) {- location[names[i]] = toIntIfInt(match[i+1]);- }- }++ // append timestamp to URI+ if (this.timestampRequests) {+ query[this.timestampParam] = +new Date;}- };- var parseReg = function (obj, location, content) {- var needsBlank = obj.name && obj.names;- if (obj.push && !location[obj.push]) {- location[obj.push] = [];- }- else if (needsBlank && !location[obj.name]) {- location[obj.name] = {};+ // communicate binary support capabilities+ if (!this.supportsBinary) {+ query.b64 = 1;}- var keyLocation = obj.push ?- {} : // blank object that will be pushed- needsBlank ? location[obj.name] : location; // otherwise, named location or root- attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);+ query = parseqs.encode(query);- if (obj.push) {- location[obj.push].push(keyLocation);+ // prepend ? to query+ if (query.length) {+ query = '?' + query;}++ return schema + '://' + this.hostname + port + this.path + query;};- var grammar = require('./grammar');- var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);+ /**+ * Feature detection for WebSocket.+ *+ * @return {Boolean} whether this transport is available.+ * @api public+ */- exports.parse = function (sdp) {- var session = {}- , media = []- , location = session; // points at where properties go under (one of the above)+ WS.prototype.check = function(){+ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);+ };- // parse lines we understand- sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {- var type = l[0];- var content = l.slice(2);- if (type === 'm') {- media.push({rtp: [], fmtp: []});- location = media[media.length-1]; // point at latest media line- }-},{"../transport":98,"component-inherit":105,"debug":106,"engine.io-parser":109,"parseqs":121,"ws":123}],104:[function(require,module,exports){++},{"../transport":95,"component-inherit":102,"debug":103,"engine.io-parser":106,"parseqs":118,"ws":120}],101:[function(require,module,exports){+ // browser shim for xmlhttprequest module+ var hasCORS = require('has-cors');- for (var j = 0; j < (grammar[type] || []).length; j += 1) {- var obj = grammar[type][j];- if (obj.reg.test(content)) {- return parseReg(obj, location, content);- }+ module.exports = function(opts) {+ var xdomain = opts.xdomain;++ // scheme must be same when usign XDomainRequest+ // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx+ var xscheme = opts.xscheme;++ // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.+ // https://github.com/Automattic/engine.io-client/pull/217+ var enablesXDR = opts.enablesXDR;++ // XMLHttpRequest can be disabled on IE+ try {+ if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {+ return new XMLHttpRequest();}- });+ } catch (e) { }- session.media = media; // link it up- return session;- };+ // Use XDomainRequest for IE8 if enablesXDR is true+ // because loading bar keeps flashing when using jsonp-polling+ // https://github.com/yujiosaka/socke.io-ie8-loading-example+ try {+ if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {+ return new XDomainRequest();+ }+ } catch (e) { }- var fmtpReducer = function (acc, expr) {- var s = expr.split('=');- if (s.length === 2) {- acc[s[0]] = toIntIfInt(s[1]);+ if (!xdomain) {+ try {+ return new ActiveXObject('Microsoft.XMLHTTP');+ } catch(e) { }}- return acc;- };+ }- exports.parseFmtpConfig = function (str) {- return str.split(/\;\s?/).reduce(fmtpReducer, {});- };-},{"has-cors":118}],105:[function(require,module,exports){++},{"has-cors":115}],102:[function(require,module,exports){- exports.parsePayloads = function (str) {- return str.split(' ').map(Number);+ module.exports = function(a, b){+ var fn = function(){};+ fn.prototype = b.prototype;+ a.prototype = new fn;+ a.prototype.constructor = a;};-},{}],106:[function(require,module,exports){++},{}],103:[function(require,module,exports){- exports.parseRemoteCandidates = function (str) {- var candidates = [];- var parts = str.split(' ').map(toIntIfInt);- for (var i = 0; i < parts.length; i += 3) {- candidates.push({- component: parts[i],- ip: parts[i + 1],- port: parts[i + 2]- });- }- return candidates;- };+ /**+ * This is the web browser implementation of `debug()`.+ *+ * Expose `debug()` as the module.+ */- },{"./grammar":108}],111:[function(require,module,exports){- var grammar = require('./grammar');+ exports = module.exports = require('./debug');+ exports.log = log;+ exports.formatArgs = formatArgs;+ exports.save = save;+ exports.load = load;+ exports.useColors = useColors;- // customized util.format - discards excess arguments and can void middle ones- var formatRegExp = /%[sdv%]/g;- var format = function (formatStr) {- var i = 1;- var args = arguments;- var len = args.length;- return formatStr.replace(formatRegExp, function (x) {- if (i >= len) {- return x; // missing argument- }- var arg = args[i];- i += 1;- switch (x) {- case '%%':- return '%';- case '%s':- return String(arg);- case '%d':- return Number(arg);- case '%v':- return '';- }- });- // NB: we discard excess arguments - they are typically undefined from makeLine- };+ /**+ * Colors.+ */- var makeLine = function (type, obj, location) {- var str = obj.format instanceof Function ?- (obj.format(obj.push ? location : location[obj.name])) :- obj.format;+ exports.colors = [+ 'lightseagreen',+ 'forestgreen',+ 'goldenrod',+ 'dodgerblue',+ 'darkorchid',+ 'crimson'+ ];- var args = [type + '=' + str];- if (obj.names) {- for (var i = 0; i < obj.names.length; i += 1) {- var n = obj.names[i];- if (obj.name) {- args.push(location[obj.name][n]);- }- else { // for mLine and push attributes- args.push(location[obj.names[i]]);- }- }- }- else {- args.push(location[obj.name]);- }- return format.apply(null, args);+ /**+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,+ * and the Firebug extension (any Firefox version) are known+ * to support "%c" CSS customizations.+ *+ * TODO: add a `localStorage` variable to explicitly enable/disable colors+ */++ function useColors() {+ // is webkit? http://stackoverflow.com/a/16459606/376773+ return ('WebkitAppearance' in document.documentElement.style) ||+ // is firebug? http://stackoverflow.com/a/398120/376773+ (window.console && (console.firebug || (console.exception && console.table))) ||+ // is firefox >= v31?+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages+ (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);+ }++ /**+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.+ */++ exports.formatters.j = function(v) {+ return JSON.stringify(v);};- // RFC specified order- // TODO: extend this with all the rest- var defaultOuterOrder = [- 'v', 'o', 's', 'i',- 'u', 'e', 'p', 'c',- 'b', 't', 'r', 'z', 'a'- ];- var defaultInnerOrder = ['i', 'c', 'b', 'a'];+ /**+ * Colorize log arguments if enabled.+ *+ * @api public+ */- module.exports = function (session, opts) {- opts = opts || {};- // ensure certain properties exist- if (session.version == null) {- session.version = 0; // "v=0" must be there (only defined version atm)- }- if (session.name == null) {- session.name = " "; // "s= " must be there if no meaningful name set- }- session.media.forEach(function (mLine) {- if (mLine.payloads == null) {- mLine.payloads = "";+ function formatArgs() {+ var args = arguments;+ var useColors = this.useColors;++ args[0] = (useColors ? '%c' : '')+ + this.namespace+ + (useColors ? ' %c' : ' ')+ + args[0]+ + (useColors ? '%c ' : ' ')+ + '+' + exports.humanize(this.diff);++ if (!useColors) return args;++ var c = 'color: ' + this.color;+ args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));++ // the final "%c" is somewhat tricky, because there could be other+ // arguments passed either before or after the %c, so we need to+ // figure out the correct index to insert the CSS into+ var index = 0;+ var lastC = 0;+ args[0].replace(/%[a-z%]/g, function(match) {+ if ('%%' === match) return;+ index++;+ if ('%c' === match) {+ // we only are interested in the *last* %c+ // (the user may have provided their own)+ lastC = index;}});- var outerOrder = opts.outerOrder || defaultOuterOrder;- var innerOrder = opts.innerOrder || defaultInnerOrder;- var sdp = [];+ args.splice(lastC, 0, c);+ return args;+ }- // loop through outerOrder for matching properties on session- outerOrder.forEach(function (type) {- grammar[type].forEach(function (obj) {- if (obj.name in session && session[obj.name] != null) {- sdp.push(makeLine(type, obj, session));- }- else if (obj.push in session && session[obj.push] != null) {- session[obj.push].forEach(function (el) {- sdp.push(makeLine(type, obj, el));- });- }- });- });+ /**+ * Invokes `console.log()` when available.+ * No-op when `console.log` is not a "function".+ *+ * @api public+ */- // then for each media line, follow the innerOrder- session.media.forEach(function (mLine) {- sdp.push(makeLine('m', grammar.m[0], mLine));+ function log() {+ // This hackery is required for IE8,+ // where the `console.log` function doesn't have 'apply'+ return 'object' == typeof console+ && 'function' == typeof console.log+ && Function.prototype.apply.call(console.log, console, arguments);+ }- innerOrder.forEach(function (type) {- grammar[type].forEach(function (obj) {- if (obj.name in mLine && mLine[obj.name] != null) {- sdp.push(makeLine(type, obj, mLine));- }- else if (obj.push in mLine && mLine[obj.push] != null) {- mLine[obj.push].forEach(function (el) {- sdp.push(makeLine(type, obj, el));- });- }- });- });- });+ /**+ * Save `namespaces`.+ *+ * @param {String} namespaces+ * @api private+ */- return sdp.join('\r\n') + '\r\n';- };+ function save(namespaces) {+ try {+ if (null == namespaces) {+ localStorage.removeItem('debug');+ } else {+ localStorage.debug = namespaces;+ }+ } catch(e) {}+ }- },{"./grammar":108}],112:[function(require,module,exports){- /* Copyright @ 2015 Atlassian Pty Ltd- *- * 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+ /**+ * Load `namespaces`.*- * http://www.apache.org/licenses/LICENSE-2.0+ * @return {String} returns the previously persisted debug modes+ * @api private+ */++ function load() {+ var r;+ try {+ r = localStorage.debug;+ } catch(e) {}+ return r;+ }++ /**+ * Enable namespaces listed in `localStorage.debug` initially.+ */++ exports.enable(load());+-},{"./debug":107}],107:[function(require,module,exports){++},{"./debug":104}],104:[function(require,module,exports){++ /**+ * This is the common logic for both the Node.js and web browser+ * implementations of `debug()`.*- * 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.+ * Expose `debug()` as the module.*/- var transform = require('sdp-transform');- var transformUtils = require('./transform-utils');- var parseSsrcs = transformUtils.parseSsrcs;- var writeSsrcs = transformUtils.writeSsrcs;+ exports = module.exports = debug;+ exports.coerce = coerce;+ exports.disable = disable;+ exports.enable = enable;+ exports.enabled = enabled;+ exports.humanize = require('ms');- //region Constants+ /**+ * The currently active debug mode names, and names to skip.+ */- var DEFAULT_NUM_OF_LAYERS = 3;+ exports.names = [];+ exports.skips = [];- //endregion+ /**+ * Map of special "%n" handling functions, for the debug "format" argument.+ *+ * Valid key names are a single, lowercased letter, i.e. "n".+ */- //region Ctor+ exports.formatters = {};- function Simulcast(options) {+ /**+ * Previously assigned color.+ */- this.options = options ? options : {};+ var prevColor = 0;- if (!this.options.numOfLayers) {- this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;- }+ /**+ * Previous log timestamp.+ */- this.layers = [];- }+ var prevTime;- //endregion+ /**+ * Select a color.+ *+ * @return {Number}+ * @api private+ */- //region Stateless private utility functions+ function selectColor() {+ return exports.colors[prevColor++ % exports.colors.length];+ }/**- * Returns a random integer between min (included) and max (excluded)- * Using Math.round() gives a non-uniform distribution!- * @returns {number}+ * Create a debugger with the given `namespace`.+ *+ * @param {String} namespace+ * @return {Function}+ * @api public*/- function generateSSRC() {- var min = 0, max = 0xffffffff;- return Math.floor(Math.random() * (max - min)) + min;- };- function processVideo(session, action) {- if (session == null || !Array.isArray(session.media)) {- return;+ function debug(namespace) {++ // define the `disabled` version+ function disabled() {+ }+ disabled.enabled = false;++ // define the `enabled` version+ function enabled() {++ var self = enabled;++ // set `diff` timestamp+ var curr = +new Date();+ var ms = curr - (prevTime || curr);+ self.diff = ms;+ self.prev = prevTime;+ self.curr = curr;+ prevTime = curr;++ // add the `color` if not set+ if (null == self.useColors) self.useColors = exports.useColors();+ if (null == self.color && self.useColors) self.color = selectColor();++ var args = Array.prototype.slice.call(arguments);++ args[0] = exports.coerce(args[0]);++ if ('string' !== typeof args[0]) {+ // anything else let's inspect with %o+ args = ['%o'].concat(args);}- session.media.forEach(function (mLine) {- if (mLine.type === 'video') {- action(mLine);- }+ // apply any `formatters` transformations+ var index = 0;+ args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {+ // if we encounter an escaped % then don't increase the array index+ if (match === '%%') return match;+ index++;+ var formatter = exports.formatters[format];+ if ('function' === typeof formatter) {+ var val = args[index];+ match = formatter.call(self, val);++ // now we need to remove `args[index]` since it's inlined in the `format`+ args.splice(index, 1);+ index--;+ }+ return match;});- }- function validateDescription(desc)- {- return desc && desc != null- && desc.type && desc.type != ''- && desc.sdp && desc.sdp != '';+ if ('function' === typeof exports.formatArgs) {+ args = exports.formatArgs.apply(self, args);+ }+ var logFn = enabled.log || exports.log || console.log.bind(console);+ logFn.apply(self, args);+ }+ enabled.enabled = true;++ var fn = exports.enabled(namespace) ? enabled : disabled;++ fn.namespace = namespace;++ return fn;}- function explodeRemoteSimulcast(mLine) {+ /**+ * Enables a debug mode by namespaces. This can include modes+ * separated by a colon and wildcards.+ *+ * @param {String} namespaces+ * @api public+ */- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {- return;+ function enable(namespaces) {+ exports.save(namespaces);++ var split = (namespaces || '').split(/[\s,]+/);+ var len = split.length;++ for (var i = 0; i < len; i++) {+ if (!split[i]) continue; // ignore empty strings+ namespaces = split[i].replace(/\*/g, '.*?');+ if (namespaces[0] === '-') {+ exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));+ } else {+ exports.names.push(new RegExp('^' + namespaces + '$'));}+ }+ }- var sources = parseSsrcs(mLine);- var order = [];+ /**+ * Disable debug output.+ *+ * @api public+ */- // Find the SIM group and explode its sources.- var j = mLine.ssrcGroups.length;- while (j--) {+ function disable() {+ exports.enable('');+ }- if (mLine.ssrcGroups[j].semantics !== 'SIM') {- continue;- }+ /**+ * Returns true if the given mode name is enabled, false otherwise.+ *+ * @param {String} name+ * @return {Boolean}+ * @api public+ */- var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');+ function enabled(name) {+ var i, len;+ for (i = 0, len = exports.skips.length; i < len; i++) {+ if (exports.skips[i].test(name)) {+ return false;+ }+ }+ for (i = 0, len = exports.names.length; i < len; i++) {+ if (exports.names[i].test(name)) {+ return true;+ }+ }+ return false;+ }- for (var i = 0; i < simulcastSsrcs.length; i++) {+ /**+ * Coerce `val`.+ *+ * @param {Mixed} val+ * @return {Mixed}+ * @api private+ */- var ssrc = simulcastSsrcs[i];- order.push(ssrc);+ function coerce(val) {+ if (val instanceof Error) return val.stack || val.message;+ return val;+ }- var parts = sources[ssrc].msid.split(' ');- sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');- sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');-},{"ms":108}],108:[function(require,module,exports){++},{"ms":105}],105:[function(require,module,exports){+ /**+ * Helpers.+ */- // Remove all the groups that this SSRC participates in.- mLine.ssrcGroups.forEach(function (relatedGroup) {- if (relatedGroup.semantics === 'SIM') {- return;- }+ var s = 1000;+ var m = s * 60;+ var h = m * 60;+ var d = h * 24;+ var y = d * 365.25;- var relatedSsrcs = relatedGroup.ssrcs.split(' ');- if (relatedSsrcs.indexOf(ssrc) === -1) {- return;- }+ /**+ * Parse or format the given `val`.+ *+ * Options:+ *+ * - `long` verbose formatting [false]+ *+ * @param {String|Number} val+ * @param {Object} options+ * @return {String|Number}+ * @api public+ */- // Nuke all the related SSRCs.- relatedSsrcs.forEach(function (relatedSSRC) {- sources[relatedSSRC].msid = sources[ssrc].msid;- sources[relatedSSRC].cname = sources[ssrc].cname;- if (relatedSSRC !== ssrc) {- order.push(relatedSSRC);- }- });+ module.exports = function(val, options){+ options = options || {};+ if ('string' == typeof val) return parse(val);+ return options.long+ ? long(val)+ : short(val);+ };- // Schedule the related group for nuking.- })- }+ /**+ * Parse the given `str` and return milliseconds.+ *+ * @param {String} str+ * @return {Number}+ * @api private+ */- mLine.ssrcs = writeSsrcs(sources, order);- mLine.ssrcGroups.splice(j, 1);- };+ function parse(str) {+ var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);+ if (!match) return;+ var n = parseFloat(match[1]);+ var type = (match[2] || 'ms').toLowerCase();+ switch (type) {+ case 'years':+ case 'year':+ case 'y':+ return n * y;+ case 'days':+ case 'day':+ case 'd':+ return n * d;+ case 'hours':+ case 'hour':+ case 'h':+ return n * h;+ case 'minutes':+ case 'minute':+ case 'm':+ return n * m;+ case 'seconds':+ case 'second':+ case 's':+ return n * s;+ case 'ms':+ return n;+ }}- function implodeRemoteSimulcast(mLine) {-- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {- console.info('Halt: There are no SSRC groups in the remote ' +- 'description.');- return;- }+ /**+ * Short format for `ms`.+ *+ * @param {Number} ms+ * @return {String}+ * @api private+ */- var sources = parseSsrcs(mLine);+ function short(ms) {+ if (ms >= d) return Math.round(ms / d) + 'd';+ if (ms >= h) return Math.round(ms / h) + 'h';+ if (ms >= m) return Math.round(ms / m) + 'm';+ if (ms >= s) return Math.round(ms / s) + 's';+ return ms + 'ms';+ }- // Find the SIM group and nuke it.- mLine.ssrcGroups.forEach(function (simulcastGroup) {- if (simulcastGroup.semantics !== 'SIM') {- return;- }+ /**+ * Long format for `ms`.+ *+ * @param {Number} ms+ * @return {String}+ * @api private+ */- console.info("Imploding SIM group: " + simulcastGroup.ssrcs);- // Schedule the SIM group for nuking.- simulcastGroup.nuke = true;+ function long(ms) {+ return plural(ms, d, 'day')+ || plural(ms, h, 'hour')+ || plural(ms, m, 'minute')+ || plural(ms, s, 'second')+ || ms + ' ms';+ }- var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');+ /**+ * Pluralization helper.+ */- // Nuke all the higher layer SSRCs.- for (var i = 1; i < simulcastSsrcs.length; i++) {+ function plural(ms, n, name) {+ if (ms < n) return;+ if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;+ return Math.ceil(ms / n) + ' ' + name + 's';+ }- var ssrc = simulcastSsrcs[i];- delete sources[ssrc];-},{}],109:[function(require,module,exports){++},{}],106:[function(require,module,exports){+ (function (global){+ /**+ * Module dependencies.+ */- // Remove all the groups that this SSRC participates in.- mLine.ssrcGroups.forEach(function (relatedGroup) {- if (relatedGroup.semantics === 'SIM') {- return;- }+ var keys = require('./keys');+ var hasBinary = require('has-binary');+ var sliceBuffer = require('arraybuffer.slice');+ var base64encoder = require('base64-arraybuffer');+ var after = require('after');+ var utf8 = require('utf8');- var relatedSsrcs = relatedGroup.ssrcs.split(' ');- if (relatedSsrcs.indexOf(ssrc) === -1) {- return;- }+ /**+ * Check if we are running an android browser. That requires us to use+ * ArrayBuffer with polling transports...+ *+ * http://ghinda.net/jpeg-blob-ajax-android/+ */- // Nuke all the related SSRCs.- relatedSsrcs.forEach(function (relatedSSRC) {- delete sources[relatedSSRC];- });+ var isAndroid = navigator.userAgent.match(/Android/i);- // Schedule the related group for nuking.- relatedGroup.nuke = true;- })- }+ /**+ * Check if we are running in PhantomJS.+ * Uploading a Blob with PhantomJS does not work correctly, as reported here:+ * https://github.com/ariya/phantomjs/issues/11395+ * @type boolean+ */+ var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);- return;- });+ /**+ * When true, avoids using Blobs to encode payloads.+ * @type boolean+ */+ var dontSendBlobs = isAndroid || isPhantomJS;- mLine.ssrcs = writeSsrcs(sources);+ /**+ * Current protocol version.+ */- // Nuke all the scheduled groups.- var i = mLine.ssrcGroups.length;- while (i--) {- if (mLine.ssrcGroups[i].nuke) {- mLine.ssrcGroups.splice(i, 1);- }- }- }+ exports.protocol = 3;- function removeGoogConference(mLine) {- if (!mLine || !Array.isArray(mLine.invalid)) {- return;- }+ /**+ * Packet types.+ */- var i = mLine.invalid.length;- while (i--) {- if (mLine.invalid[i].value == 'x-google-flag:conference') {- mLine.invalid.splice(i, 1);- }- }- }+ var packets = exports.packets = {+ open: 0 // non-ws+ , close: 1 // non-ws+ , ping: 2+ , pong: 3+ , message: 4+ , upgrade: 5+ , noop: 6+ };- function assertGoogConference(mLine) {- if (!mLine) {- return;- }+ var packetslist = keys(packets);- if (!Array.isArray(mLine.invalid)) {- mLine.invalid = [];- }+ /**+ * Premade error packet.+ */- if (!mLine.invalid.some(- function (i) { return i.value === 'x-google-flag:conference' })) {- mLine.invalid.push({'value': 'x-google-flag:conference'});- }- }+ var err = { type: 'error', data: 'parser error' };- //endregion+ /**+ * Create a blob api even for blob builder when vendor prefixes exist+ */- //region "Private" functions+ var Blob = require('blob');/**+ * Encodes a packet.*- * @param mLine- * @private+ * <packet type id> [ <data> ]+ *+ * Example:+ *+ * 5hello world+ * 3+ * 4+ *+ * Binary is encoded in an identical principle+ *+ * @api private*/- Simulcast.prototype._maybeInitializeLayers = function(mLine) {- if (!mLine || mLine.type !== 'video') {- return;- }+ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {+ if ('function' == typeof supportsBinary) {+ callback = supportsBinary;+ supportsBinary = false;+ }- var sources = parseSsrcs(mLine);+ if ('function' == typeof utf8encode) {+ callback = utf8encode;+ utf8encode = null;+ }- if (Object.keys(sources).length === 0) {+ var data = (packet.data === undefined)+ ? undefined+ : packet.data.buffer || packet.data;- // no sources, disable simulcast.- if (this.layers.length !== 0) {- this.layers = [];- }+ if (global.ArrayBuffer && data instanceof ArrayBuffer) {+ return encodeArrayBuffer(packet, supportsBinary, callback);+ } else if (Blob && data instanceof global.Blob) {+ return encodeBlob(packet, supportsBinary, callback);+ }- return;- }+ // might be an object with { base64: true, data: dataAsBase64String }+ if (data && data.base64) {+ return encodeBase64Object(packet, callback);+ }- // find the base layer (we'll reuse its msid and cname).- var baseLayerSSRC = Object.keys(sources)[0];- var baseLayer = sources[baseLayerSSRC];+ // Sending data as a utf-8 string+ var encoded = packets[packet.type];- // todo(gp) handle screen sharing.+ // data fragment is optional+ if (undefined !== packet.data) {+ encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);+ }- // check if base CNAME has changed and reinitialise layers.- if (this.layers.length > 0- && sources[baseLayerSSRC].cname !== this.layers[0].cname) {- this.layers = [];- }+ return callback('' + encoded);- // (re)initialise layers- if (this.layers.length < 1) {+ };- // first push the base layer.- this.layers.push({- ssrc: baseLayerSSRC,- msid: baseLayer.msid,- cname: baseLayer.cname- });+ function encodeBase64Object(packet, callback) {+ // packet data is an object { base64: true, data: dataAsBase64String }+ var message = 'b' + exports.packets[packet.type] + packet.data.data;+ return callback(message);+ }- var rtx = false; // RFC 4588- if (Array.isArray(mLine.rtp)) {- rtx = mLine.rtp.some(- function (rtpmap) { return rtpmap.codec === 'rtx'; });- }+ /**+ * Encode packet helpers for binary types+ */- if (rtx) {- this.layers[0].rtx = generateSSRC();- }+ function encodeArrayBuffer(packet, supportsBinary, callback) {+ if (!supportsBinary) {+ return exports.encodeBase64Packet(packet, callback);+ }- // now push additional layers.- for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {+ var data = packet.data;+ var contentArray = new Uint8Array(data);+ var resultBuffer = new Uint8Array(1 + data.byteLength);- var layer = { ssrc: generateSSRC() };- if (rtx) {- layer.rtx = generateSSRC();- }+ resultBuffer[0] = packets[packet.type];+ for (var i = 0; i < contentArray.length; i++) {+ resultBuffer[i+1] = contentArray[i];+ }- this.layers.push(layer);- }- }- };+ return callback(resultBuffer.buffer);+ }- /**- *- * @param mLine- * @private- */- Simulcast.prototype._restoreSimulcastView = function(mLine) {- if (mLine && mLine.type === 'video' && this.layers.length !== 0) {+ function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {+ if (!supportsBinary) {+ return exports.encodeBase64Packet(packet, callback);+ }- var sources = {};+ var fr = new FileReader();+ fr.onload = function() {+ packet.data = fr.result;+ exports.encodePacket(packet, supportsBinary, true, callback);+ };+ return fr.readAsArrayBuffer(packet.data);+ }- var msid = this.layers[0].msid;- var cname = this.layers[0].cname;- var simulcastSsrcs = [];- var ssrcGroups = [];+ function encodeBlob(packet, supportsBinary, callback) {+ if (!supportsBinary) {+ return exports.encodeBase64Packet(packet, callback);+ }- for (var i = 0; i < this.layers.length; i++) {- var layer = this.layers[i];+ if (dontSendBlobs) {+ return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);+ }- sources[layer.ssrc] = { msid: msid, cname: cname };- simulcastSsrcs.push(layer.ssrc);+ var length = new Uint8Array(1);+ length[0] = packets[packet.type];+ var blob = new Blob([length.buffer, packet.data]);- if (layer.rtx) {+ return callback(blob);+ }- sources[layer.rtx] = {- msid: msid,- cname: cname- }+ /**+ * Encodes a packet with binary data in a base64 string+ *+ * @param {Object} packet, has `type` and `data`+ * @return {String} base64 encoded message+ */- ssrcGroups.push({- semantics: 'FID',- ssrcs: [layer.ssrc, layer.rtx].join(' ')- });- }- }+ exports.encodeBase64Packet = function(packet, callback) {+ var message = 'b' + exports.packets[packet.type];+ if (Blob && packet.data instanceof Blob) {+ var fr = new FileReader();+ fr.onload = function() {+ var b64 = fr.result.split(',')[1];+ callback(message + b64);+ };+ return fr.readAsDataURL(packet.data);+ }- ssrcGroups.push({- semantics: 'SIM',- ssrcs: simulcastSsrcs.join(' ')- });+ var b64data;+ try {+ b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));+ } catch (e) {+ // iPhone Safari doesn't let you apply with typed arrays+ var typed = new Uint8Array(packet.data);+ var basic = new Array(typed.length);+ for (var i = 0; i < typed.length; i++) {+ basic[i] = typed[i];+ }+ b64data = String.fromCharCode.apply(null, basic);+ }+ message += global.btoa(b64data);+ return callback(message);+ };++ /**+ * Decodes a packet. Changes format to Blob if requested.+ *+ * @return {Object} with `type` and `data` (if any)+ * @api private+ */- mLine.ssrcGroups = ssrcGroups;- mLine.ssrcs = writeSsrcs(sources);+ exports.decodePacket = function (data, binaryType, utf8decode) {+ // String data+ if (typeof data == 'string' || data === undefined) {+ if (data.charAt(0) == 'b') {+ return exports.decodeBase64Packet(data.substr(1), binaryType);}- }- //endregion+ if (utf8decode) {+ try {+ data = utf8.decode(data);+ } catch (e) {+ return err;+ }+ }+ var type = data.charAt(0);- //region "Public" functions+ if (Number(type) != type || !packetslist[type]) {+ return err;+ }- Simulcast.prototype.isSupported = function () {- return window.chrome;+ if (data.length > 1) {+ return { type: packetslist[type], data: data.substring(1) };+ } else {+ return { type: packetslist[type] };+ }+ }- // TODO this needs improvements. For example I doubt that Chrome in Android- // has simulcast support. Also, only recent versions of Chromium have native- // simulcast support.- }+ var asArray = new Uint8Array(data);+ var type = asArray[0];+ var rest = sliceBuffer(data, 1);+ if (Blob && binaryType === 'blob') {+ rest = new Blob([rest]);+ }+ return { type: packetslist[type], data: rest };+ };/**+ * Decodes a packet encoded in a base64 string*- * @param desc- * @returns {RTCSessionDescription}+ * @param {String} base64 encoded message+ * @return {Object} with `type` and `data` (if any)*/- Simulcast.prototype.mungeRemoteDescription = function (desc) {-- if (!validateDescription(desc)) {- return desc;- }-- var session = transform.parse(desc.sdp);- var self = this;- processVideo(session, function (mLine) {+ exports.decodeBase64Packet = function(msg, binaryType) {+ var type = packetslist[msg.charAt(0)];+ if (!global.ArrayBuffer) {+ return { type: type, data: { base64: true, data: msg.substr(1) } };+ }- // Handle simulcast reception.- if (self.options.explodeRemoteSimulcast) {- explodeRemoteSimulcast(mLine);- } else {- implodeRemoteSimulcast(mLine);- }+ var data = base64encoder.decode(msg.substr(1));- // If native simulcast is enabled, we must append the x-goog-conference- // attribute to the SDP.- if (self.layers.length < 1) {- removeGoogConference(mLine);- } else {- assertGoogConference(mLine);- }- });+ if (binaryType === 'blob' && Blob) {+ data = new Blob([data]);+ }- return new RTCSessionDescription({- type: desc.type,- sdp: transform.write(session)- });+ return { type: type, data: data };};/**@@@ -29572,506 -28959,569 +29035,569 @@@ exports.encodePayloadAsBlob = function(* @api public*/- function Manager(uri, opts){- if (!(this instanceof Manager)) return new Manager(uri, opts);- if (uri && ('object' == typeof uri)) {- opts = uri;- uri = undefined;+ exports.decodePayloadAsBinary = function (data, binaryType, callback) {+ if (typeof binaryType === 'function') {+ callback = binaryType;+ binaryType = null;}- opts = opts || {};- opts.path = opts.path || '/socket.io';- this.nsps = {};- this.subs = [];- this.opts = opts;- this.reconnection(opts.reconnection !== false);- this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);- this.reconnectionDelay(opts.reconnectionDelay || 1000);- this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);- this.randomizationFactor(opts.randomizationFactor || 0.5);- this.backoff = new Backoff({- min: this.reconnectionDelay(),- max: this.reconnectionDelayMax(),- jitter: this.randomizationFactor()- });- this.timeout(null == opts.timeout ? 20000 : opts.timeout);- this.readyState = 'closed';- this.uri = uri;- this.connected = [];- this.encoding = false;- this.packetBuffer = [];- this.encoder = new parser.Encoder();- this.decoder = new parser.Decoder();- this.autoConnect = opts.autoConnect !== false;- if (this.autoConnect) this.open();- }+ var bufferTail = data;+ var buffers = [];++ var numberTooLong = false;+ while (bufferTail.byteLength > 0) {+ var tailArray = new Uint8Array(bufferTail);+ var isString = tailArray[0] === 0;+ var msgLength = '';++ for (var i = 1; ; i++) {+ if (tailArray[i] == 255) break;++ if (msgLength.length > 310) {+ numberTooLong = true;+ break;+ }++ msgLength += tailArray[i];+ }++ if(numberTooLong) return callback(err, 0, 1);- /**- * Propagate given event to sockets and emit on `this`- *- * @api private- */+ bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);+ msgLength = parseInt(msgLength);- Manager.prototype.emitAll = function() {- this.emit.apply(this, arguments);- for (var nsp in this.nsps) {- this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);+ var msg = sliceBuffer(bufferTail, 0, msgLength);+ if (isString) {+ try {+ msg = String.fromCharCode.apply(null, new Uint8Array(msg));+ } catch (e) {+ // iPhone Safari doesn't let you apply to typed arrays+ var typed = new Uint8Array(msg);+ msg = '';+ for (var i = 0; i < typed.length; i++) {+ msg += String.fromCharCode(typed[i]);+ }+ }+ }++ buffers.push(msg);+ bufferTail = sliceBuffer(bufferTail, msgLength);}++ var total = buffers.length;+ buffers.forEach(function(buffer, i) {+ callback(exports.decodePacket(buffer, binaryType, true), i, total);+ });};+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"./keys":110,"after":111,"arraybuffer.slice":112,"base64-arraybuffer":113,"blob":114,"has-binary":115,"utf8":117}],110:[function(require,module,exports){++},{"./keys":107,"after":108,"arraybuffer.slice":109,"base64-arraybuffer":110,"blob":111,"has-binary":112,"utf8":114}],107:[function(require,module,exports){+/**- * Update `socket.id` of all sockets+ * Gets the keys for an object.*+ * @return {Array} keys* @api private*/- Manager.prototype.updateSocketIds = function(){- for (var nsp in this.nsps) {- this.nsps[nsp].id = this.engine.id;+ module.exports = Object.keys || function keys (obj){+ var arr = [];+ var has = Object.prototype.hasOwnProperty;++ for (var i in obj) {+ if (has.call(obj, i)) {+ arr.push(i);+ }}+ return arr;};- /**- * Mix in `Emitter`.- */-- Emitter(Manager.prototype);-- /**- * Sets the `reconnection` config.- *- * @param {Boolean} true/false if it should automatically reconnect- * @return {Manager} self or value- * @api public- */-- Manager.prototype.reconnection = function(v){- if (!arguments.length) return this._reconnection;- this._reconnection = !!v;- return this;- };-},{}],111:[function(require,module,exports){++},{}],108:[function(require,module,exports){+ module.exports = after- /**- * Sets the reconnection attempts config.- *- * @param {Number} max reconnection attempts before giving up- * @return {Manager} self or value- * @api public- */+ function after(count, callback, err_cb) {+ var bail = false+ err_cb = err_cb || noop+ proxy.count = count- Manager.prototype.reconnectionAttempts = function(v){- if (!arguments.length) return this._reconnectionAttempts;- this._reconnectionAttempts = v;- return this;- };+ return (count === 0) ? callback() : proxy- /**- * Sets the delay between reconnections.- *- * @param {Number} delay- * @return {Manager} self or value- * @api public- */+ function proxy(err, result) {+ if (proxy.count <= 0) {+ throw new Error('after called too many times')+ }+ --proxy.count- Manager.prototype.reconnectionDelay = function(v){- if (!arguments.length) return this._reconnectionDelay;- this._reconnectionDelay = v;- this.backoff && this.backoff.setMin(v);- return this;- };+ // after first error, rest are passed to err_cb+ if (err) {+ bail = true+ callback(err)+ // future error callbacks will go to error handler+ callback = err_cb+ } else if (proxy.count === 0 && !bail) {+ callback(null, result)+ }+ }+ }- Manager.prototype.randomizationFactor = function(v){- if (!arguments.length) return this._randomizationFactor;- this._randomizationFactor = v;- this.backoff && this.backoff.setJitter(v);- return this;- };+ function noop() {}-},{}],112:[function(require,module,exports){++},{}],109:[function(require,module,exports){/**- * Sets the maximum delay between reconnections.+ * An abstraction for slicing an arraybuffer even when+ * ArrayBuffer.prototype.slice is not supported*- * @param {Number} delay- * @return {Manager} self or value* @api public*/- Manager.prototype.reconnectionDelayMax = function(v){- if (!arguments.length) return this._reconnectionDelayMax;- this._reconnectionDelayMax = v;- this.backoff && this.backoff.setMax(v);- return this;- };+ module.exports = function(arraybuffer, start, end) {+ var bytes = arraybuffer.byteLength;+ start = start || 0;+ end = end || bytes;- /**- * Sets the connection timeout. `false` to disable- *- * @return {Manager} self or value- * @api public- */+ if (arraybuffer.slice) { return arraybuffer.slice(start, end); }- Manager.prototype.timeout = function(v){- if (!arguments.length) return this._timeout;- this._timeout = v;- return this;- };+ if (start < 0) { start += bytes; }+ if (end < 0) { end += bytes; }+ if (end > bytes) { end = bytes; }- /**- * Starts trying to reconnect if reconnection is enabled and we have not- * started reconnecting yet- *- * @api private- */+ if (start >= bytes || start >= end || bytes === 0) {+ return new ArrayBuffer(0);+ }- Manager.prototype.maybeReconnectOnOpen = function() {- // Only try to reconnect if it's the first time we're connecting- if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {- // keeps reconnection from firing twice for the same reconnection loop- this.reconnect();+ var abv = new Uint8Array(arraybuffer);+ var result = new Uint8Array(end - start);+ for (var i = start, ii = 0; i < end; i++, ii++) {+ result[ii] = abv[i];}+ return result.buffer;};-- /**- * Sets the current transport `socket`.-},{}],113:[function(require,module,exports){++},{}],110:[function(require,module,exports){+ /*+ * base64-arraybuffer+ * https://github.com/niklasvh/base64-arraybuffer*- * @param {Function} optional, callback- * @return {Manager} self- * @api public+ * Copyright (c) 2012 Niklas von Hertzen+ * Licensed under the MIT license.*/+ (function(chars){+ "use strict";- Manager.prototype.open =- Manager.prototype.connect = function(fn){- debug('readyState %s', this.readyState);- if (~this.readyState.indexOf('open')) return this;-- debug('opening %s', this.uri);- this.engine = eio(this.uri, this.opts);- var socket = this.engine;- var self = this;- this.readyState = 'opening';- this.skipReconnect = false;+ exports.encode = function(arraybuffer) {+ var bytes = new Uint8Array(arraybuffer),+ i, len = bytes.length, base64 = "";- // emit `open`- var openSub = on(socket, 'open', function() {- self.onopen();- fn && fn();- });+ for (i = 0; i < len; i+=3) {+ base64 += chars[bytes[i] >> 2];+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];+ base64 += chars[bytes[i + 2] & 63];+ }- // emit `connect_error`- var errorSub = on(socket, 'error', function(data){- debug('connect_error');- self.cleanup();- self.readyState = 'closed';- self.emitAll('connect_error', data);- if (fn) {- var err = new Error('Connection error');- err.data = data;- fn(err);- } else {- // Only do this if there is no fn to handle the error- self.maybeReconnectOnOpen();+ if ((len % 3) === 2) {+ base64 = base64.substring(0, base64.length - 1) + "=";+ } else if (len % 3 === 1) {+ base64 = base64.substring(0, base64.length - 2) + "==";}- });- // emit `connect_timeout`- if (false !== this._timeout) {- var timeout = this._timeout;- debug('connect attempt will timeout after %d', timeout);+ return base64;+ };- // set timer- var timer = setTimeout(function(){- debug('connect attempt timed out after %d', timeout);- openSub.destroy();- socket.close();- socket.emit('error', 'timeout');- self.emitAll('connect_timeout', timeout);- }, timeout);+ exports.decode = function(base64) {+ var bufferLength = base64.length * 0.75,+ len = base64.length, i, p = 0,+ encoded1, encoded2, encoded3, encoded4;- this.subs.push({- destroy: function(){- clearTimeout(timer);+ if (base64[base64.length - 1] === "=") {+ bufferLength--;+ if (base64[base64.length - 2] === "=") {+ bufferLength--;}- });- }+ }- this.subs.push(openSub);- this.subs.push(errorSub);+ var arraybuffer = new ArrayBuffer(bufferLength),+ bytes = new Uint8Array(arraybuffer);- return this;- };+ for (i = 0; i < len; i+=4) {+ encoded1 = chars.indexOf(base64[i]);+ encoded2 = chars.indexOf(base64[i+1]);+ encoded3 = chars.indexOf(base64[i+2]);+ encoded4 = chars.indexOf(base64[i+3]);++ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);+ }+ return arraybuffer;+ };+ })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");+-},{}],114:[function(require,module,exports){++},{}],111:[function(require,module,exports){+ (function (global){/**- * Called upon transport open.- *- * @api private+ * Create a blob builder even when vendor prefixes exist*/- Manager.prototype.onopen = function(){- debug('open');-- // clear old subs- this.cleanup();+ var BlobBuilder = global.BlobBuilder+ || global.WebKitBlobBuilder+ || global.MSBlobBuilder+ || global.MozBlobBuilder;- // mark as open- this.readyState = 'open';- this.emit('open');+ /**+ * Check if Blob constructor is supported+ */- // add new subs- var socket = this.engine;- this.subs.push(on(socket, 'data', bind(this, 'ondata')));- this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));- this.subs.push(on(socket, 'error', bind(this, 'onerror')));- this.subs.push(on(socket, 'close', bind(this, 'onclose')));- };+ var blobSupported = (function() {+ try {+ var b = new Blob(['hi']);+ return b.size == 2;+ } catch(e) {+ return false;+ }+ })();/**- * Called with data.- *- * @api private+ * Check if BlobBuilder is supported*/- Manager.prototype.ondata = function(data){- this.decoder.add(data);+ var blobBuilderSupported = BlobBuilder+ && BlobBuilder.prototype.append+ && BlobBuilder.prototype.getBlob;++ function BlobBuilderConstructor(ary, options) {+ options = options || {};++ var bb = new BlobBuilder();+ for (var i = 0; i < ary.length; i++) {+ bb.append(ary[i]);+ }+ return (options.type) ? bb.getBlob(options.type) : bb.getBlob();};- /**- * Called when parser fully decodes a packet.- *- * @api private+ module.exports = (function() {+ if (blobSupported) {+ return global.Blob;+ } else if (blobBuilderSupported) {+ return BlobBuilderConstructor;+ } else {+ return undefined;+ }+ })();++ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{}],115:[function(require,module,exports){++},{}],112:[function(require,module,exports){+ (function (global){++ /*+ * Module requirements.*/- Manager.prototype.ondecoded = function(packet) {- this.emit('packet', packet);- };+ var isArray = require('isarray');/**- * Called upon socket error.- *- * @api private+ * Module exports.*/- Manager.prototype.onerror = function(err){- debug('error', err);- this.emitAll('error', err);- };+ module.exports = hasBinary;/**- * Creates a new socket for the given `nsp`.+ * Checks for binary data.*- * @return {Socket}+ * Right now only Buffer and ArrayBuffer are supported..+ *+ * @param {Object} anything* @api public*/- Manager.prototype.socket = function(nsp){- var socket = this.nsps[nsp];- if (!socket) {- socket = new Socket(this, nsp);- this.nsps[nsp] = socket;- var self = this;- socket.on('connect', function(){- socket.id = self.engine.id;- if (!~indexOf(self.connected, socket)) {- self.connected.push(socket);+ function hasBinary(data) {++ function _hasBinary(obj) {+ if (!obj) return false;++ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||+ (global.Blob && obj instanceof Blob) ||+ (global.File && obj instanceof File)+ ) {+ return true;+ }++ if (isArray(obj)) {+ for (var i = 0; i < obj.length; i++) {+ if (_hasBinary(obj[i])) {+ return true;+ }}- });+ } else if (obj && 'object' == typeof obj) {+ if (obj.toJSON) {+ obj = obj.toJSON();+ }++ for (var key in obj) {+ if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {+ return true;+ }+ }+ }++ return false;}- return socket;++ return _hasBinary(data);+ }++ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"isarray":116}],116:[function(require,module,exports){++},{"isarray":113}],113:[function(require,module,exports){+ module.exports = Array.isArray || function (arr) {+ return Object.prototype.toString.call(arr) == '[object Array]';};- /**- * Called upon a socket close.- *- * @param {Socket} socket- */-},{}],117:[function(require,module,exports){++},{}],114:[function(require,module,exports){+ (function (global){+ /*! http://mths.be/utf8js v2.0.0 by @mathias */+ ;(function(root) {- Manager.prototype.destroy = function(socket){- var index = indexOf(this.connected, socket);- if (~index) this.connected.splice(index, 1);- if (this.connected.length) return;+ // Detect free variables `exports`+ var freeExports = typeof exports == 'object' && exports;- this.close();- };+ // Detect free variable `module`+ var freeModule = typeof module == 'object' && module &&+ module.exports == freeExports && module;- /**- * Writes a packet.- *- * @param {Object} packet- * @api private- */+ // Detect free variable `global`, from Node.js or Browserified code,+ // and use it as `root`+ var freeGlobal = typeof global == 'object' && global;+ if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {+ root = freeGlobal;+ }- Manager.prototype.packet = function(packet){- debug('writing packet %j', packet);- var self = this;+ /*--------------------------------------------------------------------------*/- if (!self.encoding) {- // encode, then write to engine with result- self.encoding = true;- this.encoder.encode(packet, function(encodedPackets) {- for (var i = 0; i < encodedPackets.length; i++) {- self.engine.write(encodedPackets[i]);- }- self.encoding = false;- self.processPacketQueue();- });- } else { // add packet to the queue- self.packetBuffer.push(packet);- }- };+ var stringFromCharCode = String.fromCharCode;- /**- * If packet buffer is non-empty, begins encoding the- * next packet in line.- *- * @api private- */+ // Taken from http://mths.be/punycode+ function ucs2decode(string) {+ var output = [];+ var counter = 0;+ var length = string.length;+ var value;+ var 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;+ }++ // Taken from http://mths.be/punycode+ function ucs2encode(array) {+ var length = array.length;+ var index = -1;+ var value;+ var output = '';+ while (++index < length) {+ value = array[index];+ if (value > 0xFFFF) {+ value -= 0x10000;+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);+ value = 0xDC00 | value & 0x3FF;+ }+ output += stringFromCharCode(value);+ }+ return output;+ }- Manager.prototype.processPacketQueue = function() {- if (this.packetBuffer.length > 0 && !this.encoding) {- var pack = this.packetBuffer.shift();- this.packet(pack);- }- };+ /*--------------------------------------------------------------------------*/- /**- * Clean up transport subscriptions and packet buffer.- *- * @api private- */+ function createByte(codePoint, shift) {+ return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);+ }- Manager.prototype.cleanup = function(){- var sub;- while (sub = this.subs.shift()) sub.destroy();+ function encodeCodePoint(codePoint) {+ if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence+ return stringFromCharCode(codePoint);+ }+ var symbol = '';+ if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence+ symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);+ }+ else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence+ symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);+ symbol += createByte(codePoint, 6);+ }+ else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence+ symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);+ symbol += createByte(codePoint, 12);+ symbol += createByte(codePoint, 6);+ }+ symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);+ return symbol;+ }- this.packetBuffer = [];- this.encoding = false;+ function utf8encode(string) {+ var codePoints = ucs2decode(string);- this.decoder.destroy();- };+ // console.log(JSON.stringify(codePoints.map(function(x) {+ // return 'U+' + x.toString(16).toUpperCase();+ // })));- /**- * Close the current socket.- *- * @api private- */+ var length = codePoints.length;+ var index = -1;+ var codePoint;+ var byteString = '';+ while (++index < length) {+ codePoint = codePoints[index];+ byteString += encodeCodePoint(codePoint);+ }+ return byteString;+ }- Manager.prototype.close =- Manager.prototype.disconnect = function(){- this.skipReconnect = true;- this.backoff.reset();- this.readyState = 'closed';- this.engine && this.engine.close();- };+ /*--------------------------------------------------------------------------*/- /**- * Called upon engine close.- *- * @api private- */+ function readContinuationByte() {+ if (byteIndex >= byteCount) {+ throw Error('Invalid byte index');+ }- Manager.prototype.onclose = function(reason){- debug('close');- this.cleanup();- this.backoff.reset();- this.readyState = 'closed';- this.emit('close', reason);- if (this._reconnection && !this.skipReconnect) {- this.reconnect();- }- };+ var continuationByte = byteArray[byteIndex] & 0xFF;+ byteIndex++;- /**- * Attempt a reconnection.- *- * @api private- */+ if ((continuationByte & 0xC0) == 0x80) {+ return continuationByte & 0x3F;+ }- Manager.prototype.reconnect = function(){- if (this.reconnecting || this.skipReconnect) return this;+ // If we end up here, it’s not a continuation byte+ throw Error('Invalid continuation byte');+ }- var self = this;+ function decodeSymbol() {+ var byte1;+ var byte2;+ var byte3;+ var byte4;+ var codePoint;- if (this.backoff.attempts >= this._reconnectionAttempts) {- debug('reconnect failed');- this.backoff.reset();- this.emitAll('reconnect_failed');- this.reconnecting = false;- } else {- var delay = this.backoff.duration();- debug('will wait %dms before reconnect attempt', delay);+ if (byteIndex > byteCount) {+ throw Error('Invalid byte index');+ }- this.reconnecting = true;- var timer = setTimeout(function(){- if (self.skipReconnect) return;+ if (byteIndex == byteCount) {+ return false;+ }- debug('attempting reconnect');- self.emitAll('reconnect_attempt', self.backoff.attempts);- self.emitAll('reconnecting', self.backoff.attempts);+ // Read first byte+ byte1 = byteArray[byteIndex] & 0xFF;+ byteIndex++;- // check again for the case socket closed in above events- if (self.skipReconnect) return;+ // 1-byte sequence (no continuation bytes)+ if ((byte1 & 0x80) == 0) {+ return byte1;+ }- self.open(function(err){- if (err) {- debug('reconnect attempt error');- self.reconnecting = false;- self.reconnect();- self.emitAll('reconnect_error', err.data);- } else {- debug('reconnect success');- self.onreconnect();- }- });- }, delay);+ // 2-byte sequence+ if ((byte1 & 0xE0) == 0xC0) {+ var byte2 = readContinuationByte();+ codePoint = ((byte1 & 0x1F) << 6) | byte2;+ if (codePoint >= 0x80) {+ return codePoint;+ } else {+ throw Error('Invalid continuation byte');+ }+ }- this.subs.push({- destroy: function(){- clearTimeout(timer);- }- });- }- };+ // 3-byte sequence (may include unpaired surrogates)+ if ((byte1 & 0xF0) == 0xE0) {+ byte2 = readContinuationByte();+ byte3 = readContinuationByte();+ codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;+ if (codePoint >= 0x0800) {+ return codePoint;+ } else {+ throw Error('Invalid continuation byte');+ }+ }- /**- * Called upon successful reconnect.- *- * @api private- */+ // 4-byte sequence+ if ((byte1 & 0xF8) == 0xF0) {+ byte2 = readContinuationByte();+ byte3 = readContinuationByte();+ byte4 = readContinuationByte();+ codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |+ (byte3 << 0x06) | byte4;+ if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {+ return codePoint;+ }+ }- Manager.prototype.onreconnect = function(){- var attempt = this.backoff.attempts;- this.reconnecting = false;- this.backoff.reset();- this.updateSocketIds();- this.emitAll('reconnect', attempt);- };+ throw Error('Invalid UTF-8 detected');+ }- },{"./on":121,"./socket":122,"./url":123,"backo2":48,"component-bind":52,"component-emitter":53,"debug":55,"engine.io-client":56,"indexof":76,"object-component":83,"socket.io-parser":125}],121:[function(require,module,exports){+ var byteArray;+ var byteCount;+ var byteIndex;+ function utf8decode(byteString) {+ byteArray = ucs2decode(byteString);+ byteCount = byteArray.length;+ byteIndex = 0;+ var codePoints = [];+ var tmp;+ while ((tmp = decodeSymbol()) !== false) {+ codePoints.push(tmp);+ }+ return ucs2encode(codePoints);+ }- /**- * Module exports.- */+ /*--------------------------------------------------------------------------*/- module.exports = on;+ var utf8 = {+ 'version': '2.0.0',+ 'encode': utf8encode,+ 'decode': utf8decode+ };- /**- * Helper for subscriptions.- *- * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`- * @param {String} event name- * @param {Function} callback- * @api public- */+ // 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(function() {+ return utf8;+ });+ } else if (freeExports && !freeExports.nodeType) {+ if (freeModule) { // in Node.js or RingoJS v0.8.0++ freeModule.exports = utf8;+ } else { // in Narwhal or RingoJS v0.7.0-+ var object = {};+ var hasOwnProperty = object.hasOwnProperty;+ for (var key in utf8) {+ hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);+ }+ }+ } else { // in Rhino or a web browser+ root.utf8 = utf8;+ }- function on(obj, ev, fn) {- obj.on(ev, fn);- return {- destroy: function(){- obj.removeListener(ev, fn);- }- };- }+ }(this));- },{}],122:[function(require,module,exports){+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{}],118:[function(require,module,exports){++},{}],115:[function(require,module,exports){/*** Module dependencies.@@@ -30087,148 -29531,72 +29607,72 @@@ var global = require('global')/*** Module exports.- */-- module.exports = exports = Socket;-- /**- * Internal events (blacklisted).- * These events can't be emitted by the user.*- * @api private- */-- var events = {- connect: 1,- connect_error: 1,- connect_timeout: 1,- disconnect: 1,- error: 1,- reconnect: 1,- reconnect_attempt: 1,- reconnect_failed: 1,- reconnect_error: 1,- reconnecting: 1- };-- /**- * Shortcut to `Emitter#emit`.- */-- var emit = Emitter.prototype.emit;-- /**- * `Socket` constructor.+ * Logic borrowed from Modernizr:*- * @api public+ * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js*/- function Socket(io, nsp){- this.io = io;- this.nsp = nsp;- this.json = this; // compat- this.ids = 0;- this.acks = {};- if (this.io.autoConnect) this.open();- this.receiveBuffer = [];- this.sendBuffer = [];- this.connected = false;- this.disconnected = true;+ try {+ module.exports = 'XMLHttpRequest' in global &&+ 'withCredentials' in new global.XMLHttpRequest();+ } catch (err) {+ // if XMLHttp support is disabled in IE then it will throw+ // when trying to create+ module.exports = false;}- /**- * Mix in `Emitter`.- */-- Emitter(Socket.prototype);-- /**- * Subscribe to open, close and packet events- *- * @api private- */-- Socket.prototype.subEvents = function() {- if (this.subs) return;-- var io = this.io;- this.subs = [- on(io, 'open', bind(this, 'onopen')),- on(io, 'packet', bind(this, 'onpacket')),- on(io, 'close', bind(this, 'onclose'))- ];- };-},{"global":119}],119:[function(require,module,exports){++},{"global":116}],116:[function(require,module,exports){/**- * "Opens" the socket.- *- * @api public+ * Returns `this`. Execute this without a "context" (i.e. without it being+ * attached to an object of the left-hand side), and `this` points to the+ * "global" scope of the current JS execution.*/- Socket.prototype.open =- Socket.prototype.connect = function(){- if (this.connected) return this;-- this.subEvents();- this.io.open(); // ensure open- if ('open' == this.io.readyState) this.onopen();- return this;- };+ module.exports = (function () { return this; })();-},{}],120:[function(require,module,exports){++},{}],117:[function(require,module,exports){+ (function (global){/**- * Sends a `message` event.+ * JSON parse.*- * @return {Socket} self- * @api public+ * @see Based on jQuery#parseJSON (MIT) and JSON2+ * @api private*/- Socket.prototype.send = function(){- var args = toArray(arguments);- args.unshift('message');- this.emit.apply(this, args);- return this;- };-- /**- * Override `emit`.- * If the event is in `events`, it's emitted normally.- *- * @param {String} event name- * @return {Socket} self- * @api public- */+ var rvalidchars = /^[\],:{}\s]*$/;+ var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;+ var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;+ var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;+ var rtrimLeft = /^\s+/;+ var rtrimRight = /\s+$/;- Socket.prototype.emit = function(ev){- if (events.hasOwnProperty(ev)) {- emit.apply(this, arguments);- return this;+ module.exports = function parsejson(data) {+ if ('string' != typeof data || !data) {+ return null;}- var args = toArray(arguments);- var parserType = parser.EVENT; // default- if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary- var packet = { type: parserType, data: args };+ data = data.replace(rtrimLeft, '').replace(rtrimRight, '');- // event ack callback- if ('function' == typeof args[args.length - 1]) {- debug('emitting packet with ack id %d', this.ids);- this.acks[this.ids] = args.pop();- packet.id = this.ids++;+ // Attempt to parse using the native JSON parser first+ if (global.JSON && JSON.parse) {+ return JSON.parse(data);}- if (this.connected) {- this.packet(packet);- } else {- this.sendBuffer.push(packet);+ if (rvalidchars.test(data.replace(rvalidescape, '@')+ .replace(rvalidtokens, ']')+ .replace(rvalidbraces, ''))) {+ return (new Function('return ' + data))();}-- return this;};-+ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{}],121:[function(require,module,exports){++},{}],118:[function(require,module,exports){/**- * Sends a packet.+ * Compiles a querystring+ * Returns string representation of the object*- * @param {Object} packet+ * @param {Object}* @api private*/@@@ -30243,195 -29620,201 +29696,201 @@@ exports.encode = function (obj)* @api private*/- Socket.prototype.onopen = function(){- debug('transport is open - connecting');-- // write connect packet if necessary- if ('/' != this.nsp) {- this.packet({ type: parser.CONNECT });+ exports.decode = function(qs){+ var qry = {};+ var pairs = qs.split('&');+ for (var i = 0, l = pairs.length; i < l; i++) {+ var pair = pairs[i].split('=');+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);}+ return qry;};-},{}],122:[function(require,module,exports){++},{}],119:[function(require,module,exports){/**- * Called upon engine `close`.+ * Parses an URI*- * @param {String} reason+ * @author Steven Levithan <stevenlevithan.com> (MIT license)* @api private*/- Socket.prototype.onclose = function(reason){- debug('close (%s)', reason);- this.connected = false;- this.disconnected = true;- delete this.id;- this.emit('disconnect', reason);- };+ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;- /**- * Called with socket packet.- *- * @param {Object} packet- * @api private- */+ var parts = [+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'+ ];- Socket.prototype.onpacket = function(packet){- if (packet.nsp != this.nsp) return;+ module.exports = function parseuri(str) {+ var src = str,+ b = str.indexOf('['),+ e = str.indexOf(']');- switch (packet.type) {- case parser.CONNECT:- this.onconnect();- break;+ if (b != -1 && e != -1) {+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);+ }- case parser.EVENT:- this.onevent(packet);- break;+ var m = re.exec(str || ''),+ uri = {},+ i = 14;++ while (i--) {+ uri[parts[i]] = m[i] || '';+ }- case parser.BINARY_EVENT:- this.onevent(packet);- break;+ if (b != -1 && e != -1) {+ uri.source = src;+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');+ uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');+ uri.ipv6uri = true;+ }- case parser.ACK:- this.onack(packet);- break;+ return uri;+ };- case parser.BINARY_ACK:- this.onack(packet);- break;-},{}],123:[function(require,module,exports){++},{}],120:[function(require,module,exports){- case parser.DISCONNECT:- this.ondisconnect();- break;+ /**+ * Module dependencies.+ */- case parser.ERROR:- this.emit('error', packet.data);- break;- }- };+ var global = (function() { return this; })();/**- * Called upon a server event.- *- * @param {Object} packet- * @api private+ * WebSocket constructor.*/- Socket.prototype.onevent = function(packet){- var args = packet.data || [];- debug('emitting event %j', args);+ var WebSocket = global.WebSocket || global.MozWebSocket;- if (null != packet.id) {- debug('attaching ack callback to event');- args.push(this.ack(packet.id));- }+ /**+ * Module exports.+ */- if (this.connected) {- emit.apply(this, args);- } else {- this.receiveBuffer.push(args);- }- };+ module.exports = WebSocket ? ws : null;/**- * Produces an ack callback to emit with an event.+ * WebSocket constructor.*- * @api private+ * The third `opts` options object gets ignored in web browsers, since it's+ * non-standard, and throws a TypeError if passed to the constructor.+ * See: https://github.com/einaros/ws/issues/227+ *+ * @param {String} uri+ * @param {Array} protocols (optional)+ * @param {Object) opts (optional)+ * @api public*/- Socket.prototype.ack = function(id){- var self = this;- var sent = false;- return function(){- // prevent double callbacks- if (sent) return;- sent = true;- var args = toArray(arguments);- debug('sending ack %j', args);+ function ws(uri, protocols, opts) {+ var instance;+ if (protocols) {+ instance = new WebSocket(uri, protocols);+ } else {+ instance = new WebSocket(uri);+ }+ return instance;+ }- var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;- self.packet({- type: type,- id: id,- data: args- });- };- };+ if (WebSocket) ws.prototype = WebSocket.prototype;- /**- * Called upon a server acknowlegement.- *- * @param {Object} packet- * @api private-},{}],124:[function(require,module,exports){++},{}],121:[function(require,module,exports){+ (function (global){++ /*+ * Module requirements.*/- Socket.prototype.onack = function(packet){- debug('calling ack %s with %j', packet.id, packet.data);- var fn = this.acks[packet.id];- fn.apply(this, packet.data);- delete this.acks[packet.id];- };+ var isArray = require('isarray');/**- * Called upon server connect.- *- * @api private+ * Module exports.*/- Socket.prototype.onconnect = function(){- this.connected = true;- this.disconnected = false;- this.emit('connect');- this.emitBuffered();- };+ module.exports = hasBinary;/**- * Emit buffered events (received and emitted).+ * Checks for binary data.*- * @api private+ * Right now only Buffer and ArrayBuffer are supported..+ *+ * @param {Object} anything+ * @api public*/- Socket.prototype.emitBuffered = function(){- var i;- for (i = 0; i < this.receiveBuffer.length; i++) {- emit.apply(this, this.receiveBuffer[i]);+ function hasBinary(data) {++ function _hasBinary(obj) {+ if (!obj) return false;++ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||+ (global.Blob && obj instanceof Blob) ||+ (global.File && obj instanceof File)+ ) {+ return true;+ }++ if (isArray(obj)) {+ for (var i = 0; i < obj.length; i++) {+ if (_hasBinary(obj[i])) {+ return true;+ }+ }+ } else if (obj && 'object' == typeof obj) {+ if (obj.toJSON) {+ obj = obj.toJSON();+ }++ for (var key in obj) {+ if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {+ return true;+ }+ }+ }++ return false;}- this.receiveBuffer = [];- for (i = 0; i < this.sendBuffer.length; i++) {- this.packet(this.sendBuffer[i]);+ return _hasBinary(data);+ }++ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{"isarray":125}],125:[function(require,module,exports){-arguments[4][116][0].apply(exports,arguments)-},{"dup":116}],126:[function(require,module,exports){++},{"isarray":122}],122:[function(require,module,exports){++arguments[4][113][0].apply(exports,arguments)++},{"dup":113}],123:[function(require,module,exports){++ var indexOf = [].indexOf;++ module.exports = function(arr, obj){+ if (indexOf) return arr.indexOf(obj);+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i] === obj) return i;}- this.sendBuffer = [];+ return -1;};-},{}],127:[function(require,module,exports){++},{}],124:[function(require,module,exports){/**- * Called upon server disconnect.- *- * @api private+ * HOP ref.*/- Socket.prototype.ondisconnect = function(){- debug('server disconnect (%s)', this.nsp);- this.destroy();- this.onclose('io server disconnect');- };+ var has = Object.prototype.hasOwnProperty;/**- * Called upon forced client/server side disconnections,- * this method ensures the manager stops tracking us and- * that reconnections don't get triggered for this.+ * Return own keys in `obj`.*- * @api private.+ * @param {Object} obj+ * @return {Array}+ * @api public*/- Socket.prototype.destroy = function(){- if (this.subs) {- // clean subscriptions to avoid reconnections- for (var i = 0; i < this.subs.length; i++) {- this.subs[i].destroy();+ exports.keys = Object.keys || function(obj){+ var keys = [];+ for (var key in obj) {+ if (has.call(obj, key)) {+ keys.push(key);}- this.subs = null;}-- this.io.destroy(this);+ return keys;};/**@@@ -30483,59 -29873,37 +29949,37 @@@ exports.length = function(obj)* @api public*/- function url(uri, loc){- var obj = uri;-- // default to window.location- var loc = loc || global.location;- if (null == uri) uri = loc.protocol + '//' + loc.host;+ exports.isEmpty = function(obj){+ return 0 == exports.length(obj);+ };-},{}],128:[function(require,module,exports){++},{}],125:[function(require,module,exports){+ /**+ * Parses an URI+ *+ * @author Steven Levithan <stevenlevithan.com> (MIT license)+ * @api private+ */- // relative path support- if ('string' == typeof uri) {- if ('/' == uri.charAt(0)) {- if ('/' == uri.charAt(1)) {- uri = loc.protocol + uri;- } else {- uri = loc.hostname + uri;- }- }+ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;- if (!/^(https?|wss?):\/\//.test(uri)) {- debug('protocol-less url %s', uri);- if ('undefined' != typeof loc) {- uri = loc.protocol + '//' + uri;- } else {- uri = 'https://' + uri;- }- }+ var parts = [+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'+ , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'+ ];- // parse- debug('parse %s', uri);- obj = parseuri(uri);- }+ module.exports = function parseuri(str) {+ var m = re.exec(str || '')+ , uri = {}+ , i = 14;- // make sure we treat `localhost:80` and `localhost` equally- if (!obj.port) {- if (/^(http|ws)$/.test(obj.protocol)) {- obj.port = '80';- }- else if (/^(http|ws)s$/.test(obj.protocol)) {- obj.port = '443';- }+ while (i--) {+ uri[parts[i]] = m[i] || '';}- obj.path = obj.path || '/';-- // define unique id- obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;- // define href- obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));-- return obj;- }+ return uri;+ };- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"debug":55,"parseuri":102}],124:[function(require,module,exports){-},{}],129:[function(require,module,exports){++},{}],126:[function(require,module,exports){(function (global){/*global Blob,File*/@@@ -30680,7 -30048,7 +30124,7 @@@ exports.removeBlobs = function(data, ca};}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{"./is-buffer":126,"isarray":77}],125:[function(require,module,exports){-},{"./is-buffer":131,"isarray":132}],130:[function(require,module,exports){++},{"./is-buffer":128,"isarray":129}],127:[function(require,module,exports){/*** Module dependencies.@@@ -31061,355 -30429,932 +30505,932 @@@ BinaryReconstructor.prototype.takeBinarthis.finishedReconstruction();return packet;}- return null;- };-- /**- * Cleans up binary packet reconstruction variables.- *- * @api private- */-- BinaryReconstructor.prototype.finishedReconstruction = function() {- this.reconPack = null;- this.buffers = [];- };-- function error(data){- return {- type: exports.ERROR,- data: 'parser error'- };- }-- },{"./binary":124,"./is-buffer":126,"component-emitter":53,"debug":55,"isarray":77,"json3":80}],126:[function(require,module,exports){- (function (global){-- module.exports = isBuf;-- /**- * Returns true if obj is a buffer or an arraybuffer.- *- * @api private- */+ return null;+ };++ /**+ * Cleans up binary packet reconstruction variables.+ *+ * @api private+ */++ BinaryReconstructor.prototype.finishedReconstruction = function() {+ this.reconPack = null;+ this.buffers = [];+ };++ function error(data){+ return {+ type: exports.ERROR,+ data: 'parser error'+ };+ }+-},{"./binary":129,"./is-buffer":131,"component-emitter":93,"debug":94,"isarray":132,"json3":133}],131:[function(require,module,exports){++},{"./binary":126,"./is-buffer":128,"component-emitter":90,"debug":91,"isarray":129,"json3":130}],128:[function(require,module,exports){+ (function (global){++ module.exports = isBuf;++ /**+ * Returns true if obj is a buffer or an arraybuffer.+ *+ * @api private+ */++ function isBuf(obj) {+ return (global.Buffer && global.Buffer.isBuffer(obj)) ||+ (global.ArrayBuffer && obj instanceof ArrayBuffer);+ }++ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})-},{}],132:[function(require,module,exports){-arguments[4][116][0].apply(exports,arguments)-},{"dup":116}],133:[function(require,module,exports){++},{}],129:[function(require,module,exports){++arguments[4][113][0].apply(exports,arguments)++},{"dup":113}],130:[function(require,module,exports){+ /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */+ ;(function (window) {+ // Convenience aliases.+ var getClass = {}.toString, isProperty, forEach, undef;++ // Detect the `define` function exposed by asynchronous module loaders. The+ // strict `define` check is necessary for compatibility with `r.js`.+ var isLoader = typeof define === "function" && define.amd;++ // Detect native implementations.+ var nativeJSON = typeof JSON == "object" && JSON;++ // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if+ // available.+ var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;++ if (JSON3 && nativeJSON) {+ // Explicitly delegate to the native `stringify` and `parse`+ // implementations in CommonJS environments.+ JSON3.stringify = nativeJSON.stringify;+ JSON3.parse = nativeJSON.parse;+ } else {+ // Export for web browsers, JavaScript engines, and asynchronous module+ // loaders, using the global `JSON` object if available.+ JSON3 = window.JSON = nativeJSON || {};+ }++ // Test the `Date#getUTC*` methods. Based on work by @Yaffle.+ var isExtended = new Date(-3509827334573292);+ try {+ // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical+ // results for certain dates in Opera >= 10.53.+ isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&+ // Safari < 2.0.2 stores the internal millisecond time value correctly,+ // but clips the values returned by the date methods to the range of+ // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).+ isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;+ } catch (exception) {}++ // Internal: Determines whether the native `JSON.stringify` and `parse`+ // implementations are spec-compliant. Based on work by Ken Snyder.+ function has(name) {+ if (has[name] !== undef) {+ // Return cached feature test result.+ return has[name];+ }++ var isSupported;+ if (name == "bug-string-char-index") {+ // IE <= 7 doesn't support accessing string characters using square+ // bracket notation. IE 8 only supports this for primitives.+ isSupported = "a"[0] != "a";+ } else if (name == "json") {+ // Indicates whether both `JSON.stringify` and `JSON.parse` are+ // supported.+ isSupported = has("json-stringify") && has("json-parse");+ } else {+ var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';+ // Test `JSON.stringify`.+ if (name == "json-stringify") {+ var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;+ if (stringifySupported) {+ // A test function object with a custom `toJSON` method.+ (value = function () {+ return 1;+ }).toJSON = value;+ try {+ stringifySupported =+ // Firefox 3.1b1 and b2 serialize string, number, and boolean+ // primitives as object literals.+ stringify(0) === "0" &&+ // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object+ // literals.+ stringify(new Number()) === "0" &&+ stringify(new String()) == '""' &&+ // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or+ // does not define a canonical JSON representation (this applies to+ // objects with `toJSON` properties as well, *unless* they are nested+ // within an object or array).+ stringify(getClass) === undef &&+ // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and+ // FF 3.1b3 pass this test.+ stringify(undef) === undef &&+ // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,+ // respectively, if the value is omitted entirely.+ stringify() === undef &&+ // FF 3.1b1, 2 throw an error if the given value is not a number,+ // string, array, object, Boolean, or `null` literal. This applies to+ // objects with custom `toJSON` methods as well, unless they are nested+ // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`+ // methods entirely.+ stringify(value) === "1" &&+ stringify([value]) == "[1]" &&+ // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of+ // `"[null]"`.+ stringify([undef]) == "[null]" &&+ // YUI 3.0.0b1 fails to serialize `null` literals.+ stringify(null) == "null" &&+ // FF 3.1b1, 2 halts serialization if an array contains a function:+ // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3+ // elides non-JSON values from objects and arrays, unless they+ // define custom `toJSON` methods.+ stringify([undef, getClass, null]) == "[null,null,null]" &&+ // Simple serialization test. FF 3.1b1 uses Unicode escape sequences+ // where character escape codes are expected (e.g., `\b` => `\u0008`).+ stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&+ // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.+ stringify(null, value) === "1" &&+ stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&+ // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly+ // serialize extended years.+ stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&+ // The milliseconds are optional in ES 5, but required in 5.1.+ stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&+ // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative+ // four-digit years instead of six-digit years. Credits: @Yaffle.+ stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&+ // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond+ // values less than 1000. Credits: @Yaffle.+ stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';+ } catch (exception) {+ stringifySupported = false;+ }+ }+ isSupported = stringifySupported;+ }+ // Test `JSON.parse`.+ if (name == "json-parse") {+ var parse = JSON3.parse;+ if (typeof parse == "function") {+ try {+ // FF 3.1b1, b2 will throw an exception if a bare literal is provided.+ // Conforming implementations should also coerce the initial argument to+ // a string prior to parsing.+ if (parse("0") === 0 && !parse(false)) {+ // Simple parsing test.+ value = parse(serialized);+ var parseSupported = value["a"].length == 5 && value["a"][0] === 1;+ if (parseSupported) {+ try {+ // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.+ parseSupported = !parse('"\t"');+ } catch (exception) {}+ if (parseSupported) {+ try {+ // FF 4.0 and 4.0.1 allow leading `+` signs and leading+ // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow+ // certain octal literals.+ parseSupported = parse("01") !== 1;+ } catch (exception) {}+ }+ if (parseSupported) {+ try {+ // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal+ // points. These environments, along with FF 3.1b1 and 2,+ // also allow trailing commas in JSON objects and arrays.+ parseSupported = parse("1.") !== 1;+ } catch (exception) {}+ }+ }+ }+ } catch (exception) {+ parseSupported = false;+ }+ }+ isSupported = parseSupported;+ }+ }+ return has[name] = !!isSupported;+ }- function isBuf(obj) {- return (global.Buffer && global.Buffer.isBuffer(obj)) ||- (global.ArrayBuffer && obj instanceof ArrayBuffer);- }-- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{}],127:[function(require,module,exports){- module.exports = toArray-- function toArray(list, index) {- var array = []+ if (!has("json")) {+ // Common `[[Class]]` name aliases.+ var functionClass = "[object Function]";+ var dateClass = "[object Date]";+ var numberClass = "[object Number]";+ var stringClass = "[object String]";+ var arrayClass = "[object Array]";+ var booleanClass = "[object Boolean]";- index = index || 0+ // Detect incomplete support for accessing string characters by index.+ var charIndexBuggy = has("bug-string-char-index");- for (var i = index || 0; i < list.length; i++) {- array[i - index] = list[i]+ // Define additional utility methods if the `Date` methods are buggy.+ if (!isExtended) {+ var floor = Math.floor;+ // A mapping between the months of the year and the number of days between+ // January 1st and the first of the respective month.+ var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];+ // Internal: Calculates the number of days between the Unix epoch and the+ // first day of the given month.+ var getDay = function (year, month) {+ return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);+ };}- return array- }-- },{}],128:[function(require,module,exports){- (function (global){- /*! http://mths.be/utf8js v2.0.0 by @mathias */- ;(function(root) {-- // Detect free variables `exports`- var freeExports = typeof exports == 'object' && exports;-- // Detect free variable `module`- var freeModule = typeof module == 'object' && module &&- module.exports == freeExports && module;-- // Detect free variable `global`, from Node.js or Browserified code,- // and use it as `root`- var freeGlobal = typeof global == 'object' && global;- if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {- root = freeGlobal;- }-- /*--------------------------------------------------------------------------*/-- var stringFromCharCode = String.fromCharCode;-- // Taken from http://mths.be/punycode- function ucs2decode(string) {- var output = [];- var counter = 0;- var length = string.length;- var value;- var 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;- }-- // Taken from http://mths.be/punycode- function ucs2encode(array) {- var length = array.length;- var index = -1;- var value;- var output = '';- while (++index < length) {- value = array[index];- if (value > 0xFFFF) {- value -= 0x10000;- output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);- value = 0xDC00 | value & 0x3FF;- }- output += stringFromCharCode(value);- }- return output;- }-- /*--------------------------------------------------------------------------*/-- function createByte(codePoint, shift) {- return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);- }-- function encodeCodePoint(codePoint) {- if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence- return stringFromCharCode(codePoint);- }- var symbol = '';- if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence- symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);- }- else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence- symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);- symbol += createByte(codePoint, 6);- }- else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence- symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);- symbol += createByte(codePoint, 12);- symbol += createByte(codePoint, 6);- }- symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);- return symbol;- }-- function utf8encode(string) {- var codePoints = ucs2decode(string);+ // Internal: Determines if a property is a direct property of the given+ // object. Delegates to the native `Object#hasOwnProperty` method.+ if (!(isProperty = {}.hasOwnProperty)) {+ isProperty = function (property) {+ var members = {}, constructor;+ if ((members.__proto__ = null, members.__proto__ = {+ // The *proto* property cannot be set multiple times in recent+ // versions of Firefox and SeaMonkey.+ "toString": 1+ }, members).toString != getClass) {+ // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but+ // supports the mutable *proto* property.+ isProperty = function (property) {+ // Capture and break the object's prototype chain (see section 8.6.2+ // of the ES 5.1 spec). The parenthesized expression prevents an+ // unsafe transformation by the Closure Compiler.+ var original = this.__proto__, result = property in (this.__proto__ = null, this);+ // Restore the original prototype chain.+ this.__proto__ = original;+ return result;+ };+ } else {+ // Capture a reference to the top-level `Object` constructor.+ constructor = members.constructor;+ // Use the `constructor` property to simulate `Object#hasOwnProperty` in+ // other environments.+ isProperty = function (property) {+ var parent = (this.constructor || constructor).prototype;+ return property in this && !(property in parent && this[property] === parent[property]);+ };+ }+ members = null;+ return isProperty.call(this, property);+ };+ }- // console.log(JSON.stringify(codePoints.map(function(x) {- // return 'U+' + x.toString(16).toUpperCase();- // })));+ // Internal: A set of primitive types used by `isHostType`.+ var PrimitiveTypes = {+ 'boolean': 1,+ 'number': 1,+ 'string': 1,+ 'undefined': 1+ };- var length = codePoints.length;- var index = -1;- var codePoint;- var byteString = '';- while (++index < length) {- codePoint = codePoints[index];- byteString += encodeCodePoint(codePoint);- }- return byteString;- }+ // Internal: Determines if the given object `property` value is a+ // non-primitive.+ var isHostType = function (object, property) {+ var type = typeof object[property];+ return type == 'object' ? !!object[property] : !PrimitiveTypes[type];+ };- /*--------------------------------------------------------------------------*/+ // Internal: Normalizes the `for...in` iteration algorithm across+ // environments. Each enumerated key is yielded to a `callback` function.+ forEach = function (object, callback) {+ var size = 0, Properties, members, property;- function readContinuationByte() {- if (byteIndex >= byteCount) {- throw Error('Invalid byte index');- }+ // Tests for bugs in the current environment's `for...in` algorithm. The+ // `valueOf` property inherits the non-enumerable flag from+ // `Object.prototype` in older versions of IE, Netscape, and Mozilla.+ (Properties = function () {+ this.valueOf = 0;+ }).prototype.valueOf = 0;- var continuationByte = byteArray[byteIndex] & 0xFF;- byteIndex++;+ // Iterate over a new instance of the `Properties` class.+ members = new Properties();+ for (property in members) {+ // Ignore all properties inherited from `Object.prototype`.+ if (isProperty.call(members, property)) {+ size++;+ }+ }+ Properties = members = null;- if ((continuationByte & 0xC0) == 0x80) {- return continuationByte & 0x3F;- }+ // Normalize the iteration algorithm.+ if (!size) {+ // A list of non-enumerable properties inherited from `Object.prototype`.+ members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];+ // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable+ // properties.+ forEach = function (object, callback) {+ var isFunction = getClass.call(object) == functionClass, property, length;+ var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;+ for (property in object) {+ // Gecko <= 1.0 enumerates the `prototype` property of functions under+ // certain conditions; IE does not.+ if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {+ callback(property);+ }+ }+ // Manually invoke the callback for each non-enumerable property.+ for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));+ };+ } else if (size == 2) {+ // Safari <= 2.0.4 enumerates shadowed properties twice.+ forEach = function (object, callback) {+ // Create a set of iterated properties.+ var members = {}, isFunction = getClass.call(object) == functionClass, property;+ for (property in object) {+ // Store each property name to prevent double enumeration. The+ // `prototype` property of functions is not enumerated due to cross-+ // environment inconsistencies.+ if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {+ callback(property);+ }+ }+ };+ } else {+ // No bugs detected; use the standard `for...in` algorithm.+ forEach = function (object, callback) {+ var isFunction = getClass.call(object) == functionClass, property, isConstructor;+ for (property in object) {+ if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {+ callback(property);+ }+ }+ // Manually invoke the callback for the `constructor` property due to+ // cross-environment inconsistencies.+ if (isConstructor || isProperty.call(object, (property = "constructor"))) {+ callback(property);+ }+ };+ }+ return forEach(object, callback);+ };- // If we end up here, it’s not a continuation byte- throw Error('Invalid continuation byte');- }+ // Public: Serializes a JavaScript `value` as a JSON string. The optional+ // `filter` argument may specify either a function that alters how object and+ // array members are serialized, or an array of strings and numbers that+ // indicates which properties should be serialized. The optional `width`+ // argument may be either a string or number that specifies the indentation+ // level of the output.+ if (!has("json-stringify")) {+ // Internal: A map of control characters and their escaped equivalents.+ var Escapes = {+ 92: "\\\\",+ 34: '\\"',+ 8: "\\b",+ 12: "\\f",+ 10: "\\n",+ 13: "\\r",+ 9: "\\t"+ };- function decodeSymbol() {- var byte1;- var byte2;- var byte3;- var byte4;- var codePoint;+ // Internal: Converts `value` into a zero-padded string such that its+ // length is at least equal to `width`. The `width` must be <= 6.+ var leadingZeroes = "000000";+ var toPaddedString = function (width, value) {+ // The `|| 0` expression is necessary to work around a bug in+ // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.+ return (leadingZeroes + (value || 0)).slice(-width);+ };- if (byteIndex > byteCount) {- throw Error('Invalid byte index');- }+ // Internal: Double-quotes a string `value`, replacing all ASCII control+ // characters (characters with code unit values between 0 and 31) with+ // their escaped equivalents. This is an implementation of the+ // `Quote(value)` operation defined in ES 5.1 section 15.12.3.+ var unicodePrefix = "\\u00";+ var quote = function (value) {+ var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;+ if (isLarge) {+ symbols = value.split("");+ }+ for (; index < length; index++) {+ var charCode = value.charCodeAt(index);+ // If the character is a control character, append its Unicode or+ // shorthand escape sequence; otherwise, append the character as-is.+ switch (charCode) {+ case 8: case 9: case 10: case 12: case 13: case 34: case 92:+ result += Escapes[charCode];+ break;+ default:+ if (charCode < 32) {+ result += unicodePrefix + toPaddedString(2, charCode.toString(16));+ break;+ }+ result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];+ }+ }+ return result + '"';+ };- if (byteIndex == byteCount) {- return false;- }+ // Internal: Recursively serializes an object. Implements the+ // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.+ var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {+ var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;+ try {+ // Necessary for host object support.+ value = object[property];+ } catch (exception) {}+ if (typeof value == "object" && value) {+ className = getClass.call(value);+ if (className == dateClass && !isProperty.call(value, "toJSON")) {+ if (value > -1 / 0 && value < 1 / 0) {+ // Dates are serialized according to the `Date#toJSON` method+ // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15+ // for the ISO 8601 date time string format.+ if (getDay) {+ // Manually compute the year, month, date, hours, minutes,+ // seconds, and milliseconds if the `getUTC*` methods are+ // buggy. Adapted from @Yaffle's `date-shim` project.+ date = floor(value / 864e5);+ for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);+ for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);+ date = 1 + date - getDay(year, month);+ // The `time` value specifies the time within the day (see ES+ // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used+ // to compute `A modulo B`, as the `%` operator does not+ // correspond to the `modulo` operation for negative numbers.+ time = (value % 864e5 + 864e5) % 864e5;+ // The hours, minutes, seconds, and milliseconds are obtained by+ // decomposing the time within the day. See section 15.9.1.10.+ hours = floor(time / 36e5) % 24;+ minutes = floor(time / 6e4) % 60;+ seconds = floor(time / 1e3) % 60;+ milliseconds = time % 1e3;+ } else {+ year = value.getUTCFullYear();+ month = value.getUTCMonth();+ date = value.getUTCDate();+ hours = value.getUTCHours();+ minutes = value.getUTCMinutes();+ seconds = value.getUTCSeconds();+ milliseconds = value.getUTCMilliseconds();+ }+ // Serialize extended years correctly.+ value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) ++ "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) ++ // Months, dates, hours, minutes, and seconds should have two+ // digits; milliseconds should have three.+ "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) ++ // Milliseconds are optional in ES 5.0, but required in 5.1.+ "." + toPaddedString(3, milliseconds) + "Z";+ } else {+ value = null;+ }+ } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {+ // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the+ // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3+ // ignores all `toJSON` methods on these objects unless they are+ // defined directly on an instance.+ value = value.toJSON(property);+ }+ }+ if (callback) {+ // If a replacement function was provided, call it to obtain the value+ // for serialization.+ value = callback.call(object, property, value);+ }+ if (value === null) {+ return "null";+ }+ className = getClass.call(value);+ if (className == booleanClass) {+ // Booleans are represented literally.+ return "" + value;+ } else if (className == numberClass) {+ // JSON numbers must be finite. `Infinity` and `NaN` are serialized as+ // `"null"`.+ return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";+ } else if (className == stringClass) {+ // Strings are double-quoted and escaped.+ return quote("" + value);+ }+ // Recursively serialize objects and arrays.+ if (typeof value == "object") {+ // Check for cyclic structures. This is a linear search; performance+ // is inversely proportional to the number of unique nested objects.+ for (length = stack.length; length--;) {+ if (stack[length] === value) {+ // Cyclic structures cannot be serialized by `JSON.stringify`.+ throw TypeError();+ }+ }+ // Add the object to the stack of traversed objects.+ stack.push(value);+ results = [];+ // Save the current indentation level and indent one additional level.+ prefix = indentation;+ indentation += whitespace;+ if (className == arrayClass) {+ // Recursively serialize array elements.+ for (index = 0, length = value.length; index < length; index++) {+ element = serialize(index, value, callback, properties, whitespace, indentation, stack);+ results.push(element === undef ? "null" : element);+ }+ result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";+ } else {+ // Recursively serialize object members. Members are selected from+ // either a user-specified list of property names, or the object+ // itself.+ forEach(properties || value, function (property) {+ var element = serialize(property, value, callback, properties, whitespace, indentation, stack);+ if (element !== undef) {+ // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}+ // is not the empty string, let `member` {quote(property) + ":"}+ // be the concatenation of `member` and the `space` character."+ // The "`space` character" refers to the literal space+ // character, not the `space` {width} argument provided to+ // `JSON.stringify`.+ results.push(quote(property) + ":" + (whitespace ? " " : "") + element);+ }+ });+ result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";+ }+ // Remove the object from the traversed object stack.+ stack.pop();+ return result;+ }+ };- // Read first byte- byte1 = byteArray[byteIndex] & 0xFF;- byteIndex++;+ // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.+ JSON3.stringify = function (source, filter, width) {+ var whitespace, callback, properties, className;+ if (typeof filter == "function" || typeof filter == "object" && filter) {+ if ((className = getClass.call(filter)) == functionClass) {+ callback = filter;+ } else if (className == arrayClass) {+ // Convert the property names array into a makeshift set.+ properties = {};+ for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));+ }+ }+ if (width) {+ if ((className = getClass.call(width)) == numberClass) {+ // Convert the `width` to an integer and create a string containing+ // `width` number of space characters.+ if ((width -= width % 1) > 0) {+ for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");+ }+ } else if (className == stringClass) {+ whitespace = width.length <= 10 ? width : width.slice(0, 10);+ }+ }+ // Opera <= 7.54u2 discards the values associated with empty string keys+ // (`""`) only if they are used directly within an object member list+ // (e.g., `!("" in { "": 1})`).+ return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);+ };+ }- // 1-byte sequence (no continuation bytes)- if ((byte1 & 0x80) == 0) {- return byte1;- }+ // Public: Parses a JSON source string.+ if (!has("json-parse")) {+ var fromCharCode = String.fromCharCode;- // 2-byte sequence- if ((byte1 & 0xE0) == 0xC0) {- var byte2 = readContinuationByte();- codePoint = ((byte1 & 0x1F) << 6) | byte2;- if (codePoint >= 0x80) {- return codePoint;- } else {- throw Error('Invalid continuation byte');- }- }+ // Internal: A map of escaped control characters and their unescaped+ // equivalents.+ var Unescapes = {+ 92: "\\",+ 34: '"',+ 47: "/",+ 98: "\b",+ 116: "\t",+ 110: "\n",+ 102: "\f",+ 114: "\r"+ };- // 3-byte sequence (may include unpaired surrogates)- if ((byte1 & 0xF0) == 0xE0) {- byte2 = readContinuationByte();- byte3 = readContinuationByte();- codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;- if (codePoint >= 0x0800) {- return codePoint;- } else {- throw Error('Invalid continuation byte');- }- }+ // Internal: Stores the parser state.+ var Index, Source;- // 4-byte sequence- if ((byte1 & 0xF8) == 0xF0) {- byte2 = readContinuationByte();- byte3 = readContinuationByte();- byte4 = readContinuationByte();- codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |- (byte3 << 0x06) | byte4;- if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {- return codePoint;- }- }+ // Internal: Resets the parser state and throws a `SyntaxError`.+ var abort = function() {+ Index = Source = null;+ throw SyntaxError();+ };- throw Error('Invalid UTF-8 detected');- }+ // Internal: Returns the next token, or `"$"` if the parser has reached+ // the end of the source string. A token may be a string, number, `null`+ // literal, or Boolean literal.+ var lex = function () {+ var source = Source, length = source.length, value, begin, position, isSigned, charCode;+ while (Index < length) {+ charCode = source.charCodeAt(Index);+ switch (charCode) {+ case 9: case 10: case 13: case 32:+ // Skip whitespace tokens, including tabs, carriage returns, line+ // feeds, and space characters.+ Index++;+ break;+ case 123: case 125: case 91: case 93: case 58: case 44:+ // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at+ // the current position.+ value = charIndexBuggy ? source.charAt(Index) : source[Index];+ Index++;+ return value;+ case 34:+ // `"` delimits a JSON string; advance to the next character and+ // begin parsing the string. String tokens are prefixed with the+ // sentinel `@` character to distinguish them from punctuators and+ // end-of-string tokens.+ for (value = "@", Index++; Index < length;) {+ charCode = source.charCodeAt(Index);+ if (charCode < 32) {+ // Unescaped ASCII control characters (those with a code unit+ // less than the space character) are not permitted.+ abort();+ } else if (charCode == 92) {+ // A reverse solidus (`\`) marks the beginning of an escaped+ // control character (including `"`, `\`, and `/`) or Unicode+ // escape sequence.+ charCode = source.charCodeAt(++Index);+ switch (charCode) {+ case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:+ // Revive escaped control characters.+ value += Unescapes[charCode];+ Index++;+ break;+ case 117:+ // `\u` marks the beginning of a Unicode escape sequence.+ // Advance to the first character and validate the+ // four-digit code point.+ begin = ++Index;+ for (position = Index + 4; Index < position; Index++) {+ charCode = source.charCodeAt(Index);+ // A valid sequence comprises four hexdigits (case-+ // insensitive) that form a single hexadecimal value.+ if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {+ // Invalid Unicode escape sequence.+ abort();+ }+ }+ // Revive the escaped character.+ value += fromCharCode("0x" + source.slice(begin, Index));+ break;+ default:+ // Invalid escape sequence.+ abort();+ }+ } else {+ if (charCode == 34) {+ // An unescaped double-quote character marks the end of the+ // string.+ break;+ }+ charCode = source.charCodeAt(Index);+ begin = Index;+ // Optimize for the common case where a string is valid.+ while (charCode >= 32 && charCode != 92 && charCode != 34) {+ charCode = source.charCodeAt(++Index);+ }+ // Append the string as-is.+ value += source.slice(begin, Index);+ }+ }+ if (source.charCodeAt(Index) == 34) {+ // Advance to the next character and return the revived string.+ Index++;+ return value;+ }+ // Unterminated string.+ abort();+ default:+ // Parse numbers and literals.+ begin = Index;+ // Advance past the negative sign, if one is specified.+ if (charCode == 45) {+ isSigned = true;+ charCode = source.charCodeAt(++Index);+ }+ // Parse an integer or floating-point value.+ if (charCode >= 48 && charCode <= 57) {+ // Leading zeroes are interpreted as octal literals.+ if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {+ // Illegal octal literal.+ abort();+ }+ isSigned = false;+ // Parse the integer component.+ for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);+ // Floats cannot contain a leading decimal point; however, this+ // case is already accounted for by the parser.+ if (source.charCodeAt(Index) == 46) {+ position = ++Index;+ // Parse the decimal component.+ for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);+ if (position == Index) {+ // Illegal trailing decimal.+ abort();+ }+ Index = position;+ }+ // Parse exponents. The `e` denoting the exponent is+ // case-insensitive.+ charCode = source.charCodeAt(Index);+ if (charCode == 101 || charCode == 69) {+ charCode = source.charCodeAt(++Index);+ // Skip past the sign following the exponent, if one is+ // specified.+ if (charCode == 43 || charCode == 45) {+ Index++;+ }+ // Parse the exponential component.+ for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);+ if (position == Index) {+ // Illegal empty exponent.+ abort();+ }+ Index = position;+ }+ // Coerce the parsed value to a JavaScript number.+ return +source.slice(begin, Index);+ }+ // A negative sign may only precede numbers.+ if (isSigned) {+ abort();+ }+ // `true`, `false`, and `null` literals.+ if (source.slice(Index, Index + 4) == "true") {+ Index += 4;+ return true;+ } else if (source.slice(Index, Index + 5) == "false") {+ Index += 5;+ return false;+ } else if (source.slice(Index, Index + 4) == "null") {+ Index += 4;+ return null;+ }+ // Unrecognized token.+ abort();+ }+ }+ // Return the sentinel `$` character if the parser has reached the end+ // of the source string.+ return "$";+ };- var byteArray;- var byteCount;- var byteIndex;- function utf8decode(byteString) {- byteArray = ucs2decode(byteString);- byteCount = byteArray.length;- byteIndex = 0;- var codePoints = [];- var tmp;- while ((tmp = decodeSymbol()) !== false) {- codePoints.push(tmp);- }- return ucs2encode(codePoints);- }+ // Internal: Parses a JSON `value` token.+ var get = function (value) {+ var results, hasMembers;+ if (value == "$") {+ // Unexpected end of input.+ abort();+ }+ if (typeof value == "string") {+ if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {+ // Remove the sentinel `@` character.+ return value.slice(1);+ }+ // Parse object and array literals.+ if (value == "[") {+ // Parses a JSON array, returning a new JavaScript array.+ results = [];+ for (;; hasMembers || (hasMembers = true)) {+ value = lex();+ // A closing square bracket marks the end of the array literal.+ if (value == "]") {+ break;+ }+ // If the array literal contains elements, the current token+ // should be a comma separating the previous element from the+ // next.+ if (hasMembers) {+ if (value == ",") {+ value = lex();+ if (value == "]") {+ // Unexpected trailing `,` in array literal.+ abort();+ }+ } else {+ // A `,` must separate each array element.+ abort();+ }+ }+ // Elisions and leading commas are not permitted.+ if (value == ",") {+ abort();+ }+ results.push(get(value));+ }+ return results;+ } else if (value == "{") {+ // Parses a JSON object, returning a new JavaScript object.+ results = {};+ for (;; hasMembers || (hasMembers = true)) {+ value = lex();+ // A closing curly brace marks the end of the object literal.+ if (value == "}") {+ break;+ }+ // If the object literal contains members, the current token+ // should be a comma separator.+ if (hasMembers) {+ if (value == ",") {+ value = lex();+ if (value == "}") {+ // Unexpected trailing `,` in object literal.+ abort();+ }+ } else {+ // A `,` must separate each object member.+ abort();+ }+ }+ // Leading commas are not permitted, object property names must be+ // double-quoted strings, and a `:` must separate each property+ // name and value.+ if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {+ abort();+ }+ results[value.slice(1)] = get(lex());+ }+ return results;+ }+ // Unexpected token encountered.+ abort();+ }+ return value;+ };- /*--------------------------------------------------------------------------*/+ // Internal: Updates a traversed object member.+ var update = function(source, property, callback) {+ var element = walk(source, property, callback);+ if (element === undef) {+ delete source[property];+ } else {+ source[property] = element;+ }+ };- var utf8 = {- 'version': '2.0.0',- 'encode': utf8encode,- 'decode': utf8decode- };+ // Internal: Recursively traverses a parsed JSON object, invoking the+ // `callback` function for each value. This is an implementation of the+ // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.+ var walk = function (source, property, callback) {+ var value = source[property], length;+ if (typeof value == "object" && value) {+ // `forEach` can't be used to traverse an array in Opera <= 8.54+ // because its `Object#hasOwnProperty` implementation returns `false`+ // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).+ if (getClass.call(value) == arrayClass) {+ for (length = value.length; length--;) {+ update(value, length, callback);+ }+ } else {+ forEach(value, function (property) {+ update(value, property, callback);+ });+ }+ }+ return callback.call(source, property, value);+ };- // 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(function() {- return utf8;- });- } else if (freeExports && !freeExports.nodeType) {- if (freeModule) { // in Node.js or RingoJS v0.8.0+- freeModule.exports = utf8;- } else { // in Narwhal or RingoJS v0.7.0-- var object = {};- var hasOwnProperty = object.hasOwnProperty;- for (var key in utf8) {- hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);- }- }- } else { // in Rhino or a web browser- root.utf8 = utf8;- }+ // Public: `JSON.parse`. See ES 5.1 section 15.12.2.+ JSON3.parse = function (source, callback) {+ var result, value;+ Index = 0;+ Source = "" + source;+ result = get(lex());+ // If a JSON string contains multiple tokens, it is invalid.+ if (lex() != "$") {+ abort();+ }+ // Reset the parser state.+ Index = Source = null;+ return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;+ };+ }+ }+ // Export for asynchronous module loaders.+ if (isLoader) {+ define(function () {+ return JSON3;+ });+ }}(this));- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})- },{}],129:[function(require,module,exports){-- /**- * Module dependencies.- */-- var global = (function() { return this; })();-- /**- * WebSocket constructor.- */-- var WebSocket = global.WebSocket || global.MozWebSocket;-},{}],134:[function(require,module,exports){++},{}],131:[function(require,module,exports){+ module.exports = toArray- /**- * Module exports.- */+ function toArray(list, index) {+ var array = []- module.exports = WebSocket ? ws : null;+ index = index || 0- /**- * WebSocket constructor.- *- * The third `opts` options object gets ignored in web browsers, since it's- * non-standard, and throws a TypeError if passed to the constructor.- * See: https://github.com/einaros/ws/issues/227- *- * @param {String} uri- * @param {Array} protocols (optional)- * @param {Object) opts (optional)- * @api public- */+ for (var i = index || 0; i < list.length; i++) {+ array[i - index] = list[i]+ }- function ws(uri, protocols, opts) {- var instance;- if (protocols) {- instance = new WebSocket(uri, protocols);- } else {- instance = new WebSocket(uri);- }- return instance;+ return array}- if (WebSocket) ws.prototype = WebSocket.prototype;-- },{}],130:[function(require,module,exports){-},{}],135:[function(require,module,exports){++},{}],132:[function(require,module,exports){var MediaStreamType = {VIDEO_TYPE: "Video",AUDIO_TYPE: "Audio"};module.exports = MediaStreamType;- },{}],131:[function(require,module,exports){-},{}],136:[function(require,module,exports){++},{}],133:[function(require,module,exports){var RTCEvents = {RTC_READY: "rtc.ready",DATA_CHANNEL_OPEN: "rtc.data_channel_open",@@@ -31421,7 -31366,7 +31442,7 @@@};module.exports = RTCEvents;- },{}],132:[function(require,module,exports){-},{}],137:[function(require,module,exports){++},{}],134:[function(require,module,exports){var Resolutions = {"1080": {width: 1920,@@@ -31475,7 -31420,7 +31496,7 @@@}};module.exports = Resolutions;- },{}],133:[function(require,module,exports){-},{}],138:[function(require,module,exports){++},{}],135:[function(require,module,exports){var AuthenticationEvents = {/*** Event callback arguments:@@@ -31489,7 -31434,7 +31510,7 @@@};module.exports = AuthenticationEvents;- },{}],134:[function(require,module,exports){-},{}],139:[function(require,module,exports){++},{}],136:[function(require,module,exports){var DesktopSharingEventTypes = {/*** An event which indicates that the jidesha extension for Firefox is@@@ -31500,7 -31445,7 +31521,7 @@@module.exports = DesktopSharingEventTypes;- },{}],135:[function(require,module,exports){-},{}],140:[function(require,module,exports){++},{}],137:[function(require,module,exports){module.exports = {/*** An event carrying connection statistics.@@@ -31516,12 -31461,12 +31537,12 @@@STOP: "statistics.stop"};- },{}],136:[function(require,module,exports){-},{}],141:[function(require,module,exports){++},{}],138:[function(require,module,exports){var Constants = {LOCAL_JID: 'local'};module.exports = Constants;- },{}],137:[function(require,module,exports){-},{}],142:[function(require,module,exports){++},{}],139:[function(require,module,exports){var XMPPEvents = {// Designates an event indicating that the connection to the XMPP server// failed.