(function(e){if("function"==typeof bootstrap)bootstrap("xmpp",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeXMPP=e}else"undefined"!=typeof window?window.XMPP=e():global.XMPP=e()})(function(){var define,ses,bootstrap,module,exports; return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s 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){ 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){ 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, avatars: msg.event.updated.published[0].avatars }); }); client.publishAvatar = function (id, data, cb) { client.publish('', 'urn:xmpp:avatar:data', { id: id, avatarData: data }, cb); }; client.useAvatars = function (info, cb) { client.publish('', 'urn:xmpp:avatar:metadata', { id: 'current', avatars: info }, cb); }; client.getAvatar = function (jid, id, cb) { client.getItem(jid, 'urn:xmpp:avatar:data', id, cb); }; }; },{"../stanza/avatar":23}],6:[function(require,module,exports){ var stanzas = require('../stanza/bookmarks'); module.exports = function (client) { client.getBookmarks = function (cb) { this.getPrivateData({bookmarks: {}}, cb); }; client.setBookmarks = function (opts, cb) { this.setPrivateData({bookmarks: opts}, cb); }; }; },{"../stanza/bookmarks":25}],7:[function(require,module,exports){ var stanzas = require('../stanza/carbons'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:carbons:2'); client.enableCarbons = function (cb) { this.sendIq({ type: 'set', enableCarbons: true }, cb); }; client.disableCarbons = function (cb) { 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":27}],8:[function(require,module,exports){ 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":28}],9:[function(require,module,exports){ 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){ var stanzas = require('../stanza/delayed'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:delay'); }; },{"../stanza/delayed":30}],11:[function(require,module,exports){ /*global unescape, escape */ 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 verifyVerString(info, hash, check) { if (hash === 'sha-1') { hash = 'sha1'; } var computed = generateVerString(info, hash); return computed && computed == check; } 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 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) { this.sendIq({ to: jid, type: 'get', discoInfo: { node: node } }, cb); }; client.getDiscoItems = function (jid, node, cb) { 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 = ''; } var res = iq.resultReply({ discoInfo: { node: reportedNode, identities: client.disco.identities[node] || [], features: client.disco.features[node] || [], extensions: client.disco.extensions[node] || [] } }); debugger; client.sendIq(res); }); 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":26,"../stanza/disco":31,"crypto":63,"underscore":96}],12:[function(require,module,exports){ var stanzas = require('../stanza/forwarded'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:forward:0'); }; },{"../stanza/forwarded":33}],13:[function(require,module,exports){ var stanzas = require('../stanza/idle'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:idle:0'); }; },{"../stanza/idle":34}],14:[function(require,module,exports){ require('../stanza/visibility'); module.exports = function (client) { client.goInvisible = function (cb) { this.sendIq({ type: 'set', invisible: true }); }; client.goVisible = function (cb) { this.sendIq({ type: 'set', visible: true }); }; }; },{"../stanza/visibility":54}],15:[function(require,module,exports){ 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); }); cb = cb || function () {}; this.sendIq({ type: 'get', id: queryid, mamQuery: opts }, function (err, resp) { if (err) { cb(err); } else { self.off('mam:' + queryid); resp.mamQuery.results = mamResults; cb(null, resp); } }); }; client.getHistoryPreferences = function (cb) { client.sendIq({ type: 'get', mamPrefs: {} }, cb); }; client.setHistoryPreferences = function (opts, cb) { client.sendIq({ type: 'set', mamPrefs: opts }, cb); }; client.on('message', function (msg) { if (msg._extensions.mam) { client.emit('mam:' + msg.mam.queryid, msg); } }); }; },{"../stanza/mam":36}],16:[function(require,module,exports){ require('../stanza/muc'); module.exports = function (client) { 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); }; }; },{"../stanza/muc":38}],17:[function(require,module,exports){ var stanzas = require('../stanza/private'); module.exports = function (client) { client.getPrivateData = function (opts, cb) { this.sendIq({ type: 'get', privateStorage: opts }, cb); }; client.setPrivateData = function (opts, cb) { this.sendIq({ type: 'set', privateStorage: opts }, cb); }; }; },{"../stanza/private":40}],18:[function(require,module,exports){ 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) { client.sendIq({ type: 'set', to: jid, pubsub: { subscribe: { node: opts.node, jid: opts.jid || client.jid } } }, cb); }; client.unsubscribeFromNode = function (jid, opts, cb) { client.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) { client.sendIq({ type: 'set', to: jid, pubsub: { publish: { node: node, item: item } } }, cb); }; client.getItem = function (jid, node, id, cb) { client.sendIq({ type: 'get', to: jid, pubsub: { retrieve: { node: node, item: id } } }, cb); }; client.getItems = function (jid, node, opts, cb) { opts = opts || {}; opts.node = node; client.sendIq({ type: 'get', to: jid, pubsub: { retrieve: { node: node, max: opts.max }, rsm: opts.rsm } }, cb); }; client.retract = function (jid, node, id, notify, cb) { client.sendIq({ type: 'set', to: jid, pubsub: { retract: { node: node, notify: notify, id: id } } }, cb); }; client.purgeNode = function (jid, node, cb) { client.sendIq({ type: 'set', to: jid, pubsubOwner: { purge: node } }, cb); }; client.deleteNode = function (jid, node, cb) { client.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}; } client.sendIq(cmd, cb); }; }; },{"../stanza/pubsub":41}],19:[function(require,module,exports){ var stanzas = require('../stanza/receipts'); 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._extensions.receipt) { client.sendMessage({ to: msg.from, receipt: { id: msg.id }, id: msg.id }); } if (msg._extensions.receipt) { client.emit('receipt:' + msg.receipt.id); } }); }; },{"../stanza/receipts":42}],20:[function(require,module,exports){ var stanzas = require('../stanza/time'); module.exports = function (client) { client.disco.addFeature('urn:xmpp:time'); client.getTime = function (jid, cb) { 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":51}],21:[function(require,module,exports){ 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) { this.sendIq({ to: jid, type: 'get', version: {} }, cb); }; }; },{"../stanza/version":53}],22:[function(require,module,exports){ 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.windowCount = 0; this.unacked = []; } 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.windowCount = 0; this.unacked = []; }, ack: function () { this.conn.send(new SM.Ack({ h: this.handled })); }, request: function () { this.conn.send(new SM.Request()); }, process: function (ack, resend) { var self = this; var numAcked = mod(ack.h - this.lastAck, MAX_SEQ); for (var i = 0; i < numAcked && this.unacked.length > 0; i++) { this.conn.emit('stanza:acked', this.unacked.shift()); } if (resend) { var resendUnacked = this.unacked; this.unacked = []; resendUnacked.forEach(function (stanza) { self.conn.send(stanza); }); } this.lastAck = ack.h; }, track: function (stanza) { var name = stanza._name; var acceptable = { message: true, presence: true, iq: true }; if (this.started && acceptable[name]) { this.unacked.push(stanza); this.windowCount += 1; if (this.windowCount == this.windowSize) { this.request(); this.windowCount = 0; } } }, handle: function (stanza) { if (this.started) { this.handled = mod(this.handled + 1, MAX_SEQ); } } }; module.exports = StreamManagement; },{"./stanza/sm":47}],23:[function(require,module,exports){ 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":41,"jxt":77,"underscore":96}],24:[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":35,"./streamFeatures":50,"./util":52,"jxt":77}],25:[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":40,"./util":52,"jxt":77}],26:[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":39,"./streamFeatures":50,"jxt":77}],27:[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":33,"./iq":35,"./message":37,"jxt":77}],28:[function(require,module,exports){ 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":37,"jxt":77}],29:[function(require,module,exports){ 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); },{"./message":37,"./util":52,"jxt":77,"underscore":96}],30:[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: util.dateAttribute('stamp'), reason: stanza.text() } }); stanza.extend(Message, DelayedDelivery); stanza.extend(Presence, DelayedDelivery); },{"./message":37,"./presence":39,"./util":52,"jxt":77}],31:[function(require,module,exports){ 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":29,"./iq":35,"./rsm":44,"jxt":77,"underscore":96}],32:[function(require,module,exports){ 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":35,"./message":37,"./presence":39,"./util":52,"jxt":77,"underscore":96}],33:[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":30,"./iq":35,"./message":37,"./presence":39,"jxt":77}],34:[function(require,module,exports){ var stanza = require('jxt'); var util = require('./util'); var Presence = require('./presence'); var Idle = module.exports = stanza.define({ name: 'idle', namespace: 'urn:xmpp:idle:0', element: 'idle', fields: { since: util.dateAttribute('since') } }); stanza.extend(Presence, Idle); },{"./presence":39,"./util":52,"jxt":77}],35:[function(require,module,exports){ 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: util.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":52,"jxt":77}],36:[function(require,module,exports){ 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: util.dateSub('urn:xmpp:mam:tmp', 'start'), end: util.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":33,"./iq":35,"./message":37,"./rsm":44,"./util":52,"jxt":77}],37:[function(require,module,exports){ 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: util.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'), $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') } }); },{"./util":52,"jxt":77,"underscore":96}],38:[function(require,module,exports){ var stanza = require('jxt'); var Message = require('./message'); var Presence = require('./presence'); var Iq = require('./iq'); var NS = 'http://jabber.org/protocol/muc'; 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 = document.createElementNS(this._NS, 'history'); 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()); } } } } }); stanza.extend(Presence, exports.MUCJoin); },{"./iq":35,"./message":37,"./presence":39,"jxt":77}],39:[function(require,module,exports){ 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: util.langAttribute(), id: stanza.attribute('id'), to: util.jidAttribute('to'), from: util.jidAttribute('from'), priority: stanza.subText('jabber:client', 'priority', '0'), 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); } } } }); },{"./util":52,"jxt":77,"underscore":96}],40:[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":35,"jxt":77}],41:[function(require,module,exports){ 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":29,"./iq":35,"./message":37,"./rsm":44,"./util":52,"jxt":77,"underscore":96}],42:[function(require,module,exports){ var stanza = require('jxt'); var Message = require('./message'); stanza.add(Message, 'requestReceipt', stanza.boolSub('urn:xmpp:receipts', 'request')); var Received = module.exports = stanza.define({ name: 'receipt', namespace: 'urn:xmpp:receipts', element: 'receipt', fields: { id: stanza.attribute('id') } }); stanza.extend(Message, Received); },{"./message":37,"jxt":77}],43:[function(require,module,exports){ 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":35,"jxt":77,"underscore":96}],44:[function(require,module,exports){ 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: util.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":52,"jxt":77}],45:[function(require,module,exports){ 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: util.b64Text(), mechanism: stanza.attribute('mechanism') } }); exports.Challenge = stanza.define({ name: 'saslChallenge', eventName: 'sasl:challenge', namespace: NS, element: 'challenge', topLevel: true, fields: { value: util.b64Text() } }); exports.Response = stanza.define({ name: 'saslResponse', eventName: 'sasl:response', namespace: NS, element: 'response', topLevel: true, fields: { value: util.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: util.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":50,"./util":52,"jxt":77,"underscore":96}],46:[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":35,"./streamFeatures":50,"jxt":77}],47:[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: util.numberAttribute('h', '0'), previd: stanza.attribute('previd') } }); exports.Resumed = stanza.define({ name: 'smResumed', eventName: 'stream:management:resumed', namespace: NS, element: 'resumed', topLevel: true, fields: { h: util.numberAttribute('h', '0'), 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: util.numberAttribute('h', '0') } }); exports.Request = stanza.define({ name: 'smRequest', eventName: 'stream:management:request', namespace: NS, element: 'r', topLevel: true }); stanza.extend(StreamFeatures, exports.SMFeature); },{"./streamFeatures":50,"./util":52,"jxt":77}],48:[function(require,module,exports){ 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":52,"jxt":77}],49:[function(require,module,exports){ 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":77,"underscore":96}],50:[function(require,module,exports){ 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":77}],51:[function(require,module,exports){ 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: util.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":35,"./util":52,"jxt":77}],52:[function(require,module,exports){ var stanza = require('jxt'); var JID = require('../jid'); var XML_NS = 'http://www.w3.org/XML/1998/namespace'; exports.langAttribute = stanza.field( function (xml) { return xml.getAttributeNS(XML_NS, 'lang') || ''; }, function (xml, value) { xml.setAttributeNS(XML_NS, 'lang', value); } ); 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()); } ); exports.b64Text = stanza.field( function (xml) { if (xml.textContent && xml.textContent != '=') { return atob(xml.textContent); } return ''; }, function (xml, value) { xml.textContent = btoa(value) || '='; } ); exports.dateAttribute = stanza.field( function (xml, attr) { return new Date(stanza.getAttribute(xml, attr) || Date.now()); }, function (xml, attr, value) { if (!value) return; stanza.setAttribute(xml, attr, value.toISOString()); } ); exports.dateSub = stanza.field( function (xml, NS, sub) { return new Date(stanza.getSubText(xml, NS, sub) || Date.now()); }, function (xml, NS, sub, value) { if (!value) return; stanza.setSubText(xml, NS, sub, value.toISOString()); } ); exports.numberAttribute = stanza.field( function (xml, attr, defaultVal) { return parseInt(stanza.getAttribute(xml, attr, defaultVal), 10); }, function (xml, attr, value) { stanza.setAttribute(xml, attr, value.toString()); } ); exports.numberSub = stanza.field( function (xml, NS, sub, defaultVal) { return parseInt(stanza.getSubText(xml, NS, sub, defaultVal), 10); }, function (xml, NS, sub, value) { stanza.setSubText(xml, NS, sub, value.toString()); } ); },{"../jid":3,"jxt":77}],53:[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":35,"jxt":77}],54:[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":35,"jxt":77}],55:[function(require,module,exports){ var _ = require('underscore'); 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.emit('raw:outgoing', data); self.sm.track(data); if (typeof data !== 'string') { data = data.toString(); } self.conn.send(data); } cb(); }, 1); function wrap(data) { var result = [self.streamStart, data, self.streamEnd].join(''); return result; } function parse(data) { var nodes = (self.parser.parseFromString(data, 'application/xml')).childNodes; for (var i = 0; i < nodes.length; i++) { if (nodes[i].nodeType === 1) { return nodes[i]; } } } 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 = new Stream({}, parse(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 = new Stream({}, parse(data + self.streamEnd)); } catch (e) { try { streamData = new Stream({}, parse(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.parser = new DOMParser(); self.serializer = new XMLSerializer(); 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":22,"./stanza/iq":35,"./stanza/message":37,"./stanza/presence":39,"./stanza/stream":48,"async":56,"node-uuid":82,"underscore":96,"wildemitter":97}],56:[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