!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.XMPP=e():"undefined"!=typeof global?global.XMPP=e():"undefined"!=typeof self&&(self.XMPP=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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { this.parts.bare = this.jid.slice(0, split); } else { this.parts.bare = this.jid; } return this.parts.bare; }, get resource() { if (this.parts.resource) { return this.parts.resource; } var split = this.jid.indexOf('/'); if (split > 0) { this.parts.resource = this.jid.slice(split + 1); } else { this.parts.resource = ''; } return this.parts.resource; }, get local() { if (this.parts.local) { return this.parts.local; } var bare = this.bare; var split = bare.indexOf('@'); if (split > 0) { this.parts.local = bare.slice(0, split); } else { this.parts.local = bare; } return this.parts.local; }, get domain() { if (this.parts.domain) { return this.parts.domain; } var bare = this.bare; var split = bare.indexOf('@'); if (split > 0) { this.parts.domain = bare.slice(split + 1); } else { this.parts.domain = bare; } return this.parts.domain; } }; module.exports = JID; },{}],4:[function(require,module,exports){ "use strict"; module.exports = function (client) { client.disco.addFeature('urn:xmpp:attention:0'); client.getAttention = function (jid, opts) { opts = opts || {}; opts.to = jid; opts.type = 'headline'; opts.attention = true; client.sendMessage(opts); }; client.on('message', function (msg) { if (msg._extensions._attention) { client.emit('attention', msg); } }); }; },{}],5:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/avatar'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:avatar:metadata+notify'); client.on('pubsubEvent', function (msg) { if (!msg.event._extensions.updated) return; if (msg.event.updated.node !== 'urn:xmpp:avatar:metadata') return; client.emit('avatar', { jid: msg.from, source: 'pubsub', avatars: msg.event.updated.published[0].avatars }); }); client.on('presence', function (pres) { if (pres.avatarId) { client.emit('avatar', { jid: pres.from, source: 'vcard', avatars: [{ id: pres.avatarId }] }); } }); client.publishAvatar = function (id, data, cb) { return this.publish('', 'urn:xmpp:avatar:data', { id: id, avatarData: data }, cb); }; client.useAvatars = function (info, cb) { return this.publish('', 'urn:xmpp:avatar:metadata', { id: 'current', avatars: info }, cb); }; client.getAvatar = function (jid, id, cb) { return this.getItem(jid, 'urn:xmpp:avatar:data', id, cb); }; }; },{"../stanza/avatar":30}],6:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/bookmarks'); module.exports = function (client) { client.getBookmarks = function (cb) { return this.getPrivateData({bookmarks: {}}, cb); }; client.setBookmarks = function (opts, cb) { return this.setPrivateData({bookmarks: opts}, cb); }; }; },{"../stanza/bookmarks":32}],7:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/carbons'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:carbons:2'); client.enableCarbons = function (cb) { return this.sendIq({ type: 'set', enableCarbons: true }, cb); }; client.disableCarbons = function (cb) { return this.sendIq({ type: 'set', disableCarbons: true }, cb); }; client.on('message', function (msg) { if (msg._extensions.carbonSent) { return client.emit('carbon:sent', msg); } if (msg._extensions.carbonReceived) { return client.emit('carbon:received', msg); } }); }; },{"../stanza/carbons":34}],8:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/chatstates'); module.exports = function (client) { client.disco.addFeature('http://jabber.org/protocol/chatstates'); client.on('message', function (msg) { if (msg.chatState) { client.emit('chatState', { to: msg.to, from: msg.from, chatState: msg.chatState }); } }); }; },{"../stanza/chatstates":35}],9:[function(require,module,exports){ "use strict"; module.exports = function (client) { client.disco.addFeature('urn:xmpp:message-correct:0'); client.on('message', function (msg) { if (msg.replace) { client.emit('replace', msg); client.emit('replace:' + msg.id, msg); } }); }; },{}],10:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/delayed'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:delay'); }; },{"../stanza/delayed":37}],11:[function(require,module,exports){ /*global unescape, escape */ "use strict"; var _ = require('underscore'); var crypto = require('crypto'); require('../stanza/disco'); require('../stanza/caps'); var UTF8 = { encode: function (s) { return unescape(encodeURIComponent(s)); }, decode: function (s) { return decodeURIComponent(escape(s)); } }; function generateVerString(info, hash) { var S = ''; var features = info.features.sort(); var identities = []; var formTypes = {}; var formOrder = []; _.forEach(info.identities, function (identity) { identities.push([ identity.category || '', identity.type || '', identity.lang || '', identity.name || '' ].join('/')); }); var idLen = identities.length; var featureLen = features.length; identities = _.unique(identities, true); features = _.unique(features, true); if (featureLen != features.length || idLen != identities.length) { return false; } S += identities.join('<') + '<'; S += features.join('<') + '<'; var illFormed = false; _.forEach(info.extensions, function (ext) { var fields = ext.fields; for (var i = 0, len = fields.length; i < len; i++) { if (fields[i].name == 'FORM_TYPE' && fields[i].type == 'hidden') { var name = fields[i].value; if (formTypes[name]) { illFormed = true; return; } formTypes[name] = ext; formOrder.push(name); return; } } }); if (illFormed) { return false; } formOrder.sort(); _.forEach(formOrder, function (name) { var ext = formTypes[name]; var fields = {}; var fieldOrder = []; S += '<' + name; _.forEach(ext.fields, function (field) { var fieldName = field.name; if (fieldName != 'FORM_TYPE') { var values = field.value || ''; if (typeof values != 'object') { values = values.split('\n'); } fields[fieldName] = values.sort(); fieldOrder.push(fieldName); } }); fieldOrder.sort(); _.forEach(fieldOrder, function (fieldName) { S += '<' + fieldName; _.forEach(fields[fieldName], function (val) { S += '<' + val; }); }); }); if (hash === 'sha-1') { hash = 'sha1'; } var ver = crypto.createHash(hash).update(UTF8.encode(S)).digest('base64'); var padding = 4 - ver.length % 4; if (padding === 4) { padding = 0; } for (var i = 0; i < padding; i++) { ver += '='; } return ver; } function verifyVerString(info, hash, check) { if (hash === 'sha-1') { hash = 'sha1'; } var computed = generateVerString(info, hash); return computed && computed == check; } function Disco(client) { this.features = {}; this.identities = {}; this.extensions = {}; this.items = {}; this.caps = {}; } Disco.prototype = { constructor: { value: Disco }, addFeature: function (feature, node) { node = node || ''; if (!this.features[node]) { this.features[node] = []; } this.features[node].push(feature); }, addIdentity: function (identity, node) { node = node || ''; if (!this.identities[node]) { this.identities[node] = []; } this.identities[node].push(identity); }, addItem: function (item, node) { node = node || ''; if (!this.items[node]) { this.items[node] = []; } this.items[node].push(item); }, addExtension: function (form, node) { node = node || ''; if (!this.extensions[node]) { this.extensions[node] = []; } this.extensions[node].push(form); } }; module.exports = function (client) { client.disco = new Disco(client); client.disco.addFeature('http://jabber.org/protocol/disco#info'); client.disco.addIdentity({ category: 'client', type: 'web' }); client.getDiscoInfo = function (jid, node, cb) { return this.sendIq({ to: jid, type: 'get', discoInfo: { node: node } }, cb); }; client.getDiscoItems = function (jid, node, cb) { return this.sendIq({ to: jid, type: 'get', discoItems: { node: node } }, cb); }; client.updateCaps = function () { var node = this.config.capsNode || 'https://stanza.io'; var data = JSON.parse(JSON.stringify({ identities: this.disco.identities[''], features: this.disco.features[''], extensions: this.disco.extensions[''] })); var ver = generateVerString(data, 'sha-1'); this.disco.caps = { node: node, hash: 'sha-1', ver: ver }; node = node + '#' + ver; this.disco.features[node] = data.features; this.disco.identities[node] = data.identities; this.disco.extensions[node] = data.extensions; return client.getCurrentCaps(); }; client.getCurrentCaps = function () { var caps = client.disco.caps; if (!caps.ver) { return {ver: null, discoInfo: null}; } var node = caps.node + '#' + caps.ver; return { ver: caps.ver, discoInfo: { identities: client.disco.identities[node], features: client.disco.features[node], extensions: client.disco.extensions[node] } }; }; client.on('presence', function (pres) { if (pres._extensions.caps) { client.emit('disco:caps', pres); } }); client.on('iq:get:discoInfo', function (iq) { var node = iq.discoInfo.node; var reportedNode = iq.discoInfo.node; if (node === client.disco.caps.node + '#' + client.disco.caps.ver) { reportedNode = node; node = ''; } client.sendIq(iq.resultReply({ discoInfo: { node: reportedNode, identities: client.disco.identities[node] || [], features: client.disco.features[node] || [], extensions: client.disco.extensions[node] || [] } })); }); client.on('iq:get:discoItems', function (iq) { var node = iq.discoInfo.node; client.sendIq(iq.resultReply({ discoItems: { node: node, items: client.disco.items[node] || [] } })); }); client.verifyVerString = verifyVerString; client.generateVerString = generateVerString; }; },{"../stanza/caps":33,"../stanza/disco":38,"crypto":117,"underscore":167}],12:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/extdisco'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:extdisco:1'); client.getServices = function (jid, type, cb) { return this.sendIq({ type: 'get', to: jid, services: { type: type } }, cb); }; client.getServiceCredentials = function (jid, host, cb) { return this.sendIq({ type: 'get', to: jid, credentials: { service: { host: host } } }, cb); }; }; },{"../stanza/extdisco":40}],13:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/forwarded'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:forward:0'); }; },{"../stanza/forwarded":41}],14:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/geoloc'); module.exports = function (client) { client.disco.addFeature('http://jabber.org/protocol/geoloc'); client.disco.addFeature('http://jabber.org/protocol/geoloc+notify'); client.on('pubsubEvent', function (msg) { if (!msg.event._extensions.updated) return; if (msg.event.updated.node !== 'http://jabber.org/protocol/geoloc') return; client.emit('geoloc', { jid: msg.from, geoloc: msg.event.updated.published[0].geoloc }); }); client.publishGeoLoc = function (data, cb) { return this.publish('', 'http://jabber.org/protocol/geoloc', { geoloc: data }, cb); }; }; },{"../stanza/geoloc":42}],15:[function(require,module,exports){ "use strict"; module.exports = function (client) { client.disco.addFeature('urn:xmpp:hashes:1'); client.disco.addFeature('urn:xmpp:hash-function-text-names:md5'); client.disco.addFeature('urn:xmpp:hash-function-text-names:sha-1'); client.disco.addFeature('urn:xmpp:hash-function-text-names:sha-256'); }; },{}],16:[function(require,module,exports){ "use strict"; module.exports = function (client) { client.disco.addFeature('urn:xmpp:idle:1'); }; },{}],17:[function(require,module,exports){ "use strict"; require('../stanza/visibility'); module.exports = function (client) { client.goInvisible = function (cb) { return this.sendIq({ type: 'set', invisible: true }); }; client.goVisible = function (cb) { return this.sendIq({ type: 'set', visible: true }); }; }; },{"../stanza/visibility":67}],18:[function(require,module,exports){ "use strict"; var Jingle = require('jingle'); var stanza = require('../stanza/jingle'); var rtp = require('../stanza/rtp'); var ice = require('../stanza/iceUdp'); module.exports = function (client) { var jingle = client.jingle = new Jingle(); jingle.capabilities.forEach(function (cap) { client.disco.addFeature(cap); }); var mappedEvents = [ 'outgoing', 'incoming', 'accepted', 'terminated', 'ringing', 'mute', 'unmute', 'hold', 'resumed' ]; mappedEvents.forEach(function (event) { jingle.on(event, function (session, arg1) { client.emit('jingle:' + event, session, arg1); }); }); jingle.on('localStream', function (stream) { client.emit('jingle:localstream:added', stream); }); jingle.on('localStreamStopped', function () { client.emit('jingle:localstream:removed'); }); jingle.on('peerStreamAdded', function (session) { client.emit('jingle:remotestream:added', session); }); jingle.on('peerStreamRemoved', function (session) { client.emit('jingle:remotestream:removed', session); }); jingle.on('send', function (data) { client.sendIq(data); }); client.on('iq:set:jingle', function (data) { data = data.toJSON(); jingle.process(data); }); client.on('unavailable', function (pres) { var peer = pres.from.full; jingle.endPeerSessions(peer); }); client.call = function (peer) { peer = peer.full || peer; var sess = jingle.createMediaSession(peer); client.sendPresence({to: peer}); sess.start(); return sess; }; client.discoverICEServers = function (cb) { return this.getServices(client.config.server).then(function (res) { var services = res.services.services; var discovered = []; for (var i = 0; i < services.length; i++) { var service = services[i]; var ice = {}; if (service.type === 'stun') { ice.url = 'stun:' + service.host; if (service.port) { ice.url += ':' + service.port; } discovered.push(ice); client.jingle.addICEServer(ice); } else if (service.type === 'turn') { ice.url = 'turn:' + service.host; if (service.port) { ice.url += ':' + service.port; } if (service.transport && service.transport !== 'udp') { ice.url += '?transport=' + service.transport; } if (service.username) { ice.username = service.username; } if (service.password) { ice.credential = service.password; } discovered.push(ice); client.jingle.addICEServer(ice); } } return discovered; }).nodeify(cb); }; }; },{"../stanza/iceUdp":43,"../stanza/jingle":45,"../stanza/rtp":56,"jingle":125}],19:[function(require,module,exports){ "use strict"; var stanza = require('../stanza/json'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:json:tmp'); }; },{"../stanza/json":46}],20:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/mam'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:mam:tmp'); client.getHistory = function (opts, cb) { var self = this; var queryid = this.nextId(); opts = opts || {}; opts.queryid = queryid; var mamResults = []; this.on('mam:' + queryid, 'session', function (msg) { mamResults.push(msg); }); return this.sendIq({ type: 'get', id: queryid, mamQuery: opts }).then(function (resp) { self.off('mam:' + queryid); resp.mamQuery.results = mamResults; return resp; }).nodeify(cb); }; client.getHistoryPreferences = function (cb) { return this.sendIq({ type: 'get', mamPrefs: {} }, cb); }; client.setHistoryPreferences = function (opts, cb) { return this.sendIq({ type: 'set', mamPrefs: opts }, cb); }; client.on('message', function (msg) { if (msg._extensions.mam) { client.emit('mam:' + msg.mam.queryid, msg); } }); }; },{"../stanza/mam":47}],21:[function(require,module,exports){ "use strict"; var JID = require('../jid'); require('../stanza/muc'); module.exports = function (client) { client.disco.addFeature('', 'jabber:x:conference'); client.on('message', function (msg) { if (msg._extensions.muc) { if (msg._extensions.muc._extensions.invite) { client.emit('muc:invite', { from: msg.muc.invite.from, room: msg.from, reason: msg.muc.invite.reason, password: msg.muc.password, thread: msg.muc.invite.thread }); } if (msg._extensions.muc._extensions.destroyed) { client.emit('muc:destroyed', { room: msg.from, newRoom: msg.muc.destroyed.jid, reason: msg.muc.destroyed.reason, password: msg.muc.password }); } if (msg._extensions.muc._extensions.decline) { client.emit('muc:declined', { room: msg.from, from: msg.muc.decline.from, reason: msg.muc.decline.reason }); } } else if (msg._extensions.mucInvite) { client.emit('muc:invite', { from: msg.from, room: msg.mucInvite.jid, reason: msg.mucInvite.reason, password: msg.mucInvite.password, thread: msg.mucInvite.thread }); } if (msg.type === 'groupchat' && msg.subject) { client.emit('groupchat:subject', msg); } }); client.on('presence', function (pres) { if (pres._extensions.muc) { if (pres.type == 'error') { client.emit('muc:error', pres); } else if (pres.type == 'unavailable') { client.emit('muc:leave', pres); } else { client.emit('muc:join', pres); } } }); client.joinRoom = function (room, nick, opts) { opts = opts || {}; opts.to = room + '/' + nick; opts.caps = this.disco.caps; opts.joinMuc = opts.joinMuc || {}; this.sendPresence(opts); }; client.leaveRoom = function (room, nick, opts) { opts = opts || {}; opts.to = room + '/' + nick; opts.type = 'unavailable'; this.sendPresence(opts); }; client.ban = function (room, jid, reason, cb) { client.setRoomAffiliation(room, jid, 'outcast', reason, cb); }; client.kick = function (room, nick, reason, cb) { client.setRoomRole(room, nick, 'none', reason, cb); }; client.invite = function (room, opts) { client.sendMessage({ to: room, muc: { invites: opts } }); }; client.directInvite = function (room, opts) { opts.jid = room; client.sendMessage({ to: opts.to, mucInvite: opts }); }; client.declineInvite = function (room, sender, reason) { client.sendMessage({ to: room, muc: { decline: { to: sender, reason: reason } } }); }; client.changeNick = function (room, nick) { client.sendPresence({ to: (new JID(room)).bare + '/' + nick }); }; client.setSubject = function (room, subject) { client.sendMessage({ to: room, type: 'groupchat', subject: subject }); }; client.discoverReservedNick = function (room, cb) { client.getDiscoInfo(room, 'x-roomuser-item', function (err, res) { if (err) return cb(err); var ident = res.discoInfo.identities[0] || {}; cb(null, ident.name); }); }; client.requestRoomVoice = function (room) { client.sendMessage({ to: room, form: { fields: [ { name: 'FORM_TYPE', value: 'http://jabber.org/protocol/muc#request' }, { name: 'muc#role', type: 'text-single', value: 'participant' } ] } }); }; client.setRoomAffiliation = function (room, jid, affiliation, reason, cb) { return this.sendIq({ type: 'set', to: room, mucAdmin: { jid: jid, affiliation: affiliation, reason: reason } }, cb); }; client.setRoomRole = function (room, nick, role, reason, cb) { return this.sendIq({ type: 'set', to: room, mucAdmin: { nick: nick, role: role, reason: reason } }, cb); }; client.getRoomMembers = function (room, opts, cb) { return this.sendIq({ type: 'get', to: room, mucAdmin: opts }, cb); }; client.getRoomConfig = function (jid, cb) { return this.sendIq({ to: jid, type: 'get', mucOwner: {} }, cb); }; client.configureRoom = function (jid, form, cb) { if (!form.type) form.type = 'submit'; return this.sendIq({ to: jid, type: 'set', mucOwner: { form: form } }, cb); }; }; },{"../jid":3,"../stanza/muc":49}],22:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/oob'); module.exports = function (client) { client.disco.addFeature('jabber:x:oob'); }; },{"../stanza/oob":50}],23:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/private'); module.exports = function (client) { client.getPrivateData = function (opts, cb) { return this.sendIq({ type: 'get', privateStorage: opts }, cb); }; client.setPrivateData = function (opts, cb) { return this.sendIq({ type: 'set', privateStorage: opts }, cb); }; }; },{"../stanza/private":52}],24:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/pubsub'); module.exports = function (client) { client.on('message', function (msg) { if (msg._extensions.event) { client.emit('pubsubEvent', msg); } }); client.subscribeToNode = function (jid, opts, cb) { return this.sendIq({ type: 'set', to: jid, pubsub: { subscribe: { node: opts.node, jid: opts.jid || client.jid } } }, cb); }; client.unsubscribeFromNode = function (jid, opts, cb) { return this.sendIq({ type: 'set', to: jid, pubsub: { unsubscribe: { node: opts.node, jid: opts.jid || client.jid.split('/')[0] } } }, cb); }; client.publish = function (jid, node, item, cb) { return this.sendIq({ type: 'set', to: jid, pubsub: { publish: { node: node, item: item } } }, cb); }; client.getItem = function (jid, node, id, cb) { return this.sendIq({ type: 'get', to: jid, pubsub: { retrieve: { node: node, item: id } } }, cb); }; client.getItems = function (jid, node, opts, cb) { opts = opts || {}; opts.node = node; return this.sendIq({ type: 'get', to: jid, pubsub: { retrieve: { node: node, max: opts.max }, rsm: opts.rsm } }, cb); }; client.retract = function (jid, node, id, notify, cb) { return this.sendIq({ type: 'set', to: jid, pubsub: { retract: { node: node, notify: notify, id: id } } }, cb); }; client.purgeNode = function (jid, node, cb) { return this.sendIq({ type: 'set', to: jid, pubsubOwner: { purge: node } }, cb); }; client.deleteNode = function (jid, node, cb) { return this.sendIq({ type: 'set', to: jid, pubsubOwner: { del: node } }, cb); }; client.createNode = function (jid, node, config, cb) { var cmd = { type: 'set', to: jid, pubsubOwner: { create: node } }; if (config) { cmd.pubsubOwner.config = {form: config}; } return this.sendIq(cmd, cb); }; }; },{"../stanza/pubsub":53}],25:[function(require,module,exports){ "use strict"; module.exports = function (client) { client.disco.addFeature('urn:xmpp:receipts'); client.on('message', function (msg) { var ackTypes = { normal: true, chat: true, headline: true }; if (ackTypes[msg.type] && msg.requestReceipt && !msg.receipt) { client.sendMessage({ to: msg.from, receipt: msg.id, id: msg.id }); } if (msg.receipt) { client.emit('receipt', msg); client.emit('receipt:' + msg.receipt); } }); }; },{}],26:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/time'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:time'); client.getTime = function (jid, cb) { return this.sendIq({ to: jid, type: 'get', time: true }, cb); }; client.on('iq:get:time', function (iq) { var time = new Date(); client.sendIq(iq.resultReply({ time: { utc: time, tzo: time.getTimezoneOffset() } })); }); }; },{"../stanza/time":63}],27:[function(require,module,exports){ "use strict"; var stanzas = require('../stanza/vcard'); module.exports = function (client) { client.disco.addFeature('vcard-temp'); client.getVCard = function (jid, cb) { return this.sendIq({ to: jid, type: 'get', vCardTemp: {} }, cb); }; client.publishVCard = function (vcard, cb) { return this.sendIq({ type: 'set', vCardTemp: vcard }, cb); }; }; },{"../stanza/vcard":65}],28:[function(require,module,exports){ "use strict"; require('../stanza/version'); module.exports = function (client) { client.disco.addFeature('jabber:iq:version'); client.on('iq:get:version', function (iq) { client.sendIq(iq.resultReply({ version: client.config.version || { name: 'stanza.io' } })); }); client.getSoftwareVersion = function (jid, cb) { return this.sendIq({ to: jid, type: 'get', version: {} }, cb); }; }; },{"../stanza/version":66}],29:[function(require,module,exports){ "use strict"; var SM = require('./stanza/sm'); var MAX_SEQ = Math.pow(2, 32); function mod(v, n) { return ((v % n) + n) % n; } function StreamManagement(conn) { this.conn = conn; this.id = false; this.allowResume = true; this.started = false; this.lastAck = 0; this.handled = 0; this.windowSize = 1; this.unacked = []; this.pendingAck = false; } StreamManagement.prototype = { constructor: { value: StreamManagement }, enable: function () { var enable = new SM.Enable(); enable.resume = this.allowResume; this.conn.send(enable); this.handled = 0; this.started = true; }, resume: function () { var resume = new SM.Resume({ h: this.handled, previd: this.id }); this.conn.send(resume); this.started = true; }, enabled: function (resp) { this.id = resp.id; }, resumed: function (resp) { this.id = resp.id; if (resp.h) { this.process(resp, true); } }, failed: function (resp) { this.started = false; this.id = false; this.lastAck = 0; this.handled = 0; this.unacked = []; }, ack: function () { this.conn.send(new SM.Ack({ h: this.handled })); }, request: function () { this.pendingAck = true; this.conn.send(new SM.Request()); }, process: function (ack, resend) { var self = this; var numAcked = mod(ack.h - this.lastAck, MAX_SEQ); this.pendingAck = false; for (var i = 0; i < numAcked && this.unacked.length > 0; i++) { this.conn.emit('stanza:acked', this.unacked.shift()); } this.lastAck = ack.h; if (resend) { var resendUnacked = this.unacked; this.unacked = []; resendUnacked.forEach(function (stanza) { self.conn.send(stanza); }); } if (this.unacked.length >= this.windowSize) { this.request(); } }, track: function (stanza) { var name = stanza._name; var acceptable = { message: true, presence: true, iq: true }; if (this.started && acceptable[name]) { this.unacked.push(stanza); if (!this.pendingAck && this.unacked.length >= this.windowSize) { this.request(); } } }, handle: function (stanza) { if (this.started) { this.handled = mod(this.handled + 1, MAX_SEQ); } } }; module.exports = StreamManagement; },{"./stanza/sm":59}],30:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var Item = require('./pubsub').Item; var EventItem = require('./pubsub').EventItem; var Avatar = module.exports = stanza.define({ name: 'avatar', namespace: 'urn:xmpp:avatar:metadata', element: 'info', fields: { id: stanza.attribute('id'), bytes: stanza.attribute('bytes'), height: stanza.attribute('height'), width: stanza.attribute('width'), type: stanza.attribute('type', 'image/png'), url: stanza.attribute('url') } }); var avatars = { get: function () { var metadata = stanza.find(this.xml, 'urn:xmpp:avatar:metadata', 'metadata'); var results = []; if (metadata.length) { var avatars = stanza.find(metadata[0], 'urn:xmpp:avatar:metadata', 'info'); _.forEach(avatars, function (info) { results.push(new Avatar({}, info)); }); } return results; }, set: function (value) { var metadata = stanza.findOrCreate(this.xml, 'urn:xmpp:avatar:metadata', 'metadata'); stanza.setAttribute(metadata, 'xmlns', 'urn:xmpp:avatar:metadata'); _.forEach(value, function (info) { var avatar = new Avatar(info); metadata.appendChild(avatar.xml); }); } }; stanza.add(Item, 'avatars', avatars); stanza.add(EventItem, 'avatars', avatars); stanza.add(Item, 'avatarData', stanza.subText('urn:xmpp:avatar:data', 'data')); stanza.add(EventItem, 'avatarData', stanza.subText('urn:xmpp:avatar:data', 'data')); },{"./pubsub":53,"jxt":147,"underscore":167}],31:[function(require,module,exports){ var stanza = require('jxt'); var Iq = require('./iq'); var StreamFeatures = require('./streamFeatures'); var util = require('./util'); var NS = 'urn:ietf:params:xml:ns:xmpp-bind'; var Bind = module.exports = stanza.define({ name: 'bind', namespace: NS, element: 'bind', fields: { resource: stanza.subText(NS, 'resource'), jid: util.jidSub(NS, 'jid') } }); stanza.extend(Iq, Bind); stanza.extend(StreamFeatures, Bind); },{"./iq":44,"./streamFeatures":62,"./util":64,"jxt":147}],32:[function(require,module,exports){ var stanza = require('jxt'); var util = require('./util'); var PrivateStorage = require('./private'); var Conference = stanza.define({ name: 'conference', namespace: 'storage:bookmarks', element: 'conference', fields: { name: stanza.attribute('name'), autoJoin: stanza.boolAttribute('autojoin'), jid: util.jidAttribute('jid'), nick: stanza.subText('storage:bookmarks', 'nick') } }); var Bookmarks = module.exports = stanza.define({ name: 'bookmarks', namespace: 'storage:bookmarks', element: 'storage' }); stanza.extend(PrivateStorage, Bookmarks); stanza.extend(Bookmarks, Conference, 'conferences'); },{"./private":52,"./util":64,"jxt":147}],33:[function(require,module,exports){ var stanza = require('jxt'); var Presence = require('./presence'); var StreamFeatures = require('./streamFeatures'); var Caps = module.exports = stanza.define({ name: 'caps', namespace: 'http://jabber.org/protocol/caps', element: 'c', fields: { ver: stanza.attribute('ver'), node: stanza.attribute('node'), hash: stanza.attribute('hash'), ext: stanza.attribute('ext') } }); stanza.extend(Presence, Caps); stanza.extend(StreamFeatures, Caps); },{"./presence":51,"./streamFeatures":62,"jxt":147}],34:[function(require,module,exports){ var stanza = require('jxt'); var Message = require('./message'); var Iq = require('./iq'); var Forwarded = require('./forwarded'); exports.Sent = stanza.define({ name: 'carbonSent', eventName: 'carbon:sent', namespace: 'urn:xmpp:carbons:2', element: 'sent' }); exports.Received = stanza.define({ name: 'carbonReceived', eventName: 'carbon:received', namespace: 'urn:xmpp:carbons:2', element: 'received' }); exports.Private = stanza.define({ name: 'carbonPrivate', eventName: 'carbon:private', namespace: 'urn:xmpp:carbons:2', element: 'private' }); exports.Enable = stanza.define({ name: 'enableCarbons', namespace: 'urn:xmpp:carbons:2', element: 'enable' }); exports.Disable = stanza.define({ name: 'disableCarbons', namespace: 'urn:xmpp:carbons:2', element: 'disable' }); stanza.extend(exports.Sent, Forwarded); stanza.extend(exports.Received, Forwarded); stanza.extend(Message, exports.Sent); stanza.extend(Message, exports.Received); stanza.extend(Message, exports.Private); stanza.extend(Iq, exports.Enable); stanza.extend(Iq, exports.Disable); },{"./forwarded":41,"./iq":44,"./message":48,"jxt":147}],35:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var Message = require('./message'); var NS = 'http://jabber.org/protocol/chatstates'; var Active = stanza.define({ name: 'chatStateActive', eventName: 'chat:active', namespace: NS, element: 'active' }); var Composing = stanza.define({ name: 'chatStateComposing', eventName: 'chat:composing', namespace: NS, element: 'composing' }); var Paused = stanza.define({ name: 'chatStatePaused', eventName: 'chat:paused', namespace: NS, element: 'paused' }); var Inactive = stanza.define({ name: 'chatStateInactive', eventName: 'chat:inactive', namespace: NS, element: 'inactive' }); var Gone = stanza.define({ name: 'chatStateGone', eventName: 'chat:gone', namespace: NS, element: 'gone' }); stanza.extend(Message, Active); stanza.extend(Message, Composing); stanza.extend(Message, Paused); stanza.extend(Message, Inactive); stanza.extend(Message, Gone); stanza.add(Message, 'chatState', { get: function () { var self = this; var states = ['Active', 'Composing', 'Paused', 'Inactive', 'Gone']; for (var i = 0; i < states.length; i++) { if (self._extensions['chatState' + states[i]]) { return states[i].toLowerCase(); } } return ''; }, set: function (value) { var self = this; var states = ['Active', 'Composing', 'Paused', 'Inactive', 'Gone']; states.forEach(function (state) { if (self._extensions['chatState' + state]) { self.xml.removeChild(self._extensions['chatState' + state].xml); delete self._extensions['chatState' + state]; } }); if (value) { this['chatState' + value.charAt(0).toUpperCase() + value.slice(1)]; } } }); },{"./message":48,"jxt":147}],36:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var Message = require('./message'); exports.DataForm = stanza.define({ name: 'form', namespace: 'jabber:x:data', element: 'x', fields: { title: stanza.subText('jabber:x:data', 'title'), instructions: stanza.multiSubText('jabber:x:data', 'instructions'), type: stanza.attribute('type', 'form') } }); exports.Field = stanza.define({ name: '_field', namespace: 'jabber:x:data', element: 'field', init: function (data) { this._type = (data || {}).type || this.type; }, fields: { type: { get: function () { return stanza.getAttribute(this.xml, 'type', 'text-single'); }, set: function (value) { this._type = value; stanza.setAttribute(this.xml, 'type', value); } }, name: stanza.attribute('var'), desc: stanza.subText('desc'), required: stanza.boolSub('jabber:x:data', 'required'), label: stanza.attribute('label'), value: { get: function () { var vals = stanza.getMultiSubText(this.xml, this._NS, 'value'); if (this._type === 'boolean') { return vals[0] === '1' || vals[0] === 'true'; } if (vals.length > 1) { if (this._type === 'text-multi') { return vals.join('\n'); } return vals; } return vals[0]; }, set: function (value) { if (this._type === 'boolean') { stanza.setSubText(this.xml, this._NS, 'value', value ? '1' : '0'); } else { if (this._type === 'text-multi') { value = value.split('\n'); } stanza.setMultiSubText(this.xml, this._NS, 'value', value); } } }, options: { get: function () { var self = this; return stanza.getMultiSubText(this.xml, this._NS, 'option', function (sub) { return stanza.getSubText(sub, self._NS, 'value'); }); }, set: function (value) { var self = this; stanza.setMultiSubText(this.xml, this._NS, 'option', value, function (val) { var opt = document.createElementNS(self._NS, 'option'); var value = document.createElementNS(self._NS, 'value'); opt.appendChild(value); value.textContent = val; self.xml.appendChild(opt); }); } } } }); stanza.extend(Message, exports.DataForm); stanza.extend(exports.DataForm, exports.Field, 'fields'); },{"./message":48,"./util":64,"jxt":147,"underscore":167}],37:[function(require,module,exports){ var stanza = require('jxt'); var Message = require('./message'); var Presence = require('./presence'); var util = require('./util'); var DelayedDelivery = module.exports = stanza.define({ name: 'delay', namespace: 'urn:xmpp:delay', element: 'delay', fields: { from: util.jidAttribute('from'), stamp: stanza.dateAttribute('stamp'), reason: stanza.text() } }); stanza.extend(Message, DelayedDelivery); stanza.extend(Presence, DelayedDelivery); },{"./message":48,"./presence":51,"./util":64,"jxt":147}],38:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var JID = require('../jid'); var Iq = require('./iq'); var RSM = require('./rsm'); var DataForm = require('./dataforms').DataForm; exports.DiscoInfo = stanza.define({ name: 'discoInfo', namespace: 'http://jabber.org/protocol/disco#info', element: 'query', fields: { node: stanza.attribute('node'), identities: { get: function () { var result = []; var identities = stanza.find(this.xml, this._NS, 'identity'); identities.forEach(function (identity) { result.push({ category: stanza.getAttribute(identity, 'category'), type: stanza.getAttribute(identity, 'type'), lang: identity.getAttributeNS(stanza.XML_NS, 'lang'), name: stanza.getAttribute(identity, 'name') }); }); return result; }, set: function (values) { var self = this; var existing = stanza.find(this.xml, this._NS, 'identity'); existing.forEach(function (item) { self.xml.removeChild(item); }); values.forEach(function (value) { var identity = document.createElementNS(self._NS, 'identity'); stanza.setAttribute(identity, 'category', value.category); stanza.setAttribute(identity, 'type', value.type); stanza.setAttribute(identity, 'name', value.name); if (value.lang) { identity.setAttributeNS(stanza.XML_NS, 'lang', value.lang); } self.xml.appendChild(identity); }); } }, features: { get: function () { var result = []; var features = stanza.find(this.xml, this._NS, 'feature'); features.forEach(function (feature) { result.push(feature.getAttribute('var')); }); return result; }, set: function (values) { var self = this; var existing = stanza.find(this.xml, this._NS, 'feature'); existing.forEach(function (item) { self.xml.removeChild(item); }); values.forEach(function (value) { var feature = document.createElementNS(self._NS, 'feature'); feature.setAttribute('var', value); self.xml.appendChild(feature); }); } } } }); exports.DiscoItems = stanza.define({ name: 'discoItems', namespace: 'http://jabber.org/protocol/disco#items', element: 'query', fields: { node: stanza.attribute('node'), items: { get: function () { var result = []; var items = stanza.find(this.xml, this._NS, 'item'); items.forEach(function (item) { result.push({ jid: new JID(stanza.getAttribute(item, 'jid')), node: stanza.getAttribute(item, 'node'), name: stanza.getAttribute(item, 'name') }); }); return result; }, set: function (values) { var self = this; var existing = stanza.find(this.xml, this._NS, 'item'); existing.forEach(function (item) { self.xml.removeChild(item); }); values.forEach(function (value) { var item = document.createElementNS(self._NS, 'item'); stanza.setAttribute(item, 'jid', value.jid.toString()); stanza.setAttribute(item, 'node', value.node); stanza.setAttribute(item, 'name', value.name); self.xml.appendChild(item); }); } } } }); stanza.extend(Iq, exports.DiscoInfo); stanza.extend(Iq, exports.DiscoItems); stanza.extend(exports.DiscoItems, RSM); stanza.extend(exports.DiscoInfo, DataForm, 'extensions'); },{"../jid":3,"./dataforms":36,"./iq":44,"./rsm":55,"jxt":147,"underscore":167}],39:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var Message = require('./message'); var Presence = require('./presence'); var Iq = require('./iq'); var ERR_NS = 'urn:ietf:params:xml:ns:xmpp-stanzas'; var CONDITIONS = [ 'bad-request', 'conflict', 'feature-not-implemented', 'forbidden', 'gone', 'internal-server-error', 'item-not-found', 'jid-malformed', 'not-acceptable', 'not-allowed', 'not-authorized', 'payment-required', 'recipient-unavailable', 'redirect', 'registration-required', 'remote-server-not-found', 'remote-server-timeout', 'resource-constraint', 'service-unavailable', 'subscription-required', 'undefined-condition', 'unexpected-request' ]; var ErrorStanza = module.exports = stanza.define({ name: 'error', namespace: 'jabber:client', element: 'error', fields: { lang: { get: function () { return (this.parent || {}).lang || ''; } }, condition: { get: function () { var self = this; var result = []; CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, ERR_NS, condition); if (exists.length) { result.push(exists[0].tagName); } }); return result[0] || ''; }, set: function (value) { var self = this; CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, ERR_NS, condition); if (exists.length) { self.xml.removeChild(exists[0]); } }); if (value) { var condition = document.createElementNS(ERR_NS, value); condition.setAttribute('xmlns', ERR_NS); this.xml.appendChild(condition); } } }, gone: { get: function () { return stanza.getSubText(this.xml, ERR_NS, 'gone'); }, set: function (value) { this.condition = 'gone'; stanza.setSubText(this.xml, ERR_NS, 'gone', value); } }, redirect: { get: function () { return stanza.getSubText(this.xml, ERR_NS, 'redirect'); }, set: function (value) { this.condition = 'redirect'; stanza.setSubText(this.xml, ERR_NS, 'redirect', value); } }, code: stanza.attribute('code'), type: stanza.attribute('type'), by: util.jidAttribute('by'), $text: { get: function () { return stanza.getSubLangText(this.xml, ERR_NS, 'text', this.lang); } }, text: { get: function () { var text = this.$text; return text[this.lang] || ''; }, set: function (value) { stanza.setSubLangText(this.xml, ERR_NS, 'text', value, this.lang); } } } }); stanza.extend(Message, ErrorStanza); stanza.extend(Presence, ErrorStanza); stanza.extend(Iq, ErrorStanza); },{"./iq":44,"./message":48,"./presence":51,"./util":64,"jxt":147,"underscore":167}],40:[function(require,module,exports){ var stanza = require('jxt'); var Iq = require('./iq'); var DataForm = require('./dataforms').DataForm; var NS = 'urn:xmpp:extdisco:1'; var Services = exports.Services = stanza.define({ name: 'services', namespace: NS, element: 'services', fields: { type: stanza.attribute('type') } }); var Credentials = exports.Credentials = stanza.define({ name: 'credentials', namespace: NS, element: 'credentials' }); var Service = stanza.define({ name: 'service', namespace: NS, element: 'service', fields: { host: stanza.attribute('host'), port: stanza.attribute('port'), transport: stanza.attribute('transport'), type: stanza.attribute('type'), username: stanza.attribute('username'), password: stanza.attribute('password') } }); stanza.extend(Services, Service, 'services'); stanza.extend(Credentials, Service); stanza.extend(Service, DataForm); stanza.extend(Iq, Services); stanza.extend(Iq, Credentials); },{"./dataforms":36,"./iq":44,"jxt":147}],41:[function(require,module,exports){ var stanza = require('jxt'); var Message = require('./message'); var Presence = require('./presence'); var Iq = require('./iq'); var DelayedDelivery = require('./delayed'); var Forwarded = module.exports = stanza.define({ name: 'forwarded', eventName: 'forward', namespace: 'urn:xmpp:forward:0', element: 'forwarded' }); stanza.extend(Message, Forwarded); stanza.extend(Forwarded, Message); stanza.extend(Forwarded, Presence); stanza.extend(Forwarded, Iq); stanza.extend(Forwarded, DelayedDelivery); },{"./delayed":37,"./iq":44,"./message":48,"./presence":51,"jxt":147}],42:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var Item = require('./pubsub').Item; var EventItem = require('./pubsub').EventItem; var NS = 'http://jabber.org/protocol/geoloc'; var GeoLoc = module.exports = stanza.define({ name: 'geoloc', namespace: NS, element: 'geoloc', fields: { accuracy: stanza.numberSub(NS, 'accuracy', true), altitude: stanza.numberSub(NS, 'alt', true), area: stanza.subText(NS, 'area'), heading: stanza.numberSub(NS, 'bearing', true), bearing: stanza.numberSub(NS, 'bearing', true), building: stanza.subText(NS, 'building'), country: stanza.subText(NS, 'country'), countrycode: stanza.subText(NS, 'countrycode'), datum: stanza.subText(NS, 'datum'), description: stanza.subText(NS, 'description'), error: stanza.numberSub(NS, 'error', true), floor: stanza.subText(NS, 'floor'), latitude: stanza.numberSub(NS, 'lat', true), locality: stanza.subText(NS, 'locality'), longitude: stanza.numberSub(NS, 'lon', true), postalcode: stanza.subText(NS, 'postalcode'), region: stanza.subText(NS, 'region'), room: stanza.subText(NS, 'room'), speed: stanza.numberSub(NS, 'speed', true), street: stanza.subText(NS, 'street'), text: stanza.subText(NS, 'text'), timestamp: stanza.dateSub(NS, 'timestamp'), uri: stanza.subText(NS, 'uri') } }); stanza.extend(Item, GeoLoc); stanza.extend(EventItem, GeoLoc); },{"./pubsub":53,"jxt":147}],43:[function(require,module,exports){ var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var jingle = require('./jingle'); var NS = 'urn:xmpp:jingle:transports:ice-udp:1'; exports.ICEUDP = stanza.define({ name: '_iceUdp', namespace: NS, element: 'transport', fields: { transType: {value: 'iceUdp'}, pwd: stanza.attribute('pwd'), ufrag: stanza.attribute('ufrag') } }); exports.RemoteCandidate = stanza.define({ name: 'remoteCandidate', namespace: NS, element: 'remote-candidate', fields: { component: stanza.attribute('component'), ip: stanza.attribute('ip'), port: stanza.attribute('port') } }); exports.Candidate = stanza.define({ name: '_iceUdpCandidate', namespace: NS, element: 'candidate', fields: { component: stanza.attribute('component'), foundation: stanza.attribute('foundation'), generation: stanza.attribute('generation'), id: stanza.attribute('id'), ip: stanza.attribute('ip'), network: stanza.attribute('network'), port: stanza.attribute('port'), priority: stanza.attribute('priority'), protocol: stanza.attribute('protocol'), relAddr: stanza.attribute('rel-addr'), relPort: stanza.attribute('rel-port'), type: stanza.attribute('type') } }); exports.Fingerprint = stanza.define({ name: '_iceFingerprint', namespace: 'urn:xmpp:tmp:jingle:apps:dtls:0', element: 'fingerprint', fields: { hash: stanza.attribute('hash'), value: stanza.text(), required: stanza.boolAttribute('required') } }); stanza.extend(jingle.Content, exports.ICEUDP); stanza.extend(exports.ICEUDP, exports.Candidate, 'candidates'); stanza.extend(exports.ICEUDP, exports.RemoteCandidate); stanza.extend(exports.ICEUDP, exports.Fingerprint, 'fingerprints'); },{"./jingle":45,"./util":64,"jxt":147,"underscore":167}],44:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var util = require('./util'); var Iq = module.exports = stanza.define({ name: 'iq', namespace: 'jabber:client', element: 'iq', topLevel: true, fields: { lang: stanza.langAttribute(), id: stanza.attribute('id'), to: util.jidAttribute('to'), from: util.jidAttribute('from'), type: stanza.attribute('type') } }); Iq.prototype.resultReply = function (data) { data.to = this.from; data.id = this.id; data.type = 'result'; return new Iq(data); }; Iq.prototype.errorReply = function (data) { data.to = this.from; data.id = this.id; data.type = 'error'; return new Iq(data); }; },{"./util":64,"jxt":147}],45:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var Iq = require('./iq'); var ErrorStanza = require('./error'); var NS = 'urn:xmpp:jingle:1'; var ERRNS = 'urn:xmpp:jingle:errors:1'; var CONDITIONS = ['out-of-order', 'tie-break', 'unknown-session', 'unsupported-info']; var REASONS = [ 'alternative-session', 'busy', 'cancel', 'connectivity-error', 'decline', 'expired', 'failed-application', 'failed-transport', 'general-error', 'gone', 'incompatible-parameters', 'media-error', 'security-error', 'success', 'timeout', 'unsupported-applications', 'unsupported-transports' ]; exports.Jingle = stanza.define({ name: 'jingle', namespace: NS, element: 'jingle', fields: { action: stanza.attribute('action'), initiator: stanza.attribute('initiator'), responder: stanza.attribute('responder'), sid: stanza.attribute('sid') } }); exports.Content = stanza.define({ name: '_jingleContent', namespace: NS, element: 'content', fields: { creator: stanza.attribute('creator'), disposition: stanza.attribute('disposition', 'session'), name: stanza.attribute('name'), senders: stanza.attribute('senders', 'both'), description: { get: function () { var opts = ['_rtp']; for (var i = 0; i < opts.length; i++) { if (this._extensions[opts[i]]) { return this._extensions[opts[i]]; } } }, set: function (value) { var ext = '_' + value.descType; this[ext] = value; } }, transport: { get: function () { var opts = ['_iceUdp']; for (var i = 0; i < opts.length; i++) { if (this._extensions[opts[i]]) { return this._extensions[opts[i]]; } } }, set: function (value) { var ext = '_' + value.transType; this[ext] = value; } } } }); exports.Reason = stanza.define({ name: 'reason', namespace: NS, element: 'reason', fields: { condition: { get: function () { var self = this; var result = []; REASONS.forEach(function (condition) { var exists = stanza.find(self.xml, NS, condition); if (exists.length) { result.push(exists[0].tagName); } }); return result[0] || ''; }, set: function (value) { var self = this; REASONS.forEach(function (condition) { var exists = stanza.find(self.xml, NS, condition); if (exists.length) { self.xml.removeChild(exists[0]); } }); if (value) { var condition = document.createElementNS(NS, value); this.xml.appendChild(condition); } } }, alternativeSession: { get: function () { return stanza.getSubText(this.xml, NS, 'alternative-session'); }, set: function (value) { this.condition = 'alternative-session'; stanza.setSubText(this.xml, NS, 'alternative-session', value); } }, text: stanza.subText(NS, 'text') } }); stanza.add(ErrorStanza, 'jingleCondition', { get: function () { var self = this; var result = []; CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, ERRNS, condition); if (exists.length) { result.push(exists[0].tagName); } }); return result[0] || ''; }, set: function (value) { var self = this; CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, ERRNS, condition); if (exists.length) { self.xml.removeChild(exists[0]); } }); if (value) { var condition = document.createElementNS(ERRNS, value); this.xml.appendChild(condition); } } }); stanza.extend(Iq, exports.Jingle); stanza.extend(exports.Jingle, exports.Content, 'contents'); stanza.extend(exports.Jingle, exports.Reason); },{"./error":39,"./iq":44,"./util":64,"jxt":147,"underscore":167}],46:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var Message = require('./message'); var Item = require('./pubsub').Item; var EventItem = require('./pubsub').EventItem; var JSONExtension = module.exports = { get: function () { var data = stanza.getSubText(this.xml, 'urn:xmpp:json:0', 'json'); if (data) { return JSON.parse(data); } }, set: function (value) { value = JSON.stringify(value); if (value) { stanza.setSubText(this.xml, 'urn:xmpp:json:0', 'json', value); } } }; stanza.add(Message, 'json', JSONExtension); stanza.add(Item, 'json', JSONExtension); stanza.add(EventItem, 'json', JSONExtension); },{"./message":48,"./pubsub":53,"jxt":147}],47:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var util = require('./util'); var Message = require('./message'); var Iq = require('./iq'); var Forwarded = require('./forwarded'); var RSM = require('./rsm'); var JID = require('../jid'); exports.MAMQuery = stanza.define({ name: 'mamQuery', namespace: 'urn:xmpp:mam:tmp', element: 'query', fields: { queryid: stanza.attribute('queryid'), start: stanza.dateSub('urn:xmpp:mam:tmp', 'start'), end: stanza.dateSub('urn:xmpp:mam:tmp', 'end'), 'with': util.jidSub('urn:xmpp:mam:tmp', 'with') } }); exports.Result = stanza.define({ name: 'mam', eventName: 'mam:result', namespace: 'urn:xmpp:mam:tmp', element: 'result', fields: { queryid: stanza.attribute('queryid'), id: stanza.attribute('id') } }); exports.Archived = stanza.define({ name: 'mamArchived', namespace: 'urn:xmpp:mam:tmp', element: 'archived', fields: { by: util.jidAttribute('by'), id: stanza.attribute('id') } }); exports.Prefs = stanza.define({ name: 'mamPrefs', namespace: 'urn:xmpp:mam:tmp', element: 'prefs', fields: { defaultCondition: stanza.attribute('default'), always: { get: function () { var results = []; var container = stanza.find(this.xml, this._NS, 'always'); if (container.length === 0) { return results; } container = container[0]; var jids = stanza.getMultiSubText(container, this._NS, 'jid'); jids.forEach(function (jid) { results.push(new JID(jid.textContent)); }); return results; }, set: function (value) { if (value.length > 0) { var container = stanza.find(this.xml, this._NS, 'always'); stanza.setMultiSubText(container, this._NS, 'jid', value); } } }, never: { get: function () { var results = []; var container = stanza.find(this.xml, this._NS, 'always'); if (container.length === 0) { return results; } container = container[0]; var jids = stanza.getMultiSubText(container, this._NS, 'jid'); jids.forEach(function (jid) { results.push(new JID(jid.textContent)); }); return results; }, set: function (value) { if (value.length > 0) { var container = stanza.find(this.xml, this._NS, 'never'); stanza.setMultiSubText(container, this._NS, 'jid', value); } } } } }); stanza.extend(Message, exports.Archived, 'archived'); stanza.extend(Iq, exports.MAMQuery); stanza.extend(Iq, exports.Prefs); stanza.extend(Message, exports.Result); stanza.extend(exports.Result, Forwarded); stanza.extend(exports.MAMQuery, RSM); },{"../jid":3,"./forwarded":41,"./iq":44,"./message":48,"./rsm":55,"./util":64,"jxt":147}],48:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); module.exports = stanza.define({ name: 'message', namespace: 'jabber:client', element: 'message', topLevel: true, fields: { lang: stanza.langAttribute(), id: stanza.attribute('id'), to: util.jidAttribute('to'), from: util.jidAttribute('from'), type: stanza.attribute('type', 'normal'), thread: stanza.subText('jabber:client', 'thread'), parentThread: stanza.subAttribute('jabber:client', 'thread', 'parent'), subject: stanza.subText('jabber:client', 'subject'), $body: { get: function () { return stanza.getSubLangText(this.xml, this._NS, 'body', this.lang); } }, body: { get: function () { var bodies = this.$body; return bodies[this.lang] || ''; }, set: function (value) { stanza.setSubLangText(this.xml, this._NS, 'body', value, this.lang); } }, attention: stanza.boolSub('urn:xmpp:attention:0', 'attention'), replace: stanza.subAttribute('urn:xmpp:message-correct:0', 'replace', 'id'), requestReceipt: stanza.boolSub('urn:xmpp:receipts', 'request'), receipt: stanza.subAttribute('urn:xmpp:receipts', 'received', 'id') } }); },{"./util":64,"jxt":147,"underscore":167}],49:[function(require,module,exports){ 'use strict'; var stanza = require('jxt'); var Message = require('./message'); var Presence = require('./presence'); var Iq = require('./iq'); var DataForm = require('./dataforms').DataForm; var util = require('./util'); var NS = 'http://jabber.org/protocol/muc'; var USER_NS = NS + '#user'; var ADMIN_NS = NS + '#admin'; var OWNER_NS = NS + '#owner'; var proxy = function (child, field) { return { get: function () { if (this._extensions[child]) { return this[child][field]; } }, set: function (value) { this[child][field] = value; } }; }; var UserItem = stanza.define({ name: '_mucUserItem', namespace: USER_NS, element: 'item', fields: { affiliation: stanza.attribute('affiliation'), nick: stanza.attribute('nick'), jid: util.jidAttribute('jid'), role: stanza.attribute('role'), reason: stanza.subText(USER_NS, 'reason') } }); var UserActor = stanza.define({ name: '_mucUserActor', namespace: USER_NS, element: 'actor', fields: { nick: stanza.attribute('nick'), jid: util.jidAttribute('jid') } }); var Destroyed = stanza.define({ name: 'destroyed', namespace: USER_NS, element: 'destroy', fields: { jid: util.jidAttribute('jid'), reason: stanza.subText(USER_NS, 'reason') } }); var Invite = stanza.define({ name: 'invite', namespace: USER_NS, element: 'invite', fields: { to: util.jidAttribute('to'), from: util.jidAttribute('from'), reason: stanza.subText(USER_NS, 'reason'), thread: stanza.subAttribute(USER_NS, 'continue', 'thread'), 'continue': stanza.boolSub(USER_NS, 'continue') } }); var Decline = stanza.define({ name: 'decline', namespace: USER_NS, element: 'decline', fields: { to: util.jidAttribute('to'), from: util.jidAttribute('from'), reason: stanza.subText(USER_NS, 'reason') } }); var AdminItem = stanza.define({ name: '_mucAdminItem', namespace: ADMIN_NS, element: 'item', fields: { affiliation: stanza.attribute('affiliation'), nick: stanza.attribute('nick'), jid: util.jidAttribute('jid'), role: stanza.attribute('role'), reason: stanza.subText(ADMIN_NS, 'reason') } }); var AdminActor = stanza.define({ name: 'actor', namespace: USER_NS, element: 'actor', fields: { nick: stanza.attribute('nick'), jid: util.jidAttribute('jid') } }); var Destroy = stanza.define({ name: 'destroy', namespace: OWNER_NS, element: 'destroy', fields: { jid: util.jidAttribute('jid'), password: stanza.subText(OWNER_NS, 'password'), reason: stanza.subText(OWNER_NS, 'reason') } }); exports.MUC = stanza.define({ name: 'muc', namespace: USER_NS, element: 'x', fields: { affiliation: proxy('_mucUserItem', 'affiliation'), nick: proxy('_mucUserItem', 'nick'), jid: proxy('_mucUserItem', 'jid'), role: proxy('_mucUserItem', 'role'), actor: proxy('_mucUserItem', '_mucUserActor'), reason: proxy('_mucUserItem', 'reason'), password: stanza.subText(USER_NS, 'password'), codes: { get: function () { return stanza.getMultiSubText(this.xml, USER_NS, 'status', function (sub) { return stanza.getAttribute(sub, 'code'); }); }, set: function (value) { var self = this; stanza.setMultiSubText(this.xml, USER_NS, 'status', value, function (val) { var child = stanza.createElement(USER_NS, 'status', USER_NS); stanza.setAttribute(child, 'code', val); self.xml.appendChild(child); }); } } } }); exports.MUCAdmin = stanza.define({ name: 'mucAdmin', namespace: ADMIN_NS, element: 'query', fields: { affiliation: proxy('_mucAdminItem', 'affiliation'), nick: proxy('_mucAdminItem', 'nick'), jid: proxy('_mucAdminItem', 'jid'), role: proxy('_mucAdminItem', 'role'), actor: proxy('_mucAdminItem', '_mucAdminActor'), reason: proxy('_mucAdminItem', 'reason') } }); exports.MUCOwner = stanza.define({ name: 'mucOwner', namespace: OWNER_NS, element: 'query' }); exports.MUCJoin = stanza.define({ name: 'joinMuc', namespace: NS, element: 'x', fields: { password: stanza.subText(NS, 'password'), history: { get: function () { var result = {}; var hist = stanza.find(this.xml, this._NS, 'history'); if (!hist.length) { return {}; } hist = hist[0]; var maxchars = hist.getAttribute('maxchars') || ''; var maxstanzas = hist.getAttribute('maxstanas') || ''; var seconds = hist.getAttribute('seconds') || ''; var since = hist.getAttribute('since') || ''; if (maxchars) { result.maxchars = parseInt(maxchars, 10); } if (maxstanzas) { result.maxstanzas = parseInt(maxstanzas, 10); } if (seconds) { result.seconds = parseInt(seconds, 10); } if (since) { result.since = new Date(since); } }, set: function (opts) { var existing = stanza.find(this.xml, this._NS, 'history'); if (existing.length) { for (var i = 0; i < existing.length; i++) { this.xml.removeChild(existing[i]); } } var hist = stanza.createElement(this._NS, 'history', this._NS); this.xml.appendChild(hist); if (opts.maxchars) { hist.setAttribute('' + opts.maxchars); } if (opts.maxstanzas) { hist.setAttribute('' + opts.maxstanzas); } if (opts.seconds) { hist.setAttribute('' + opts.seconds); } if (opts.since) { hist.setAttribute(opts.since.toISOString()); } } } } }); exports.DirectInvite = stanza.define({ name: 'mucInvite', namespace: 'jabber:x:conference', element: 'x', fields: { jid: util.jidAttribute('jid'), password: stanza.attribute('password'), reason: stanza.attribute('reason'), thread: stanza.attribute('thread'), 'continue': stanza.boolAttribute('continue') } }); stanza.extend(UserItem, UserActor); stanza.extend(exports.MUC, UserItem); stanza.extend(exports.MUC, Invite, 'invites'); stanza.extend(exports.MUC, Decline); stanza.extend(exports.MUC, Destroyed); stanza.extend(AdminItem, AdminActor); stanza.extend(exports.MUCAdmin, AdminItem, 'items'); stanza.extend(exports.MUCOwner, Destroy); stanza.extend(exports.MUCOwner, DataForm); stanza.extend(Presence, exports.MUC); stanza.extend(Message, exports.MUC); stanza.extend(Presence, exports.MUCJoin); stanza.extend(Message, exports.DirectInvite); stanza.extend(Iq, exports.MUCAdmin); stanza.extend(Iq, exports.MUCOwner); },{"./dataforms":36,"./iq":44,"./message":48,"./presence":51,"./util":64,"jxt":147}],50:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var Message = require('./message'); var NS = 'jabber:x:oob'; var OOB = module.exports = stanza.define({ name: 'oob', element: 'x', namespace: NS, fields: { url: stanza.subText(NS, 'url'), desc: stanza.subText(NS, 'desc') } }); stanza.extend(Message, OOB, 'oobURIs'); },{"./message":48,"jxt":147}],51:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); module.exports = stanza.define({ name: 'presence', namespace: 'jabber:client', element: 'presence', topLevel: true, fields: { lang: stanza.langAttribute(), id: stanza.attribute('id'), to: util.jidAttribute('to'), from: util.jidAttribute('from'), priority: stanza.numberSub('jabber:client', 'priority'), show: stanza.subText('jabber:client', 'show'), type: { get: function () { return stanza.getAttribute(this.xml, 'type', 'available'); }, set: function (value) { if (value === 'available') { value = false; } stanza.setAttribute(this.xml, 'type', value); } }, $status: { get: function () { return stanza.getSubLangText(this.xml, this._NS, 'status', this.lang); } }, status: { get: function () { var statuses = this.$status; return statuses[this.lang] || ''; }, set: function (value) { stanza.setSubLangText(this.xml, this._NS, 'status', value, this.lang); } }, idleSince: stanza.dateSubAttribute('urn:xmpp:idle:1', 'idle', 'since'), decloak: stanza.subAttribute('urn:xmpp:decloak:0', 'decloak', 'reason'), avatarId: { get: function () { var NS = 'vcard-temp:x:update'; var update = stanza.find(this.xml, NS, 'x'); if (!update.length) return ''; return stanza.getSubText(update[0], NS, 'photo'); }, set: function (value) { var NS = 'vcard-temp:x:update'; var update = stanza.findOrCreate(this.xml, NS, 'x'); if (value === '') { stanza.setBoolSub(update, NS, 'photo', true); } else if (value === true) { return; } else if (value) { stanza.setSubText(update, NS, 'photo', value); } else { this.xml.removeChild(update); } } } } }); },{"./util":64,"jxt":147,"underscore":167}],52:[function(require,module,exports){ var stanza = require('jxt'); var Iq = require('./iq'); var PrivateStorage = module.exports = stanza.define({ name: 'privateStorage', namespace: 'jabber:iq:private', element: 'query' }); stanza.extend(Iq, PrivateStorage); },{"./iq":44,"jxt":147}],53:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var Iq = require('./iq'); var Message = require('./message'); var Form = require('./dataforms').DataForm; var RSM = require('./rsm'); var JID = require('../jid'); var NS = 'http://jabber.org/protocol/pubsub'; var OwnerNS = 'http://jabber.org/protocol/pubsub#owner'; var EventNS = 'http://jabber.org/protocol/pubsub#event'; exports.Pubsub = stanza.define({ name: 'pubsub', namespace: 'http://jabber.org/protocol/pubsub', element: 'pubsub', fields: { publishOptions: { get: function () { var conf = stanza.find(this.xml, this._NS, 'publish-options'); if (conf.length && conf[0].childNodes.length) { return new Form({}, conf[0].childNodes[0]); } }, set: function (value) { var conf = stanza.findOrCreate(this.xml, this._NS, 'publish-options'); if (value) { var form = new Form(value); conf.appendChild(form.xml); } } } } }); exports.PubsubOwner = stanza.define({ name: 'pubsubOwner', namespace: OwnerNS, element: 'pubsub', fields: { create: stanza.subAttribute(OwnerNS, 'create', 'node'), purge: stanza.subAttribute(OwnerNS, 'purge', 'node'), del: stanza.subAttribute(OwnerNS, 'delete', 'node'), redirect: { get: function () { var del = stanza.find(this.xml, this._NS, 'delete'); if (del.length) { return stanza.getSubAttribute(del[0], this._NS, 'redirect', 'uri'); } return ''; }, set: function (value) { var del = stanza.findOrCreate(this.xml, this._NS, 'delete'); stanza.setSubAttribute(del, this._NS, 'redirect', 'uri', value); } } } }); exports.Configure = stanza.define({ name: 'config', namespace: OwnerNS, element: 'configure', fields: { node: stanza.attribute('node') } }); exports.Event = stanza.define({ name: 'event', namespace: EventNS, element: 'event' }); exports.Subscribe = stanza.define({ name: 'subscribe', namespace: NS, element: 'subscribe', fields: { node: stanza.attribute('node'), jid: util.jidAttribute('jid') } }); exports.Subscription = stanza.define({ name: 'subscription', namespace: NS, element: 'subscription', fields: { node: stanza.attribute('node'), jid: util.jidAttribute('jid'), subid: stanza.attribute('subid'), type: stanza.attribute('subscription') } }); exports.Unsubscribe = stanza.define({ name: 'unsubscribe', namespace: NS, element: 'unsubscribe', fields: { node: stanza.attribute('node'), jid: util.jidAttribute('jid') } }); exports.Publish = stanza.define({ name: 'publish', namespace: NS, element: 'publish', fields: { node: stanza.attribute('node'), } }); exports.Retract = stanza.define({ name: 'retract', namespace: NS, element: 'retract', fields: { node: stanza.attribute('node'), notify: stanza.boolAttribute('notify'), id: stanza.subAttribute(NS, 'item', 'id') } }); exports.Retrieve = stanza.define({ name: 'retrieve', namespace: NS, element: 'items', fields: { node: stanza.attribute('node'), max: stanza.attribute('max_items') } }); exports.Item = stanza.define({ name: 'item', namespace: NS, element: 'item', fields: { id: stanza.attribute('id') } }); exports.EventItems = stanza.define({ name: 'updated', namespace: EventNS, element: 'items', fields: { node: stanza.attribute('node'), retracted: { get: function () { var results = []; var retracted = stanza.find(this.xml, this._NS, 'retract'); _.forEach(retracted, function (xml) { results.push(xml.getAttribute('id')); }); return results; }, set: function (value) { var self = this; _.forEach(value, function (id) { var retracted = document.createElementNS(self._NS, 'retract'); retracted.setAttribute('id', id); this.xml.appendChild(retracted); }); } } } }); exports.EventItem = stanza.define({ name: 'eventItem', namespace: EventNS, element: 'item', fields: { id: stanza.attribute('id'), node: stanza.attribute('node'), publisher: util.jidAttribute('publisher') } }); stanza.extend(exports.Pubsub, exports.Subscribe); stanza.extend(exports.Pubsub, exports.Unsubscribe); stanza.extend(exports.Pubsub, exports.Publish); stanza.extend(exports.Pubsub, exports.Retrieve); stanza.extend(exports.Pubsub, exports.Subscription); stanza.extend(exports.PubsubOwner, exports.Configure); stanza.extend(exports.Publish, exports.Item, 'items'); stanza.extend(exports.Retrieve, exports.Item, 'items'); stanza.extend(exports.Configure, Form); stanza.extend(exports.Pubsub, RSM); stanza.extend(exports.Event, exports.EventItems); stanza.extend(exports.EventItems, exports.EventItem, 'published'); stanza.extend(Message, exports.Event); stanza.extend(Iq, exports.Pubsub); stanza.extend(Iq, exports.PubsubOwner); },{"../jid":3,"./dataforms":36,"./iq":44,"./message":48,"./rsm":55,"./util":64,"jxt":147,"underscore":167}],54:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var Iq = require('./iq'); var JID = require('../jid'); var Roster = module.exports = stanza.define({ name: 'roster', namespace: 'jabber:iq:roster', element: 'query', fields: { ver: { get: function () { return stanza.getAttribute(this.xml, 'ver'); }, set: function (value) { var force = (value === ''); stanza.setAttribute(this.xml, 'ver', value, force); } }, items: { get: function () { var self = this; var items = stanza.find(this.xml, this._NS, 'item'); if (!items.length) { return []; } var results = []; items.forEach(function (item) { var data = { jid: new JID(stanza.getAttribute(item, 'jid', '')), name: stanza.getAttribute(item, 'name', undefined), subscription: stanza.getAttribute(item, 'subscription', 'none'), ask: stanza.getAttribute(item, 'ask', undefined), groups: [] }; var groups = stanza.find(item, self._NS, 'group'); groups.forEach(function (group) { data.groups.push(group.textContent); }); results.push(data); }); return results; }, set: function (values) { var self = this; values.forEach(function (value) { var item = document.createElementNS(self._NS, 'item'); stanza.setAttribute(item, 'jid', value.jid.toString()); stanza.setAttribute(item, 'name', value.name); stanza.setAttribute(item, 'subscription', value.subscription); stanza.setAttribute(item, 'ask', value.ask); (value.groups || []).forEach(function (name) { var group = document.createElementNS(self._NS, 'group'); group.textContent = name; item.appendChild(group); }); self.xml.appendChild(item); }); } } } }); stanza.extend(Iq, Roster); },{"../jid":3,"./iq":44,"jxt":147,"underscore":167}],55:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var util = require('./util'); var NS = 'http://jabber.org/protocol/rsm'; module.exports = stanza.define({ name: 'rsm', namespace: NS, element: 'set', fields: { after: stanza.subText(NS, 'after'), before: { get: function () { return stanza.getSubText(this.xml, this._NS, 'before'); }, set: function (value) { if (value === true) { stanza.findOrCreate(this.xml, this._NS, 'before'); } else { stanza.setSubText(this.xml, this._NS, 'before', value); } } }, count: stanza.numberSub(NS, 'count'), first: stanza.subText(NS, 'first'), firstIndex: stanza.subAttribute(NS, 'first', 'index'), index: stanza.subText(NS, 'index'), last: stanza.subText(NS, 'last'), max: stanza.subText(NS, 'max') } }); },{"./util":64,"jxt":147}],56:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var jingle = require('./jingle'); var NS = 'urn:xmpp:jingle:apps:rtp:1'; var FBNS = 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0'; var HDRNS = 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'; var INFONS = 'urn:xmpp:jingle:apps:rtp:info:1'; var SSMANS = 'urn:xmpp:jingle:apps:rtp:ssma:0'; var Feedback = { get: function () { var existing = stanza.find(this.xml, FBNS, 'rtcp-fb'); var result = []; existing.forEach(function (xml) { result.push({ type: stanza.getAttribute(xml, 'type'), subtype: stanza.getAttribute(xml, 'subtype') }); }); existing = stanza.find(this.xml, FBNS, 'rtcp-fb-trr-int'); existing.forEach(function (xml) { result.push({ type: stanza.getAttribute(xml, 'type'), value: stanza.getAttribute(xml, 'value') }); }); return result; }, set: function (values) { var self = this; var existing = stanza.find(this.xml, FBNS, 'rtcp-fb'); existing.forEach(function (item) { self.xml.removeChild(item); }); existing = stanza.find(this.xml, FBNS, 'rtcp-fb-trr-int'); existing.forEach(function (item) { self.xml.removeChild(item); }); values.forEach(function (value) { var fb; if (value.type === 'trr-int') { fb = stanza.createElement(FBNS, 'rtcp-fb-trr-int', NS); stanza.setAttribute(fb, 'type', value.type); stanza.setAttribute(fb, 'value', value.value); } else { fb = stanza.createElement(FBNS, 'rtcp-fb', NS); stanza.setAttribute(fb, 'type', value.type); stanza.setAttribute(fb, 'subtype', value.subtype); } self.xml.appendChild(fb); }); } }; exports.RTP = stanza.define({ name: '_rtp', namespace: NS, element: 'description', fields: { descType: {value: 'rtp'}, media: stanza.attribute('media'), ssrc: stanza.attribute('ssrc'), bandwidth: stanza.subText(NS, 'bandwidth'), bandwidthType: stanza.subAttribute(NS, 'bandwidth', 'type'), mux: stanza.boolSub(NS, 'rtcp-mux'), encryption: { get: function () { var enc = stanza.find(this.xml, NS, 'encryption'); if (!enc.length) return []; enc = enc[0]; var self = this; var data = stanza.find(enc, NS, 'crypto'); var results = []; data.forEach(function (xml) { results.push(new exports.Crypto({}, xml, self).toJSON()); }); return results; }, set: function (values) { var enc = stanza.find(this.xml, NS, 'encryption'); if (enc.length) { this.xml.removeChild(enc); } if (!values.length) return; stanza.setBoolSubAttribute(this.xml, NS, 'encryption', 'required', true); enc = stanza.find(this.xml, NS, 'encryption')[0]; var self = this; values.forEach(function (value) { var content = new exports.Crypto(value, null, self); enc.appendChild(content.xml); }); } }, feedback: Feedback, headerExtensions: { get: function () { var existing = stanza.find(this.xml, HDRNS, 'rtp-hdrext'); var result = []; existing.forEach(function (xml) { result.push({ id: stanza.getAttribute(xml, 'id'), uri: stanza.getAttribute(xml, 'uri'), senders: stanza.getAttribute(xml, 'senders') }); }); return result; }, set: function (values) { var self = this; var existing = stanza.find(this.xml, HDRNS, 'rtp-hdrext'); existing.forEach(function (item) { self.xml.removeChild(item); }); values.forEach(function (value) { var hdr = stanza.createElement(HDRNS, 'rtp-hdrext', NS); stanza.setAttribute(hdr, 'id', value.id); stanza.setAttribute(hdr, 'uri', value.uri); stanza.setAttribute(hdr, 'senders', value.senders); self.xml.appendChild(hdr); }); } } } }); exports.PayloadType = stanza.define({ name: '_payloadType', namespace: NS, element: 'payload-type', fields: { channels: stanza.attribute('channels'), clockrate: stanza.attribute('clockrate'), id: stanza.attribute('id'), maxptime: stanza.attribute('maxptime'), name: stanza.attribute('name'), ptime: stanza.attribute('ptime'), feedback: Feedback, parameters: { get: function () { var result = []; var params = stanza.find(this.xml, NS, 'parameter'); params.forEach(function (param) { result.push({ key: stanza.getAttribute(param, 'name'), value: stanza.getAttribute(param, 'value') }); }); return result; }, set: function (values) { var self = this; values.forEach(function (value) { var param = stanza.createElement(NS, 'parameter'); stanza.setAttribute(param, 'name', value.key); stanza.setAttribute(param, 'value', value.value); self.xml.appendChild(param); }); } } } }); exports.Crypto = stanza.define({ name: 'crypto', namespace: NS, element: 'crypto', fields: { cipherSuite: stanza.attribute('crypto-suite'), keyParams: stanza.attribute('key-params'), sessionParams: stanza.attribute('session-params'), tag: stanza.attribute('tag') } }); exports.ContentGroup = stanza.define({ name: '_group', namespace: 'urn:xmpp:jingle:apps:grouping:0', element: 'group', fields: { semantics: stanza.attribute('semantics'), contents: { get: function () { var self = this; return stanza.getMultiSubText(this.xml, this._NS, 'content', function (sub) { return stanza.getAttribute(sub, 'name'); }); }, set: function (value) { var self = this; stanza.setMultiSubText(this.xml, this._NS, 'content', value, function (val) { var child = stanza.createElement(self._NS, 'content', self._NS); stanza.setAttribute(child, 'name', val); self.xml.appendChild(child); }); } } } }); exports.SourceGroup = stanza.define({ name: '_sourceGroup', namespace: SSMANS, element: 'ssrc-group', fields: { semantics: stanza.attribute('semantics'), sources: { get: function () { var self = this; return stanza.getMultiSubText(this.xml, this._NS, 'source', function (sub) { return stanza.getAttribute(sub, 'ssrc'); }); }, set: function (value) { var self = this; stanza.setMultiSubText(this.xml, this._NS, 'source', value, function (val) { var child = stanza.createElement(self._NS, 'source', self._NS); stanza.setAttribute(child, 'ssrc', val); self.xml.appendChild(child); }); } } } }); exports.Source = stanza.define({ name: '_source', namespace: SSMANS, element: 'source', fields: { ssrc: stanza.attribute('ssrc'), parameters: { get: function () { var result = []; var params = stanza.find(this.xml, SSMANS, 'parameter'); params.forEach(function (param) { result.push({ key: stanza.getAttribute(param, 'name'), value: stanza.getAttribute(param, 'value') }); }); return result; }, set: function (values) { var self = this; values.forEach(function (value) { var param = stanza.createElement(SSMANS, 'parameter'); stanza.setAttribute(param, 'name', value.key); stanza.setAttribute(param, 'value', value.value); self.xml.appendChild(param); }); } } } }); exports.Mute = stanza.define({ name: 'mute', namespace: INFONS, element: 'mute', fields: { creator: stanza.attribute('creator'), name: stanza.attribute('name') } }); exports.Unmute = stanza.define({ name: 'unmute', namespace: INFONS, element: 'unmute', fields: { creator: stanza.attribute('creator'), name: stanza.attribute('name') } }); stanza.extend(jingle.Content, exports.RTP); stanza.extend(exports.RTP, exports.PayloadType, 'payloads'); stanza.extend(exports.RTP, exports.Source, 'sources'); stanza.extend(exports.RTP, exports.SourceGroup, 'sourceGroups'); stanza.extend(jingle.Jingle, exports.Mute); stanza.extend(jingle.Jingle, exports.Unmute); stanza.extend(jingle.Jingle, exports.ContentGroup, 'groups'); stanza.add(jingle.Jingle, 'ringing', stanza.boolSub(INFONS, 'ringing')); stanza.add(jingle.Jingle, 'hold', stanza.boolSub(INFONS, 'hold')); stanza.add(jingle.Jingle, 'active', stanza.boolSub(INFONS, 'active')); },{"./jingle":45,"./util":64,"jxt":147,"underscore":167}],57:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var util = require('./util'); var StreamFeatures = require('./streamFeatures'); var NS = 'urn:ietf:params:xml:ns:xmpp-sasl'; var CONDITIONS = [ 'aborted', 'account-disabled', 'credentials-expired', 'encryption-required', 'incorrect-encoding', 'invalid-authzid', 'invalid-mechanism', 'malformed-request', 'mechanism-too-weak', 'not-authorized', 'temporary-auth-failure' ]; exports.Mechanisms = stanza.define({ name: 'sasl', namespace: NS, element: 'mechanisms', fields: { mechanisms: stanza.multiSubText(NS, 'mechanism') } }); exports.Auth = stanza.define({ name: 'saslAuth', eventName: 'sasl:auth', namespace: NS, element: 'auth', topLevel: true, fields: { value: stanza.b64Text(), mechanism: stanza.attribute('mechanism') } }); exports.Challenge = stanza.define({ name: 'saslChallenge', eventName: 'sasl:challenge', namespace: NS, element: 'challenge', topLevel: true, fields: { value: stanza.b64Text() } }); exports.Response = stanza.define({ name: 'saslResponse', eventName: 'sasl:response', namespace: NS, element: 'response', topLevel: true, fields: { value: stanza.b64Text() } }); exports.Abort = stanza.define({ name: 'saslAbort', eventName: 'sasl:abort', namespace: NS, element: 'abort', topLevel: true }); exports.Success = stanza.define({ name: 'saslSuccess', eventName: 'sasl:success', namespace: NS, element: 'success', topLevel: true, fields: { value: stanza.b64Text() } }); exports.Failure = stanza.define({ name: 'saslFailure', eventName: 'sasl:failure', namespace: NS, element: 'failure', topLevel: true, fields: { lang: { get: function () { return this._lang || ''; }, set: function (value) { this._lang = value; } }, condition: { get: function () { var self = this; var result = []; CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, NS, condition); if (exists.length) { result.push(exists[0].tagName); } }); return result[0] || ''; }, set: function (value) { var self = this; this._CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, NS, condition); if (exists.length) { self.xml.removeChild(exists[0]); } }); if (value) { var condition = stanza.createElementNS(NS, value); condition.setAttribute('xmlns', NS); this.xml.appendChild(condition); } } }, $text: { get: function () { return stanza.getSubLangText(this.xml, NS, 'text', this.lang); } }, text: { get: function () { var text = this.$text; return text[this.lang] || ''; }, set: function (value) { stanza.setSubLangText(this.xml, NS, 'text', value, this.lang); } } } }); stanza.extend(StreamFeatures, exports.Mechanisms); },{"./streamFeatures":62,"./util":64,"jxt":147,"underscore":167}],58:[function(require,module,exports){ var stanza = require('jxt'); var Iq = require('./iq'); var StreamFeatures = require('./streamFeatures'); var Session = module.exports = stanza.define({ name: 'session', namespace: 'urn:ietf:params:xml:ns:xmpp-session', element: 'session' }); stanza.extend(StreamFeatures, Session); stanza.extend(Iq, Session); },{"./iq":44,"./streamFeatures":62,"jxt":147}],59:[function(require,module,exports){ var stanza = require('jxt'); var util = require('./util'); var StreamFeatures = require('./streamFeatures'); var NS = 'urn:xmpp:sm:3'; exports.SMFeature = stanza.define({ name: 'streamManagement', namespace: NS, element: 'sm' }); exports.Enable = stanza.define({ name: 'smEnable', eventName: 'stream:management:enable', namespace: NS, element: 'enable', topLevel: true, fields: { resume: stanza.boolAttribute('resume') } }); exports.Enabled = stanza.define({ name: 'smEnabled', eventName: 'stream:management:enabled', namespace: NS, element: 'enabled', topLevel: true, fields: { id: stanza.attribute('id'), resume: stanza.boolAttribute('resume') } }); exports.Resume = stanza.define({ name: 'smResume', eventName: 'stream:management:resume', namespace: NS, element: 'resume', topLevel: true, fields: { h: stanza.numberAttribute('h'), previd: stanza.attribute('previd') } }); exports.Resumed = stanza.define({ name: 'smResumed', eventName: 'stream:management:resumed', namespace: NS, element: 'resumed', topLevel: true, fields: { h: stanza.numberAttribute('h'), previd: stanza.attribute('previd') } }); exports.Failed = stanza.define({ name: 'smFailed', eventName: 'stream:management:failed', namespace: NS, element: 'failed', topLevel: true }); exports.Ack = stanza.define({ name: 'smAck', eventName: 'stream:management:ack', namespace: NS, element: 'a', topLevel: true, fields: { h: stanza.numberAttribute('h') } }); exports.Request = stanza.define({ name: 'smRequest', eventName: 'stream:management:request', namespace: NS, element: 'r', topLevel: true }); stanza.extend(StreamFeatures, exports.SMFeature); },{"./streamFeatures":62,"./util":64,"jxt":147}],60:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var util = require('./util'); module.exports = stanza.define({ name: 'stream', namespace: 'http://etherx.jabber.org/streams', element: 'stream', fields: { lang: { get: function () { return this.xml.getAttributeNS(stanza.XML_NS, 'lang') || ''; }, set: function (value) { this.xml.setAttributeNS(stanza.XML_NS, 'lang', value); } }, id: stanza.attribute('id'), version: stanza.attribute('version', '1.0'), to: util.jidAttribute('to'), from: util.jidAttribute('from') } }); },{"./util":64,"jxt":147}],61:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var ERR_NS = 'urn:ietf:params:xml:ns:xmpp-streams'; var CONDITIONS = [ 'bad-format', 'bad-namespace-prefix', 'conflict', 'connection-timeout', 'host-gone', 'host-unknown', 'improper-addressing', 'internal-server-error', 'invalid-from', 'invalid-namespace', 'invalid-xml', 'not-authorized', 'not-well-formed', 'policy-violation', 'remote-connection-failed', 'reset', 'resource-constraint', 'restricted-xml', 'see-other-host', 'system-shutdown', 'undefined-condition', 'unsupported-encoding', 'unsupported-feature', 'unsupported-stanza-type', 'unsupported-version' ]; module.exports = stanza.define({ name: 'streamError', namespace: 'http://etherx.jabber.org/streams', element: 'error', topLevel: true, fields: { lang: { get: function () { return this._lang || ''; }, set: function (value) { this._lang = value; } }, condition: { get: function () { var self = this; var result = []; CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, ERR_NS, condition); if (exists.length) { result.push(exists[0].tagName); } }); return result[0] || ''; }, set: function (value) { var self = this; this._CONDITIONS.forEach(function (condition) { var exists = stanza.find(self.xml, ERR_NS, condition); if (exists.length) { self.xml.removeChild(exists[0]); } }); if (value) { var condition = stanza.createElementNS(ERR_NS, value); condition.setAttribute('xmlns', ERR_NS); this.xml.appendChild(condition); } } }, seeOtherHost: { get: function () { return stanza.getSubText(this.xml, ERR_NS, 'see-other-host'); }, set: function (value) { this.condition = 'see-other-host'; stanza.setSubText(this.xml, ERR_NS, 'see-other-host', value); } }, $text: { get: function () { return stanza.getSubLangText(this.xml, ERR_NS, 'text', this.lang); } }, text: { get: function () { var text = this.$text; return text[this.lang] || ''; }, set: function (value) { stanza.setSubLangText(this.xml, ERR_NS, 'text', value, this.lang); } } } }); },{"jxt":147,"underscore":167}],62:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var StreamFeatures = module.exports = stanza.define({ name: 'streamFeatures', namespace: 'http://etherx.jabber.org/streams', element: 'features', topLevel: true, fields: { features: { get: function () { return this._extensions; } } } }); var RosterVerFeature = stanza.define({ name: 'rosterVersioning', namespace: 'urn:xmpp:features:rosterver', element: 'ver' }); var SubscriptionPreApprovalFeature = stanza.define({ name: 'subscriptionPreApproval', namespace: 'urn:xmpp:features:pre-approval', element: 'sub' }); stanza.extend(StreamFeatures, RosterVerFeature); stanza.extend(StreamFeatures, SubscriptionPreApprovalFeature); },{"jxt":147}],63:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var util = require('./util'); var Iq = require('./iq'); var EntityTime = module.exports = stanza.define({ name: 'time', namespace: 'urn:xmpp:time', element: 'time', fields: { utc: stanza.dateSub('urn:xmpp:time', 'utc'), tzo: { get: function () { var split, hrs, min; var sign = -1; var formatted = stanza.getSubText(this.xml, this._NS, 'tzo'); if (!formatted) { return 0; } if (formatted.charAt(0) === '-') { sign = 1; formatted = formatted.slice(1); } split = formatted.split(':'); hrs = parseInt(split[0], 10); min = parseInt(split[1], 10); return (hrs * 60 + min) * sign; }, set: function (value) { var hrs, min; var formatted = '-'; if (typeof value === 'number') { if (value < 0) { value = -value; formatted = '+'; } hrs = value / 60; min = value % 60; formatted += (hrs < 10 ? '0' : '') + hrs + ':' + (min < 10 ? '0' : '') + min; } else { formatted = value; } stanza.setSubText(this.xml, this._NS, 'tzo', formatted); } } } }); stanza.extend(Iq, EntityTime); },{"./iq":44,"./util":64,"jxt":147}],64:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var JID = require('../jid'); exports.jidAttribute = stanza.field( function (xml, attr) { return new JID(stanza.getAttribute(xml, attr)); }, function (xml, attr, value) { stanza.setAttribute(xml, attr, (value || '').toString()); } ); exports.jidSub = stanza.field( function (xml, NS, sub) { return new JID(stanza.getSubText(xml, NS, sub)); }, function (xml, NS, sub, value) { stanza.setSubText(xml, NS, sub, (value || '').toString()); } ); },{"../jid":3,"jxt":147}],65:[function(require,module,exports){ "use strict"; var stanza = require('jxt'); var Iq = require('./iq'); var NS = 'vcard-temp'; var VCardTemp = module.exports = stanza.define({ name: 'vCardTemp', namespace: NS, element: 'vCard', fields: { fullName: stanza.subText(NS, 'FN'), birthday: stanza.dateSub(NS, 'BDAY'), nicknames: stanza.multiSubText(NS, 'NICKNAME') } }); var Name = stanza.define({ name: 'name', namespace: NS, element: 'N', fields: { family: stanza.subText(NS, 'FAMILY'), given: stanza.subText(NS, 'GIVEN'), middle: stanza.subText(NS, 'MIDDLE'), prefix: stanza.subText(NS, 'PREFIX'), suffix: stanza.subText(NS, 'SUFFIX') } }); var Photo = stanza.define({ name: 'photo', namespace: NS, element: 'PHOTO', fields: { type: stanza.subText(NS, 'TYPE'), data: stanza.subText(NS, 'BINVAL'), url: stanza.subText(NS, 'EXTVAL') } }); stanza.extend(VCardTemp, Name); stanza.extend(VCardTemp, Photo); stanza.extend(Iq, VCardTemp); },{"./iq":44,"jxt":147}],66:[function(require,module,exports){ var stanza = require('jxt'); var Iq = require('./iq'); var NS = 'jabber:iq:version'; var Version = module.exports = stanza.define({ name: 'version', namespace: NS, element: 'query', fields: { name: stanza.subText(NS, 'name'), version: stanza.subText(NS, 'version'), os: stanza.subText(NS, 'os') } }); stanza.extend(Iq, Version); },{"./iq":44,"jxt":147}],67:[function(require,module,exports){ var stanza = require('jxt'); var Iq = require('./iq'); stanza.add(Iq, 'visible', stanza.boolSub('urn:xmpp:invisible:0', 'visible')); stanza.add(Iq, 'invisible', stanza.boolSub('urn:xmpp:invisible:0', 'invisible')); },{"./iq":44,"jxt":147}],68:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var stanza = require('jxt'); var WildEmitter = require('wildemitter'); var async = require('async'); var Stream = require('./stanza/stream'); var Message = require('./stanza/message'); var Presence = require('./stanza/presence'); var Iq = require('./stanza/iq'); var StreamManagement = require('./sm'); var uuid = require('node-uuid'); function WSConnection() { var self = this; WildEmitter.call(this); self.sm = new StreamManagement(self); self.sendQueue = async.queue(function (data, cb) { if (self.conn) { self.sm.track(data); if (typeof data !== 'string') { data = data.toString(); } self.emit('raw:outgoing', data); self.conn.send(data); } cb(); }, 1); function wrap(data) { return [self.streamStart, data, self.streamEnd].join(''); } self.on('connected', function () { self.send([ '' ].join(' ')); }); self.on('raw:incoming', function (data) { var streamData, ended; data = data.trim(); data = data.replace(/^(\s*<\?.*\?>\s*)*/, ''); if (data === '') { return; } if (data.match(self.streamEnd)) { return self.disconnect(); } else if (self.hasStream) { try { streamData = stanza.parse(Stream, wrap(data)); } catch (e) { return self.disconnect(); } } else { // Inspect start of stream element to get NS prefix name var parts = data.match(/^<(\S+:)?(\S+) /); self.streamStart = data; self.streamEnd = ''; ended = false; try { streamData = stanza.parse(Stream, data + self.streamEnd); } catch (e) { try { streamData = stanza.parse(Stream, data); ended = true; } catch (e2) { return self.disconnect(); } } self.hasStream = true; self.stream = streamData; self.emit('stream:start', streamData); } _.each(streamData._extensions, function (stanzaObj) { if (!stanzaObj.lang) { stanzaObj.lang = self.stream.lang; } if (stanzaObj._name === 'message' || stanzaObj._name === 'presence' || stanzaObj._name === 'iq') { self.sm.handle(stanzaObj); self.emit('stanza', stanzaObj); } self.emit(stanzaObj._eventname || stanzaObj._name, stanzaObj); self.emit('stream:data', stanzaObj); if (stanzaObj.id) { self.emit('id:' + stanzaObj.id, stanzaObj); } }); if (ended) { self.emit('stream:end'); } }); } WSConnection.prototype = Object.create(WildEmitter.prototype, { constructor: { value: WSConnection } }); WSConnection.prototype.connect = function (opts) { var self = this; self.config = opts; self.hasStream = false; self.streamStart = ''; self.streamEnd = ''; self.conn = new WebSocket(opts.wsURL, 'xmpp'); self.conn.onerror = function (e) { e.preventDefault(); self.emit('disconnected', self); return false; }; self.conn.onclose = function () { self.emit('disconnected', self); }; self.conn.onopen = function () { self.sm.started = false; self.emit('connected', self); }; self.conn.onmessage = function (wsMsg) { self.emit('raw:incoming', wsMsg.data); }; }; WSConnection.prototype.disconnect = function () { if (this.conn) { if (this.hasStream) { this.conn.send(''); this.emit('raw:outgoing', ''); this.emit('stream:end'); } this.hasStream = false; this.conn.close(); this.stream = undefined; this.conn = undefined; this.sm.failed(); } }; WSConnection.prototype.restart = function () { var self = this; self.hasStream = false; self.send([ '' ].join(' ')); }; WSConnection.prototype.send = function (data) { this.sendQueue.push(data); }; module.exports = WSConnection; },{"./sm":29,"./stanza/iq":44,"./stanza/message":48,"./stanza/presence":51,"./stanza/stream":60,"async":69,"jxt":147,"node-uuid":154,"underscore":167,"wildemitter":168}],69:[function(require,module,exports){ var process=require("__browserify_process");/*global setImmediate: false, setTimeout: false, console: false */ (function () { var async = {}; // global on the server, window in the browser var root, previous_async; root = this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { var called = false; return function() { if (called) throw new Error("Callback was already called."); called = true; fn.apply(root, arguments); } } //// cross-browser compatiblity functions //// var _each = function (arr, iterator) { if (arr.forEach) { return arr.forEach(iterator); } for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; var _map = function (arr, iterator) { if (arr.map) { return arr.map(iterator); } var results = []; _each(arr, function (x, i, a) { results.push(iterator(x, i, a)); }); return results; }; var _reduce = function (arr, iterator, memo) { if (arr.reduce) { return arr.reduce(iterator, memo); } _each(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; }; var _keys = function (obj) { if (Object.keys) { return Object.keys(obj); } var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// if (typeof process === 'undefined' || !(process.nextTick)) { if (typeof setImmediate === 'function') { async.nextTick = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; async.setImmediate = async.nextTick; } else { async.nextTick = function (fn) { setTimeout(fn, 0); }; async.setImmediate = async.nextTick; } } else { async.nextTick = process.nextTick; if (typeof setImmediate !== 'undefined') { async.setImmediate = setImmediate; } else { async.setImmediate = async.nextTick; } } async.each = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, only_once(function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } } })); }); }; async.forEach = async.each; async.eachSeries = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; var iterate = function () { iterator(arr[completed], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } else { iterate(); } } }); }; iterate(); }; async.forEachSeries = async.eachSeries; async.eachLimit = function (arr, limit, iterator, callback) { var fn = _eachLimit(limit); fn.apply(null, [arr, iterator, callback]); }; async.forEachLimit = async.eachLimit; var _eachLimit = function (limit) { return function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length || limit <= 0) { return callback(); } var completed = 0; var started = 0; var running = 0; (function replenish () { if (completed >= arr.length) { return callback(); } while (running < limit && started < arr.length) { started += 1; running += 1; iterator(arr[started - 1], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; running -= 1; if (completed >= arr.length) { callback(); } else { replenish(); } } }); } })(); }; }; var doParallel = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.each].concat(args)); }; }; var doParallelLimit = function(limit, fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [_eachLimit(limit)].concat(args)); }; }; var doSeries = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.eachSeries].concat(args)); }; }; var _asyncMap = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (err, v) { results[x.index] = v; callback(err); }); }, function (err) { callback(err, results); }); }; async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = function (arr, limit, iterator, callback) { return _mapLimit(limit)(arr, iterator, callback); }; var _mapLimit = function(limit) { return doParallelLimit(limit, _asyncMap); }; // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.reduce = function (arr, memo, iterator, callback) { async.eachSeries(arr, function (x, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; // inject alias async.inject = async.reduce; // foldl alias async.foldl = async.reduce; async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, function (x) { return x; }).reverse(); async.reduce(reversed, memo, iterator, callback); }; // foldr alias async.foldr = async.reduceRight; var _filter = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.filter = doParallel(_filter); async.filterSeries = doSeries(_filter); // select alias async.select = async.filter; async.selectSeries = async.filterSeries; var _reject = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (!v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.reject = doParallel(_reject); async.rejectSeries = doSeries(_reject); var _detect = function (eachfn, arr, iterator, main_callback) { eachfn(arr, function (x, callback) { iterator(x, function (result) { if (result) { main_callback(x); main_callback = function () {}; } else { callback(); } }); }, function (err) { main_callback(); }); }; async.detect = doParallel(_detect); async.detectSeries = doSeries(_detect); async.some = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (v) { main_callback(true); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(false); }); }; // any alias async.any = async.some; async.every = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (!v) { main_callback(false); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(true); }); }; // all alias async.all = async.every; async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { var fn = function (left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }; callback(null, _map(results.sort(fn), function (x) { return x.value; })); } }); }; async.auto = function (tasks, callback) { callback = callback || function () {}; var keys = _keys(tasks); if (!keys.length) { return callback(null); } var results = {}; var listeners = []; var addListener = function (fn) { listeners.unshift(fn); }; var removeListener = function (fn) { for (var i = 0; i < listeners.length; i += 1) { if (listeners[i] === fn) { listeners.splice(i, 1); return; } } }; var taskComplete = function () { _each(listeners.slice(0), function (fn) { fn(); }); }; addListener(function () { if (_keys(results).length === keys.length) { callback(null, results); callback = function () {}; } }); _each(keys, function (k) { var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; var taskCallback = function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _each(_keys(results), function(rkey) { safeResults[rkey] = results[rkey]; }); safeResults[k] = args; callback(err, safeResults); // stop subsequent errors hitting callback multiple times callback = function () {}; } else { results[k] = args; async.setImmediate(taskComplete); } }; var requires = task.slice(0, Math.abs(task.length - 1)) || []; var ready = function () { return _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); }; if (ready()) { task[task.length - 1](taskCallback, results); } else { var listener = function () { if (ready()) { removeListener(listener); task[task.length - 1](taskCallback, results); } }; addListener(listener); } }); }; async.waterfall = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor !== Array) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } var wrapIterator = function (iterator) { return function (err) { if (err) { callback.apply(null, arguments); callback = function () {}; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } async.setImmediate(function () { iterator.apply(null, args); }); } }; }; wrapIterator(async.iterator(tasks))(); }; var _parallel = function(eachfn, tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { eachfn.map(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; eachfn.each(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.parallel = function (tasks, callback) { _parallel({ map: async.map, each: async.each }, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); }; async.series = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { async.mapSeries(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; async.eachSeries(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.iterator = function (tasks) { var makeCallback = function (index) { var fn = function () { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); }; fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; }; return makeCallback(0); }; async.apply = function (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply( null, args.concat(Array.prototype.slice.call(arguments)) ); }; }; var _concat = function (eachfn, arr, fn, callback) { var r = []; eachfn(arr, function (x, cb) { fn(x, function (err, y) { r = r.concat(y || []); cb(err); }); }, function (err) { callback(err, r); }); }; async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { if (test()) { iterator(function (err) { if (err) { return callback(err); } async.whilst(test, iterator, callback); }); } else { callback(); } }; async.doWhilst = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (test()) { async.doWhilst(iterator, test, callback); } else { callback(); } }); }; async.until = function (test, iterator, callback) { if (!test()) { iterator(function (err) { if (err) { return callback(err); } async.until(test, iterator, callback); }); } else { callback(); } }; async.doUntil = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (!test()) { async.doUntil(iterator, test, callback); } else { callback(); } }); }; async.queue = function (worker, concurrency) { if (concurrency === undefined) { concurrency = 1; } function _insert(q, data, pos, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { var item = { data: task, callback: typeof callback === 'function' ? callback : null }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.saturated && q.tasks.length === concurrency) { q.saturated(); } async.setImmediate(q.process); }); } var workers = 0; var q = { tasks: [], concurrency: concurrency, saturated: null, empty: null, drain: null, push: function (data, callback) { _insert(q, data, false, callback); }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (workers < q.concurrency && q.tasks.length) { var task = q.tasks.shift(); if (q.empty && q.tasks.length === 0) { q.empty(); } workers += 1; var next = function () { workers -= 1; if (task.callback) { task.callback.apply(task, arguments); } if (q.drain && q.tasks.length + workers === 0) { q.drain(); } q.process(); }; var cb = only_once(next); worker(task.data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; } }; return q; }; async.cargo = function (worker, payload) { var working = false, tasks = []; var cargo = { tasks: tasks, payload: payload, saturated: null, empty: null, drain: null, push: function (data, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { tasks.push({ data: task, callback: typeof callback === 'function' ? callback : null }); if (cargo.saturated && tasks.length === payload) { cargo.saturated(); } }); async.setImmediate(cargo.process); }, process: function process() { if (working) return; if (tasks.length === 0) { if(cargo.drain) cargo.drain(); return; } var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0); var ds = _map(ts, function (task) { return task.data; }); if(cargo.empty) cargo.empty(); working = true; worker(ds, function () { working = false; var args = arguments; _each(ts, function (data) { if (data.callback) { data.callback.apply(null, args); } }); process(); }); }, length: function () { return tasks.length; }, running: function () { return working; } }; return cargo; }; var _console_fn = function (name) { return function (fn) { var args = Array.prototype.slice.call(arguments, 1); fn.apply(null, args.concat([function (err) { var args = Array.prototype.slice.call(arguments, 1); if (typeof console !== 'undefined') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _each(args, function (x) { console[name](x); }); } } }])); }; }; async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || function (x) { return x; }; var memoized = function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { callback.apply(null, memo[key]); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([function () { memo[key] = arguments; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, arguments); } }])); } }; memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; async.times = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.map(counter, iterator, callback); }; async.timesSeries = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.mapSeries(counter, iterator, callback); }; async.compose = function (/* functions... */) { var fns = Array.prototype.reverse.call(arguments); return function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([function () { var err = arguments[0]; var nextargs = Array.prototype.slice.call(arguments, 1); cb(err, nextargs); }])) }, function (err, results) { callback.apply(that, [err].concat(results)); }); }; }; var _applyEach = function (eachfn, fns /*args...*/) { var go = function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); return eachfn(fns, function (fn, cb) { fn.apply(that, args.concat([cb])); }, callback); }; if (arguments.length > 2) { var args = Array.prototype.slice.call(arguments, 2); return go.apply(this, args); } else { return go; } }; async.applyEach = doParallel(_applyEach); async.applyEachSeries = doSeries(_applyEach); async.forever = function (fn, callback) { function next(err) { if (err) { if (callback) { return callback(err); } throw err; } fn(next); } next(); }; // AMD / RequireJS if (typeof define !== 'undefined' && define.amd) { define([], function () { return async; }); } // Node.js else if (typeof module !== 'undefined' && module.exports) { module.exports = async; } // included directly via