Esempio n. 1
0
var ImageProgress = module.exports = function(url, params) {
    EventEmitter.call(this);

    if(!url) throw new Error('URL should be a valid string');

    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());

    this.options = _.merge({
        autostart: false,
        autoclear: true,
        leading: 2,
        jsonp: false,
    }, params);

    this.options.url = url;
    
    if ( this.options.jsonp ) {
        this.options.url += (this.options.url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    }

    this.loaded = 0;
    this.total = 0;
    this.progress = 0;

    this.request = new XMLHttpRequest();
    this.request.onprogress = this.onProgress.bind(this);
    this.request.onload = this.onComplete.bind(this);
    this.request.onerror = this.onError.bind(this);

    if(this.options.autostart) this.load();
};
Esempio n. 2
0
function ButtonSet(el, opts) {
  if (!(this instanceof ButtonSet)) return new ButtonSet(el, opts);
  Emitter.call(this);

  this.el = o(el);
  classes(this.el.get(0)).add('buttonset');
  this.options = opts || {};

  // add buttons
  if (this.options.buttons) {
    for (var i = 0; i < this.options.buttons.length; i++) {
      this.add(this.options.buttons[i]);
    }
  }

  // force unselectable if buttonset is multiple
  if (this.options.multiple) this.options.unselectable = true;

  if ('undefined' != typeof this.options.select) this.set(this.options.select);

  // bind click event to options
  this.el.on('click', 'a', this.onSet.bind(this));

  return this;
}
Esempio n. 3
0
function Rating(opts) {
  if (!(this instanceof Rating)) return new Rating(opts);
  Emitter.call(this);
  var self = this;
  opts = opts || {};

  var data = {};
  data.stars = opts.stars != null? opts.stars : 5;
  var el = this.el = domify(require('./template')(data));

  this.stars = data.stars;
  this.els = [].slice.call(el.children);
  this.delay = opts.delay != null? opts.delay : 100;
  this.current = [];
  this.disabled = false;

  var timeout = null;
  var reset = true;

  var over = function(star, i){
    if (timeout !== null) {
      clearTimeout(timeout);
      timeout = null;
    }

    if (reset) {
      reset = false;
      self.emit('mouseenter', star, i);
    }

    if (!this.disabled) {
      this.highlight(range(1, i), true);
      this.highlight(range(i+1, this.stars), false);
    }
  };

  var out = function(star, i) {
    timeout = setTimeout(function(){
      reset = true;
      self.emit('mouseleave', star, i);
      if (!this.disabled) {
        self.highlight(range(1, self.stars), false);
        self.highlight(self.current, true);
      }
    }, this.delay);
  };

  var click = function(star, i) {
    this.emit("click", star, i, self.disabled);
    if (!self.disabled)
      self.rate(i);
    classes(star).toggle('clicked');
  }

  each(el.children, function(star, i){
    var bnd = function(fn) { return bind(self, fn, star, i+1); };
    hover(star, bnd(over), bnd(out));
    events.bind(star, 'click', bnd(click));
  });
}
Esempio n. 4
0
function Menu() {
  if (!(this instanceof Menu)) return new Menu;
  Emitter.call(this);
  this.items = [];
  this.el = o('<ul class=menu>').hide().appendTo('body');
  this.on('show', this.bindEvents.bind(this));
  this.on('hide', this.unbindEvents.bind(this));
  this._isOpen = false;
}
Esempio n. 5
0
function Glob(options) {
  if (!(this instanceof Glob)) {
    return new Glob(options);
  }

  Emitter.call(this);
  this.handler = new Handler(this);
  this.init(options);
}
Esempio n. 6
0
function Composer(name) {
  Emitter.call(this);
  this.tasks = {};
  utils.define(this, '_appname', name || 'composer');
  utils.define(this, 'buildHistory', {
    get: function() {
      return builds;
    }
  });
}
Esempio n. 7
0
function WebSocketWrapper(url) {
	if (!(this instanceof WebSocketWrapper))
		return new WebSocketWrapper(url);

	Emitter.call(this);
	if (!url) throw new Error('WebSocketWrapper: url is required.')

	this.url = url;
	this._socket = this._connect();
}
Esempio n. 8
0
	function Model(data) {
		if (!(this instanceof Model)) return new Model(data);
		Emitter.call(this);
		this._data = {};
		data = data || {};
		this._model.emit('construct', this, data);
		for (var prop in data) {
			if (!(prop in Model._skip))
				this[prop] = data[prop];
		}
	}
function Calendar(options) {
  Emitter.call(this);
  this.el = $(options.template || this.template);
  this.el.on('click', '.js-next', bind(this, 'next') );
  this.el.on('click', '.js-previous', bind(this, 'previous') );
  this.el.on('click', '.js-today', bind(this, 'today') );
  this.el.on('click', '.js-select', bind(this, 'onSelect') );
  this.title = this.el.find(this.titleSelector);
  this.body = this.el.find(this.bodySelector);
  this.current = this.selected = moment();
  this.render();
};
Esempio n. 10
0
function Request(method, url) {
    var self = this;
    Emitter.call(this);
    this.method = method;
    this.url = url;
    this.header = {};
    this.isAsync = true;
    this.set('X-Requested-With', 'XMLHttpRequest');
    this.on('end', function(){
        self.callback(new Response(self.xhr));
    });
}
Esempio n. 11
0
function Days() {
  Emitter.call(this);
  var self = this;
  this.el = domify(template);
  classes(this.el).add('calendar-days');
  this.head = this.el.tHead;
  this.body = this.el.tBodies[0];
  this.title = this.head.querySelector('.title');
  this.select(new Date);
  this.validRange = new DayRange;

  // emit "day"
  events.bind(this.body, 'click', normalize(function(e){
    if (e.target.tagName !== 'A') {
      return true;
    }

    e.preventDefault();

    var el = e.target;
    var data = el.getAttribute('data-date').split('-');
    if (!self.validRange.valid(data)) {
      return false;
    }
    var year = data[0];
    var month = data[1];
    var day = data[2];
    var date = new Date(year, month, day);
    self.select(date);
    self.emit('change', date);
    return false;
  }));

  // emit "prev"
  events.bind(this.el.querySelector('.prev'), 'click', normalize(function(ev){
    ev.preventDefault();

    self.emit('prev');
    return false;
  }));

  // emit "next"
  events.bind(this.el.querySelector('.next'), 'click', normalize(function(ev){
    ev.preventDefault();

    self.emit('next');
    return false;
  }));
}
Esempio n. 12
0
var SCChannel = function (name, client, options) {
  var self = this;

  Emitter.call(this);

  this.PENDING = 'pending';
  this.SUBSCRIBED = 'subscribed';
  this.UNSUBSCRIBED = 'unsubscribed';

  this.name = name;
  this.state = this.UNSUBSCRIBED;
  this.client = client;

  this.options = options || {};
  this.setOptions(this.options);
};
Esempio n. 13
0
function Calendar(date) {
  Emitter.call(this);
  var self = this;
  this.el = o('<div class=calendar></div>');
  this.days = new Days;
  this.el.append(this.days.el);
  this.on('change', this.show.bind(this));
  this.days.on('prev', this.prev.bind(this));
  this.days.on('next', this.next.bind(this));
  this.days.on('year', this.menuChange.bind(this, 'year'));
  this.days.on('month', this.menuChange.bind(this, 'month'));
  this.show(date || new Date);
  this.days.on('change', function(date){
    if (self.invalidDate(date)) { return };
    self.emit('change', date);
  });
}
Esempio n. 14
0
function Task(task) {
  if (!(this instanceof Task)) {
    return new Task(task);
  }
  Emitter.call(this);
  if (typeof task === 'undefined') {
    throw new Error('Expected `task` to be an `object` but got `' + typeof task + '`.');
  }
  if (typeof task.name === 'undefined') {
    throw new Error('Expected `task.name` to be a `string` but got `' + typeof task.name + '`.');
  }
  this.app = task.app;
  this.name = task.name;
  this.options = task.options || {};
  this.deps = task.deps || this.options.deps || [];
  this.fn = task.fn || noop;
  this._runs = [];
}
Esempio n. 15
0
var AbstractNode = function () {
  Emitter.call(this)

  // Each node has an id. That is used by the parent nodes and in views.
  this.id = seqid.next().toString()

  // Nodes with null parent are root nodes i.e. spaces.
  // AbstractNode#remove sets _parent to null.
  this._parent = null

  // Keep track on node siblings in two-way linked list manner.
  this._prevSibling = null
  this._nextSibling = null

  // Dict because good key search time complexity
  this._children = {}
  // List for children order
  this._order = []
}
Esempio n. 16
0
/**
 * TableSorter
 *
 * @param {Element} table
 * @param {Object} options
 * @api public
 */
function TableSorter(table, options) {
  if (!(this instanceof TableSorter)) return new TableSorter(table, options);
  var self = this;
  Emitter.call(this);
  options = options || {};
  var defaultSort = function(h, i){
    return function(a, b) {
      a = a.children[i];
      b = b.children[i];
      return natural(a.textContent, b.textContent);
    };
  };
  options.sort = options.sort || defaultSort;
  TableSorter.defaultSort = defaultSort;
  this.defaultSort = defaultSort;
  this.options = options;
  this.table = table;
  this.order = 'none';
  this.attach(table, options);
}
function Client(node, parent){
  if (!(this instanceof Client)) {
    return new Client(node, parent);
  }
  Emitter.call(this);
  this.loaded = false;    // "true" when the SWF movie has loaded
  this._text = '';        // the text to copy to the clipboard. set with "text()".
  this._cursor = true;    // whether to show the hand cursor on mouse-over
  this.zIndex = 99;       // default z-index of the movie object

  // unique ID
  this.id = window.ZeroClipboard.nextId++;
  this.movieId = 'ZeroClipboardMovie_' + this.id;

  // register client with ZeroClipboard global to receive flash events
  window.ZeroClipboard.clients[this.id] = this;

  // create movie
  if (node) this.render(node, parent);
}
Esempio n. 18
0
var SCEmitter = function () {
  Emitter.call(this);
};
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.socketCluster=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],2:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],3:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":1,"./encode":2}],4:[function(require,module,exports){var pkg=require("./package.json");var SCSocket=require("./lib/scsocket");module.exports.SCSocket=SCSocket;module.exports.SCEmitter=require("sc-emitter").SCEmitter;module.exports.connect=function(options){return new SCSocket(options)};module.exports.version=pkg.version},{"./lib/scsocket":8,"./package.json":18,"sc-emitter":14}],5:[function(require,module,exports){(function(global){var AuthEngine=function(){this._internalStorage={}};AuthEngine.prototype.saveToken=function(name,token,options,callback){var store=options.persistent?global.localStorage:global.sessionStorage;var secondaryStore=options.persistent?global.sessionStorage:global.localStorage;if(store){store.setItem(name,token);if(secondaryStore){secondaryStore.removeItem(name)}}else{this._internalStorage[name]=token}callback&&callback()};AuthEngine.prototype.removeToken=function(name,callback){var localStore=global.localStorage;var sessionStore=global.sessionStorage;if(localStore){localStore.removeItem(name)}if(sessionStore){sessionStore.removeItem(name)}delete this._internalStorage[name];callback&&callback()};AuthEngine.prototype.loadToken=function(name,callback){var localStore=global.localStorage;var sessionStore=global.sessionStorage;var token;if(sessionStore){token=sessionStore.getItem(name)}if(localStore&&token==null){token=localStore.getItem(name)}if(token==null){token=this._internalStorage[name]||null}callback(null,token)};module.exports.AuthEngine=AuthEngine}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],6:[function(require,module,exports){module.exports.create=function(){function F(){}return function(o){if(arguments.length!=1){throw new Error("Object.create implementation only accepts one parameter.")}F.prototype=o;return new F}}()},{}],7:[function(require,module,exports){var Response=function(socket,id){this.socket=socket;this.id=id};Response.prototype._respond=function(responseData){this.socket.send(this.socket.stringify(responseData))};Response.prototype.end=function(data){if(this.id){var responseData={rid:this.id};if(data!==undefined){responseData.data=data}this._respond(responseData)}};Response.prototype.error=function(error,data){if(this.id){var err;if(error instanceof Error){err={name:error.name,message:error.message,stack:error.stack}}else{err=error}var responseData={rid:this.id,error:err};if(data!==undefined){responseData.data=data}this._respond(responseData)}};Response.prototype.callback=function(error,data){if(error){this.error(error,data)}else{this.end(data)}};module.exports.Response=Response},{}],8:[function(require,module,exports){(function(global){var SCEmitter=require("sc-emitter").SCEmitter;var SCChannel=require("sc-channel").SCChannel;var Response=require("./response").Response;var AuthEngine=require("./auth").AuthEngine;var SCTransport=require("./sctransport").SCTransport;var querystring=require("querystring");var LinkedList=require("linked-list");if(!Object.create){Object.create=require("./objectcreate")}var isBrowser=typeof window!="undefined";var SCSocket=function(options){var self=this;SCEmitter.call(this);var opts={port:null,autoReconnect:true,ackTimeout:1e4,hostname:global.location&&location.hostname,path:"/socketcluster/",secure:global.location&&location.protocol=="https:",timestampRequests:false,timestampParam:"t",authEngine:null,authTokenName:"socketCluster.authToken",binaryType:"arraybuffer"};for(var i in options){opts[i]=options[i]}this.id=null;this.state=this.CLOSED;this.ackTimeout=opts.ackTimeout;this.pingTimeout=this.ackTimeout;var maxTimeout=Math.pow(2,31)-1;var verifyDuration=function(propertyName){if(self[propertyName]>maxTimeout){throw new Error("The "+propertyName+" value provided exceeded the maximum amount allowed")}};verifyDuration("ackTimeout");verifyDuration("pingTimeout");this._localEvents={connect:1,connectAbort:1,disconnect:1,message:1,error:1,raw:1,fail:1,kickOut:1,subscribe:1,unsubscribe:1,setAuthToken:1,removeAuthToken:1};this._connectAttempts=0;this._emitBuffer=new LinkedList;this._channels={};this._base64Chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.options=opts;if(this.options.autoReconnect){if(this.options.autoReconnectOptions==null){this.options.autoReconnectOptions={}}var reconnectOptions=this.options.autoReconnectOptions;if(reconnectOptions.initialDelay==null){reconnectOptions.initialDelay=1e4}if(reconnectOptions.randomness==null){reconnectOptions.randomness=1e4}if(reconnectOptions.multiplier==null){reconnectOptions.multiplier=1.5}if(reconnectOptions.maxDelay==null){reconnectOptions.maxDelay=6e4}}if(this.options.subscriptionRetryOptions==null){this.options.subscriptionRetryOptions={}}if(this.options.authEngine){this.auth=this.options.authEngine}else{this.auth=new AuthEngine}this.options.path=this.options.path.replace(/\/$/,"")+"/";this.options.query=opts.query||{};if(typeof this.options.query=="string"){this.options.query=querystring.parse(this.options.query)}this.options.port=opts.port||(global.location&&location.port?location.port:this.options.secure?443:80);this.connect();this._channelEmitter=new SCEmitter;if(isBrowser){var unloadHandler=function(){self.disconnect()};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}};SCSocket.prototype=Object.create(SCEmitter.prototype);SCSocket.CONNECTING=SCSocket.prototype.CONNECTING=SCTransport.prototype.CONNECTING;SCSocket.OPEN=SCSocket.prototype.OPEN=SCTransport.prototype.OPEN;SCSocket.CLOSED=SCSocket.prototype.CLOSED=SCTransport.prototype.CLOSED;SCSocket.ignoreStatuses={1e3:"Socket closed normally",1001:"Socket hung up"};SCSocket.errorStatuses={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Server failed to sign auth token",4003:"Failed to complete handshake",4004:"Client failed to save auth token"};SCSocket.prototype._privateEventHandlerMap={"#fail":function(data){this._onSCError(data)},"#publish":function(data){var isSubscribed=this.isSubscribed(data.channel,true);if(isSubscribed){this._channelEmitter.emit(data.channel,data.data)}},"#kickOut":function(data){var channelName=data.channel;var channel=this._channels[channelName];if(channel){SCEmitter.prototype.emit.call(this,"kickOut",data.message,channelName);channel.emit("kickOut",data.message,channelName);this._triggerChannelUnsubscribe(channel)}},"#setAuthToken":function(data,response){var self=this;if(data){var tokenOptions={persistent:!!data.persistent,expiresInMinutes:!!data.expiresInMinutes};var triggerSetAuthToken=function(err){if(err){response.error(err.message||err);self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"setAuthToken",data.token);response.end()}};if(data.persistent&&data.expiresInMinutes!=null){this.auth.saveToken(this.options.authTokenName,data.token,tokenOptions,triggerSetAuthToken)}else{this.auth.saveToken(this.options.authTokenName,data.token,tokenOptions,triggerSetAuthToken)}}else{response.error("No token data provided with setAuthToken event")}},"#removeAuthToken":function(data,response){var self=this;this.auth.removeToken(this.options.authTokenName,function(err){if(err){response.error(err.message||err);self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"removeAuthToken");response.end()}})},"#disconnect":function(data){this.transport.close(data.code,data.data)}};SCSocket.prototype.getState=function(){return this.state};SCSocket.prototype.getBytesReceived=function(){return this.transport.getBytesReceived()};SCSocket.prototype.removeAuthToken=function(callback){var self=this;this.auth.removeToken(this.options.authTokenName,function(err){callback&&callback(err);if(err){self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"removeAuthToken")}})};SCSocket.prototype.connect=SCSocket.prototype.open=function(){var self=this;if(this.state==this.CLOSED){clearTimeout(this._reconnectTimeout);this.state=this.CONNECTING;if(this.transport){this.transport.off()}this.transport=new SCTransport(this.auth,this.options);this.transport.on("open",function(status){self.state=self.OPEN;self._onSCOpen(status)});this.transport.on("error",function(err){self._onSCError(err)});this.transport.on("close",function(code,data){self.state=self.CLOSED;self._onSCClose(code,data)});this.transport.on("openAbort",function(code,data){self.state=self.CLOSED;self._onSCClose(code,data,true)});this.transport.on("event",function(event,data,res){self._onSCEvent(event,data,res)})}};SCSocket.prototype.disconnect=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this.transport.emit("#disconnect",packet);this.transport.close(code)}else if(this.state==this.CONNECTING){this.transport.close(code)}};SCSocket.prototype._tryReconnect=function(initialDelay){var self=this;var exponent=this._connectAttempts++;var reconnectOptions=this.options.autoReconnectOptions;var timeout;if(initialDelay==null||exponent>0){var initialTimeout=Math.round(reconnectOptions.initialDelay+(reconnectOptions.randomness||0)*Math.random());timeout=Math.round(initialTimeout*Math.pow(reconnectOptions.multiplier,exponent))}else{timeout=initialDelay}if(timeout>reconnectOptions.maxDelay){timeout=reconnectOptions.maxDelay}clearTimeout(this._reconnectTimeout);this._reconnectTimeout=setTimeout(function(){self.connect()},timeout)};SCSocket.prototype._onSCOpen=function(status){if(status){this.id=status.id;this.pingTimeout=status.pingTimeout;this.transport.pingTimeout=this.pingTimeout}this._connectAttempts=0;this._resubscribe();SCEmitter.prototype.emit.call(this,"connect",status);this._flushEmitBuffer()};SCSocket.prototype._onSCError=function(err){var self=this;setTimeout(function(){if(self.listeners("error").length<1){throw err}else{SCEmitter.prototype.emit.call(self,"error",err)}},0)};SCSocket.prototype._suspendSubscriptions=function(){var channel,newState;for(var channelName in this._channels){channel=this._channels[channelName];if(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING){newState=channel.PENDING}else{newState=channel.UNSUBSCRIBED}this._triggerChannelUnsubscribe(channel,newState)}};SCSocket.prototype._onSCClose=function(code,data,openAbort){var self=this;this.id=null;if(this.transport){this.transport.off()}clearTimeout(this._reconnectTimeout);this._suspendSubscriptions();if(openAbort){SCEmitter.prototype.emit.call(self,"connectAbort",code,data)}else{SCEmitter.prototype.emit.call(self,"disconnect",code,data)}if(this.options.autoReconnect){if(code==4e3||code==4001||code==1005){this._tryReconnect(0)}else if(code==1006||code==4003){this._tryReconnect()}}if(!SCSocket.ignoreStatuses[code]){var err=new Error(SCSocket.errorStatuses[code]||"Socket connection failed for unknown reasons");err.code=code;this._onSCError(err)}};SCSocket.prototype._onSCEvent=function(event,data,res){var handler=this._privateEventHandlerMap[event];if(handler){handler.call(this,data,res)}else{SCEmitter.prototype.emit.call(this,event,data,res)}};SCSocket.prototype.parse=function(message){return this.transport.parse(message)};SCSocket.prototype.stringify=function(object){return this.transport.stringify(object)};SCSocket.prototype._flushEmitBuffer=function(){var currentNode=this._emitBuffer.head;var nextNode;while(currentNode){nextNode=currentNode.next;var eventObject=currentNode.data;currentNode.detach();this.transport.emitRaw(eventObject);currentNode=nextNode}};SCSocket.prototype._handleEventAckTimeout=function(eventObject,eventNode){var errorMessage="Event response for '"+eventObject.event+"' timed out";var error=new Error(errorMessage);error.type="timeout";var callback=eventObject.callback;delete eventObject.callback;if(eventNode){eventNode.detach()}callback.call(eventObject,error,eventObject);this._onSCError(error)};SCSocket.prototype._emit=function(event,data,callback){var self=this;if(this.state==this.CLOSED){this.connect()}var eventObject={event:event,data:data,callback:callback};var eventNode=new LinkedList.Item;eventNode.data=eventObject;if(callback){eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject,eventNode)},this.ackTimeout)}this._emitBuffer.append(eventNode);if(this.state==this.OPEN){this._flushEmitBuffer()}};SCSocket.prototype.emit=function(event,data,callback){if(this._localEvents[event]==null){this._emit(event,data,callback)}else{SCEmitter.prototype.emit.call(this,event,data)}};SCSocket.prototype.publish=function(channelName,data,callback){var pubData={channel:channelName,data:data};this.emit("#publish",pubData,function(err){callback&&callback(err)})};SCSocket.prototype._triggerChannelSubscribe=function(channel){var channelName=channel.name;if(channel.state!=channel.SUBSCRIBED){channel.state=channel.SUBSCRIBED;channel.emit("subscribe",channelName);SCEmitter.prototype.emit.call(this,"subscribe",channelName)}};SCSocket.prototype._triggerChannelSubscribeFail=function(err,channel){var channelName=channel.name;if(channel.state!=channel.UNSUBSCRIBED){channel.state=channel.UNSUBSCRIBED;channel.emit("subscribeFail",err,channelName);SCEmitter.prototype.emit.call(this,"subscribeFail",err,channelName)}};SCSocket.prototype._cancelPendingSubscribeCallback=function(channel){if(channel._pendingSubscriptionCid!=null){this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);delete channel._pendingSubscriptionCid}};SCSocket.prototype._trySubscribe=function(channel){var self=this;if(this.state==this.OPEN&&channel._pendingSubscriptionCid==null){var options={noTimeout:true};channel._pendingSubscriptionCid=this.transport.emit("#subscribe",channel.name,options,function(err){delete channel._pendingSubscriptionCid;if(err){self._triggerChannelSubscribeFail(err,channel)}else{self._triggerChannelSubscribe(channel)}})}};SCSocket.prototype.subscribe=function(channelName){var channel=this._channels[channelName];if(!channel){channel=new SCChannel(channelName,this);this._channels[channelName]=channel}if(channel.state==channel.UNSUBSCRIBED){channel.state=channel.PENDING;this._trySubscribe(channel)}return channel};SCSocket.prototype._triggerChannelUnsubscribe=function(channel,newState){var channelName=channel.name;var oldState=channel.state;if(newState){channel.state=newState}else{channel.state=channel.UNSUBSCRIBED}this._cancelPendingSubscribeCallback(channel);if(oldState==channel.SUBSCRIBED){channel.emit("unsubscribe",channelName);SCEmitter.prototype.emit.call(this,"unsubscribe",channelName)}};SCSocket.prototype._tryUnsubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubscribeCallback(channel);this.transport.emit("#unsubscribe",channel.name,options)}};SCSocket.prototype.unsubscribe=function(channelName){var channel=this._channels[channelName];if(channel){if(channel.state!=channel.UNSUBSCRIBED){this._triggerChannelUnsubscribe(channel);this._tryUnsubscribe(channel)}}};SCSocket.prototype.channel=function(channelName){var currentChannel=this._channels[channelName];if(!currentChannel){currentChannel=new SCChannel(channelName,this);this._channels[channelName]=currentChannel}return currentChannel};SCSocket.prototype.destroyChannel=function(channelName){var channel=this._channels[channelName];channel.unwatch();channel.unsubscribe();delete this._channels[channelName]};SCSocket.prototype.subscriptions=function(includePending){var subs=[];var channel,includeChannel;for(var channelName in this._channels){channel=this._channels[channelName];if(includePending){includeChannel=channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}else{includeChannel=channel&&channel.state==channel.SUBSCRIBED}if(includeChannel){subs.push(channelName)}}return subs};SCSocket.prototype.isSubscribed=function(channel,includePending){var channel=this._channels[channel];if(includePending){return!!channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}return!!channel&&channel.state==channel.SUBSCRIBED};SCSocket.prototype._resubscribe=function(){var self=this;var channels=[];for(var channelName in this._channels){channels.push(channelName)}for(var i in this._channels){(function(channel){if(channel.state==channel.PENDING){self._trySubscribe(channel)}})(this._channels[i])}};SCSocket.prototype.watch=function(channelName,handler){this._channelEmitter.on(channelName,handler)};SCSocket.prototype.unwatch=function(channelName,handler){if(handler){this._channelEmitter.removeListener(channelName,handler)}else{this._channelEmitter.removeAllListeners(channelName)}};SCSocket.prototype.watchers=function(channelName){return this._channelEmitter.listeners(channelName)};module.exports=SCSocket}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./auth":5,"./objectcreate":6,"./response":7,"./sctransport":9,"linked-list":11,querystring:3,"sc-channel":12,"sc-emitter":14}],9:[function(require,module,exports){var WebSocket=require("ws");var SCEmitter=require("sc-emitter").SCEmitter;var Response=require("./response").Response;var querystring=require("querystring");var SCTransport=function(authEngine,options){this.state=this.CLOSED;this.auth=authEngine;this.options=options;this.pingTimeout=options.ackTimeout;this._cid=1;this._pingTimeoutTicker=null;this._callbackMap={};this.open()};SCTransport.prototype=Object.create(SCEmitter.prototype);SCTransport.CONNECTING=SCTransport.prototype.CONNECTING="connecting";SCTransport.OPEN=SCTransport.prototype.OPEN="open";SCTransport.CLOSED=SCTransport.prototype.CLOSED="closed";SCTransport.prototype.uri=function(){var query=this.options.query||{};var schema=this.options.secure?"wss":"ws";var port="";if(this.options.port&&("wss"==schema&&this.options.port!=443||"ws"==schema&&this.options.port!=80)){port=":"+this.options.port}if(this.options.timestampRequests){query[this.options.timestampParam]=(new Date).getTime()}query=querystring.stringify(query);if(query.length){query="?"+query}return schema+"://"+this.options.hostname+port+this.options.path+query};SCTransport.prototype._nextCallId=function(){return this._cid++};SCTransport.prototype.open=function(){var self=this;this.state=this.CONNECTING;var uri=this.uri();var wsSocket=new WebSocket(uri,null,this.options);wsSocket.binaryType=this.options.binaryType;this.socket=wsSocket;wsSocket.onopen=function(){self._onOpen()};wsSocket.onclose=function(event){self._onClose(event.code,event.reason)};wsSocket.onmessage=function(message,flags){self._onMessage(message.data)}};SCTransport.prototype._onOpen=function(){var self=this;this._resetPingTimeout();this._handshake(function(err,status){if(err){self._onError(err);self._onClose(4003);self.socket.close(4003)}else{self.state=self.OPEN;SCEmitter.prototype.emit.call(self,"open",status);self._resetPingTimeout()}})};SCTransport.prototype._handshake=function(callback){var self=this;this.auth.loadToken(this.options.authTokenName,function(err,token){if(err){callback(err)}else{var options={force:true};self.emit("#handshake",{authToken:token},options,callback)}})};SCTransport.prototype._onClose=function(code,data){delete this.socket.onopen;delete this.socket.onclose;delete this.socket.onmessage;if(this.state==this.OPEN){this.state=this.CLOSED;SCEmitter.prototype.emit.call(this,"close",code,data)}else if(this.state==this.CONNECTING){this.state=this.CLOSED;SCEmitter.prototype.emit.call(this,"openAbort",code,data)}};SCTransport.prototype._onMessage=function(message){SCEmitter.prototype.emit.call(this,"event","message",message);if(message=="1"){this._resetPingTimeout();if(this.socket.readyState==this.socket.OPEN){this.socket.send("2")}}else{var obj;try{obj=this.parse(message)}catch(err){obj=message}var event=obj.event;if(event){var response=new Response(this,obj.cid);SCEmitter.prototype.emit.call(this,"event",event,obj.data,response)}else if(obj.rid!=null){var eventObject=this._callbackMap[obj.rid];if(eventObject){clearTimeout(eventObject.timeout);delete this._callbackMap[obj.rid];eventObject.callback(obj.error,obj.data)}if(obj.error){this._onError(obj.error)}}else{SCEmitter.prototype.emit.call(this,"event","raw",obj)}}};SCTransport.prototype._onError=function(err){SCEmitter.prototype.emit.call(this,"error",err)};SCTransport.prototype._resetPingTimeout=function(){var self=this;var now=(new Date).getTime();clearTimeout(this._pingTimeoutTicker);this._pingTimeoutTicker=setTimeout(function(){self._onClose(4e3);self.socket.close(4e3)},this.pingTimeout)};SCTransport.prototype.getBytesReceived=function(){return this.socket.bytesReceived};SCTransport.prototype.close=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this.emit("#disconnect",packet);this._onClose(code,data);this.socket.close(code)}else if(this.state==this.CONNECTING){this._onClose(code,data);this.socket.close(code)}};SCTransport.prototype.emitRaw=function(eventObject){eventObject.cid=this._nextCallId();if(eventObject.callback){this._callbackMap[eventObject.cid]=eventObject}var simpleEventObject={event:eventObject.event,data:eventObject.data,cid:eventObject.cid};this.sendObject(simpleEventObject);return eventObject.cid};SCTransport.prototype._handleEventAckTimeout=function(eventObject){var errorMessage="Event response for '"+eventObject.event+"' timed out";var error=new Error(errorMessage);error.type="timeout";if(eventObject.cid){delete this._callbackMap[eventObject.cid]}var callback=eventObject.callback;delete eventObject.callback;callback.call(eventObject,error,eventObject);this._onError(error)};SCTransport.prototype.emit=function(event,data,a,b){var self=this;var callback,options;if(b){options=a;callback=b}else{if(a instanceof Function){options={};callback=a}else{options=a}}var eventObject={event:event,data:data,callback:callback};if(callback&&!options.noTimeout){eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject)},this.options.ackTimeout)}var cid=null;if(this.state==this.OPEN||options.force){cid=this.emitRaw(eventObject)}return cid};SCTransport.prototype.cancelPendingResponse=function(cid){delete this._callbackMap[cid]};SCTransport.prototype._isOwnDescendant=function(object,ancestors){for(var i in ancestors){if(ancestors[i]===object){return true}}return false};SCTransport.prototype._arrayBufferToBase64=function(arraybuffer){var chars=this._base64Chars;var bytes=new Uint8Array(arraybuffer);var len=bytes.length;var base64="";for(var 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};SCTransport.prototype._convertBuffersToBase64=function(object,ancestors){if(!ancestors){ancestors=[]}if(this._isOwnDescendant(object,ancestors)){throw new Error("Cannot traverse circular structure")}var newAncestors=ancestors.concat([object]);if(typeof ArrayBuffer!="undefined"&&object instanceof ArrayBuffer){return{base64:true,data:this._arrayBufferToBase64(object)}}if(object instanceof Array){var base64Array=[];for(var i in object){base64Array[i]=this._convertBuffersToBase64(object[i],newAncestors)}return base64Array}if(object instanceof Object){var base64Object={};for(var j in object){base64Object[j]=this._convertBuffersToBase64(object[j],newAncestors)}return base64Object}return object};SCTransport.prototype.parse=function(message){return JSON.parse(message)};SCTransport.prototype.stringify=function(object){return JSON.stringify(this._convertBuffersToBase64(object))};SCTransport.prototype.send=function(data){if(this.socket.readyState!=this.socket.OPEN){this._onClose(1005)}else{this.socket.send(data)}};SCTransport.prototype.sendObject=function(object){this.send(this.stringify(object))};module.exports.SCTransport=SCTransport},{"./response":7,querystring:3,"sc-emitter":14,ws:17}],10:[function(require,module,exports){"use strict";var errorMessage;errorMessage="An argument without append, prepend, "+"or detach methods was given to `List";function List(){if(arguments.length){return List.from(arguments)}}var ListPrototype;ListPrototype=List.prototype;List.of=function(){return List.from.call(this,arguments)};List.from=function(items){var list=new this,length,iterator,item;if(items&&(length=items.length)){iterator=-1;while(++iterator<length){item=items[iterator];if(item!==null&&item!==undefined){list.append(item)}}}return list};ListPrototype.head=null;ListPrototype.tail=null;ListPrototype.toArray=function(){var item=this.head,result=[];while(item){result.push(item);item=item.next}return result};ListPrototype.prepend=function(item){if(!item){return false}if(!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"#prepend`.")}var self,head;self=this;head=self.head;if(head){return head.prepend(item)}item.detach();item.list=self;self.head=item;return item};ListPrototype.append=function(item){if(!item){return false}if(!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"#append`.")}var self,head,tail;self=this;tail=self.tail;if(tail){return tail.append(item)}head=self.head;if(head){return head.append(item)}item.detach();item.list=self;self.head=item;return item};function ListItem(){}List.Item=ListItem;var ListItemPrototype=ListItem.prototype;ListItemPrototype.next=null;ListItemPrototype.prev=null;ListItemPrototype.list=null;ListItemPrototype.detach=function(){var self=this,list=self.list,prev=self.prev,next=self.next;if(!list){return self}if(list.tail===self){list.tail=prev}if(list.head===self){list.head=next}if(list.tail===list.head){list.tail=null}if(prev){prev.next=next}if(next){next.prev=prev}self.prev=self.next=self.list=null;return self};ListItemPrototype.prepend=function(item){if(!item||!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"Item#prepend`.")}var self=this,list=self.list,prev=self.prev;if(!list){return false}item.detach();if(prev){item.prev=prev;prev.next=item}item.next=self;item.list=list;self.prev=item;if(self===list.head){list.head=item}if(!list.tail){list.tail=self}return item};ListItemPrototype.append=function(item){if(!item||!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"Item#append`.")}var self=this,list=self.list,next=self.next;if(!list){return false}item.detach();if(next){item.next=next;next.prev=item}item.prev=self;item.list=list;self.next=item;if(self===list.tail||!list.tail){list.tail=item}return item};module.exports=List},{}],11:[function(require,module,exports){"use strict";module.exports=require("./_source/linked-list.js")},{"./_source/linked-list.js":10}],12:[function(require,module,exports){var SCEmitter=require("sc-emitter").SCEmitter;if(!Object.create){Object.create=require("./objectcreate")}var SCChannel=function(name,client){var self=this;SCEmitter.call(this);this.PENDING="pending";this.SUBSCRIBED="subscribed";this.UNSUBSCRIBED="unsubscribed";this.name=name;this.state=this.UNSUBSCRIBED;this.client=client};SCChannel.prototype=Object.create(SCEmitter.prototype);SCChannel.prototype.getState=function(){return this.state};SCChannel.prototype.subscribe=function(){this.client.subscribe(this.name)};SCChannel.prototype.unsubscribe=function(){this.client.unsubscribe(this.name)};SCChannel.prototype.isSubscribed=function(includePending){return this.client.isSubscribed(this.name,includePending)};SCChannel.prototype.publish=function(data,callback){this.client.publish(this.name,data,callback)};SCChannel.prototype.watch=function(handler){this.client.watch(this.name,handler)};SCChannel.prototype.unwatch=function(handler){this.client.unwatch(this.name,handler)};SCChannel.prototype.destroy=function(){this.client.destroyChannel(this.name)};module.exports.SCChannel=SCChannel},{"./objectcreate":13,"sc-emitter":14}],13:[function(require,module,exports){module.exports=require(6)},{"C:\\node\\sc\\node_modules\\socketcluster-client\\lib\\objectcreate.js":6}],14:[function(require,module,exports){var Emitter=require("component-emitter");if(!Object.create){Object.create=require("./objectcreate")}var SCEmitter=function(){Emitter.call(this)};SCEmitter.prototype=Object.create(Emitter.prototype);SCEmitter.prototype.emit=function(event){if(event=="error"&&this.domain){var err=arguments[1];if(!err){err=new Error('Uncaught, unspecified "error" event.')}err.domainEmitter=this;err.domain=this.domain;err.domainThrown=false;this.domain.emit("error",err)}Emitter.prototype.emit.apply(this,arguments)};module.exports.SCEmitter=SCEmitter},{"./objectcreate":16,"component-emitter":15}],15:[function(require,module,exports){module.exports=Emitter;
Esempio n. 20
0
function Popup (src, opts) {
  if (!(this instanceof Popup)) {
    return new Popup(src, opts);
  }

  // ensure an opts object exists
  opts = opts || {};

  // set the defaults if not provided
  for (var i in defaults) {
    if (!(i in opts)) {
      opts[i] = defaults[i];
    }
  }

  // we try to place it at the center of the current window
  // note: this "centering" logic borrowed from the Facebook JavaScript SDK
  if (opts.centered) {
    var screenX = null == window.screenX ? window.screenLeft : window.screenX;
    var screenY = null == window.screenY ? window.screenTop : window.screenY;
    var outerWidth = null == window.outerWidth
      ? document.documentElement.clientWidth : window.outerWidth;
    var outerHeight = null == window.outerHeight
      // 22= IE toolbar height
      ? (document.documentElement.clientHeight - 22) : window.outerHeight;

    if (null == opts.left)
      opts.left = parseInt(screenX + ((outerWidth - opts.width) / 2), 10);
    if (null == opts.top)
      opts.top = parseInt(screenY + ((outerHeight - opts.height) / 2.5), 10);
    delete opts.centered;
  }

  // interval to check for the window being closed
  var interval = 500;
  if (opts.interval) {
    interval = +opts.interval;
    delete opts.interval;
  }

  // turn the "opts" object into a window.open()-compatible String
  var optsStr = [];
  for (var key in opts) {
    optsStr.push(key + '=' + opts[key]);
  }
  optsStr = optsStr.join(',');

  // every popup window has a unique "name"
  var name = opts.name;

  // if a "name" was not provided, then create a random one
  if (!name) name = 'popup-' + (Math.random() * 0x10000000 | 0).toString(36);

  Emitter.call(this);
  this.name = name;
  this.opts = opts;
  this.optsStr = optsStr;

  // finally, open and return the popup window
  this.window = window.open(src, name, optsStr);
  this.focus();

  this.interval = setInterval(checkClose(this), interval);
}
Esempio n. 21
0
var SCSocket = function (id, server, socket, authData) {
  var self = this;
  
  Emitter.call(this);
  
  this._localEvents = {
    'open': 1,
    'subscribe': 1,
    'unsubscribe': 1,
    'disconnect': 1,
    '_disconnect': 1,
    'message': 1,
    'error': 1,
    'raw': 1
  };
  
  this._autoAckEvents = {
    '#publish': 1
  };
  
  this.id = id;
  this.server = server;
  this.socket = socket;
  this.state = this.OPEN;
  
  this.request = this.socket.upgradeReq;
  this.remoteAddress = this.request.remoteAddress;
  
  this._cid = 1;
  this._callbackMap = {};
  
  this._authToken = authData.token || null;
  
  this.socket.on('error', function (err) {
    Emitter.prototype.emit.call(self, 'error', err);
  });
  
  this.socket.on('close', function (code, data) {
    self._onSCClose(code, data);
  });
  
  this._pingIntervalTicker = setInterval(this._sendPing.bind(this), this.server.pingInterval);
  this._resetPongTimeout();
  
  // Receive incoming raw messages
  this.socket.on('message', function (message, flags) {
    self._resetPongTimeout();
    
    Emitter.prototype.emit.call(self, 'message', message);
    
    // If not pong, we need to parse the message.
    // If it is pong, we don't need to do anything since it has already 
    // served its purpose of resetting the pong timeout (see above).
    if (message != '2') {
      var obj = formatter.parse(message);
      
      if (obj == null) {
        var err = new Error('Received empty message');
        Emitter.prototype.emit.call(self, 'error', err);
        
      } else if (obj.event) {
        var eventName = obj.event;
        
        if (self._localEvents[eventName] == null) {
          var response = new Response(self, obj.cid);
          self.server.verifyInboundEvent(self, eventName, obj.data, function (err) {
            if (err) {
              response.error(err);
            } else {
              if (eventName == '#disconnect') {
                var eventData = obj.data || {};
                self._onSCClose(eventData.code, eventData.data);
              } else {
                if (self._autoAckEvents[eventName]) {
                  response.end();
                  Emitter.prototype.emit.call(self, eventName, obj.data);
                } else {
                  Emitter.prototype.emit.call(self, eventName, obj.data, response.callback.bind(response));
                }
              }
            }
          });
        }
      } else if (obj.rid != null) {
        // If incoming message is a response to a previously sent message
        var ret = self._callbackMap[obj.rid];
        if (ret) {
          clearTimeout(ret.timeout);
          delete self._callbackMap[obj.rid];
          ret.callback(obj.error, obj.data);
        }
      } else {
        // The last remaining case is to treat the message as raw
        Emitter.prototype.emit.call(self, 'raw', message);
      }
    }
  });
  
  // Emit socket status to client
  this.emit('#status', {
    id: this.id,
    isAuthenticated: !!this._authToken,
    authError: authData.error,
    pingTimeout: this.server.pingTimeout
  });
};
Esempio n. 22
0
function Cache(obj) {
  Emitter.call(this);
  this.cache = {};
}