1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-11-26 17:03:12 +03:00
Files
matrix-js-sdk/dist/0.3.0/browser-matrix-0.3.0.min.js
2015-10-28 16:54:07 +00:00

5 lines
101 KiB
JavaScript

!function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){var n=t[s][1][e];return o(n?n:e)},d,d.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(e,t){(function(n){var r=e("./lib/matrix");r.request(e("browser-request")),t.exports=r,n.matrixcs=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/matrix":5,"browser-request":20}],2:[function(e,t){"use strict";function n(e){if(O.checkObjectHasKeys(e,["baseUrl","request"]),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.store=e.store||new C,this.sessionStore=e.sessionStore||null,this.accountKey="DEFAULT_KEY",this.deviceId=e.deviceId,P&&null!==this.sessionStore){var t=this.sessionStore.getEndToEndAccount(),n=new q.Account;try{null===t?n.create():n.unpickle(this.accountKey,t);var r=JSON.parse(n.identity_keys()),o='{"algorithms":["'+N+'"]';o+=',"device_id":"'+this.deviceId+'"',o+=',"keys":',o+='{"ed25519:'+this.deviceId+'":',o+=JSON.stringify(r.ed25519),o+=',"curve25519:'+this.deviceId+'":',o+=JSON.stringify(r.curve25519),o+="}",o+=',"user_id":'+JSON.stringify(e.userId),o+="}";var i=n.sign(o);this.deviceKeys=JSON.parse(o);var s={};s[e.userId]={},s[e.userId]["ed25519:"+this.deviceId]=i,this.deviceKeys.signatures=s,this.deviceCurve25519Key=r.curve25519;var u=n.pickle(this.accountKey);this.sessionStore.storeEndToEndAccount(u);var c=this.sessionStore.getEndToEndDevicesForUser(e.userId)||{};c[e.deviceId]=this.deviceKeys,this.sessionStore.storeEndToEndDevicesForUser(e.userId,c)}finally{n.free()}}if(this.scheduler=e.scheduler,this.scheduler){var d=this;this.scheduler.setProcessFunction(function(e){return e.status=x.SENDING,a(d,e)})}this.clientRunning=!1;var l={baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,request:e.request,prefix:I.PREFIX_V1,onlyData:!0,extraParams:e.queryParams};this.credentials={userId:e.userId||null},this._http=new I.MatrixHttpApi(l),this._syncingRooms={},this.callList={},this._config={};var p=M.createNewMatrixCall(this);this._supportsVoip=!1,p&&(v(this),this._supportsVoip=!0)}function r(e,t,n,r,o){if(!e.sessionStore)throw new Error("Client must have an end-to-end session store to encrypt messages");if(n.algorithm===N){for(var i=[],s=0;s<n.members.length;++s){var a=n.members[s],u=e.sessionStore.getEndToEndDevicesForUser(a);for(var c in u)if(u.hasOwnProperty(c)){var d=u[c];for(var l in d.keys)0===l.indexOf("curve25519:")&&i.push(d.keys[l])}}i.sort();var p="",f={room_id:t,type:r,fingerprint:p,sender_device:e.deviceId,content:o},h={},m=JSON.stringify(f);for(s=0;s<i.length;++s){var v=i[s];if(v!=e.deviceCurve25519Key){var y=e.sessionStore.getEndToEndSessions(v),g=[];for(var _ in y)y.hasOwnProperty(_)&&g.push(_);if(g.sort(),0!==g.length){_=g[0];var E=new q.Session;try{E.unpickle(e.accountKey,y[_]),h[v]=E.encrypt(m);var S=E.pickle(e.accountKey);e.sessionStore.storeEndToEndSession(v,_,S)}finally{E.free()}}}}var w={algorithm:n.algorithm,sender_key:e.deviceCurve25519Key,ciphertext:h};return w}throw new Error("Unknown end-to-end algorithm: "+n.algorithm)}function o(e,t){if(null===e.sessionStore||!P)return i(t,"**Encryption not enabled**");var n=t.getContent();if(n.algorithm===N){var r=n.sender_key,o=n.ciphertext;if(!o)return i(t,"**Missing ciphertext**");if(!(e.deviceCurve25519Key in n.ciphertext))return i(t,"**Not included in recipients**");var s,a=n.ciphertext[e.deviceCurve25519Key],u=e.sessionStore.getEndToEndSessions(r),c=null,d=!1;for(var l in u)if(u.hasOwnProperty(l)){s=new q.Session;try{s.unpickle(e.accountKey,u[l]),0===a.type&&s.matches_inbound(a.body)&&(d=!0),c=s.decrypt(a.type,a.body);var p=s.pickle(e.accountKey);e.sessionStore.storeEndToEndSession(r,l,p)}catch(f){console.log("Failed to decrypt with an existing session: "+f.message)}finally{s.free()}}if(0===a.type&&!d&&null===c){var h=new q.Account;s=new q.Session;try{var m=e.sessionStore.getEndToEndAccount();h.unpickle(e.accountKey,m),s.create_inbound_from(h,r,a.body),c=s.decrypt(a.type,a.body),h.remove_one_time_keys(s);var v=s.pickle(e.accountKey),y=h.pickle(e.accountKey);l=s.session_id(),e.sessionStore.storeEndToEndSession(r,l,v),e.sessionStore.storeEndToEndAccount(y)}catch(f){}finally{s.free(),h.free()}}if(null!==c){var g=JSON.parse(c);return new k({origin_server_ts:t.getTs(),room_id:g.room_id,user_id:t.getSender(),event_id:t.getId(),type:g.type,content:g.content},"encrypted")}return i(t,"**Bad Encrypted Message**")}}function i(e,t){return new k({type:"m.room.message",origin_server_ts:e.getTs(),room_id:e.getRoomId(),user_id:e.getSender(),event_id:e.getId(),content:{msgtype:"m.bad.encrypted",body:t,content:e.getContent()}})}function s(e,t,n,r){var o,i=R.defer();return e.scheduler&&(o=e.scheduler.queueEvent(n),o&&e.scheduler.getQueueForEvent(n).length>1&&(n.status=x.QUEUED)),o||(o=a(e,n)),o.done(function(e){if(t){var o=e.event_id,s=O.findElement(t.timeline,function(e){return e.getId()===o},!0);s?(n.encryptedType&&(s.event.content=n.event.content,s.event.type=n.event.type),O.removeElement(t.timeline,function(e){return e.getId()===n.getId()},!0)):(n.event.event_id=e.event_id,n.status=null)}S(r,i,e)},function(e){n.status=x.NOT_SENT,E(r,i,e)}),i.promise}function a(e,t){var n,r={$roomId:t.getRoomId(),$eventType:t.getWireType(),$stateKey:t.getStateKey(),$txnId:t._txnId?t._txnId:(new Date).getTime()};if(t.isState()){var o="/rooms/$roomId/state/$eventType";t.getStateKey()&&t.getStateKey().length>0&&(o="/rooms/$roomId/state/$eventType/$stateKey"),n=O.encodeUri(o,r)}else n=O.encodeUri("/rooms/$roomId/send/$eventType/$txnId",r);return e._http.authedRequest(void 0,"PUT",n,void 0,t.getWireContent())}function u(e,t,n,r,o,i){O.isFunction(o)&&(i=o,o=void 0);var s=O.encodeUri("/rooms/$roomId/state/m.room.member/$userId",{$roomId:t,$userId:n});return e._http.authedRequest(i,"PUT",s,void 0,{membership:r,reason:o})}function c(e,t,n,r,o,i){O.isFunction(o)&&(i=o,o=void 0);var s=O.encodeUri("/rooms/$room_id/$membership",{$room_id:t,$membership:r});return e._http.authedRequest(i,"POST",s,void 0,{user_id:n,reason:o})}function d(e,t,n){var r={limit:t};n&&(r.archived=!0),e._http.authedRequest(void 0,"GET","/initialSync",r).done(function(t){var n,r;if(!(e.store instanceof C)){O.forEach(O.map(t.presence,w(e)),function(t){var n=g(e,t.getContent().user_id);n.setPresenceEvent(t),e.store.storeUser(n)});var o={};for(t.receipts=t.receipts||[],O.forEach(t.receipts.map(w(e)),function(e){o[e.getRoomId()]||(o[e.getRoomId()]=[]),o[e.getRoomId()].push(e)}),n=0;n<t.rooms.length;n++){var i=_(e,t.rooms[n].room_id);if(t.rooms[n].state||(t.rooms[n].state=[]),"invite"===t.rooms[n].membership){var s=t.rooms[n].invite;s||(s={event_id:"$fake_"+i.roomId,content:{membership:"invite"},state_key:e.credentials.userId,user_id:t.rooms[n].inviter,room_id:i.roomId,type:"m.room.member"}),t.rooms[n].state.push(s)}f(e,i,t.rooms[n].state,t.rooms[n].messages);var a=o[i.roomId]||[];for(r=0;r<a.length;r++)i.addReceipt(a[r]);i.recalculate(e.credentials.userId),e.store.storeRoom(i),e.emit("Room",i)}}if(t){e.store.setSyncToken(t.end);var u=[];for(n=0;n<t.presence.length;n++)u.push(new k(t.presence[n]));for(n=0;n<t.rooms.length;n++){if(t.rooms[n].state)for(r=0;r<t.rooms[n].state.length;r++)u.push(new k(t.rooms[n].state[r]));if(t.rooms[n].messages)for(r=0;r<t.rooms[n].messages.chunk.length;r++)u.push(new k(t.rooms[n].messages.chunk[r]))}O.forEach(u,function(t){e.emit("event",t)})}e.clientRunning=!0,e.emit("syncComplete"),l(e)},function(t){console.error("/initialSync error: %s",t),e.emit("syncError",t)})}function l(e){var t=e;if(e.clientRunning){var n=!1,r=setTimeout(function(){n=!0,console.error("/events request timed out."),l(e)},4e4);e._http.authedRequest(void 0,"GET","/events",{from:e.store.getSyncToken(),timeout:3e4}).done(function(e){if(!n){clearTimeout(r);var o=[];if(e&&(o=O.map(e.chunk,w(t))),!(t.store instanceof C)){var i={},s=0,a={};for(s=0;s<o.length;s++){var u=o[s].getRoomId();if(u)a[u]||(a[u]=[]),a[u].push(o[s]),"m.room.member"===o[s].getType()&&"invite"===o[s].getContent().membership&&(i[u]=!0);else if("m.presence"===o[s].getType()){var c=t.store.getUser(o[s].getContent().user_id);c?c.setPresenceEvent(o[s]):(c=g(t,o[s].getContent().user_id),c.setPresenceEvent(o[s]),t.store.storeUser(c))}}var d=O.keys(a);O.forEach(d,function(e){var n=t.store.getRoom(e),r=!1;n||(n=_(t,e),r=!0);var o=n.hasMembershipState(t.credentials.userId,"join");n.addEvents(a[e],"replace"),n.recalculate(t.credentials.userId),r&&(t.store.storeRoom(n),t.emit("Room",n));var i=n.hasMembershipState(t.credentials.userId,"join");!o&&i&&p(t,n)}),Object.keys(i).forEach(function(e){m(t,t.store.getRoom(e))})}e&&(t.store.setSyncToken(e.end),O.forEach(o,function(e){t.emit("event",e)})),l(t)}},function(e){console.error("/events error: %s",JSON.stringify(e)),n||(clearTimeout(r),t.emit("syncError",e),setTimeout(function(){l(t)},2e3))})}}function p(e,t){if(e._syncingRooms[t.roomId])return e._syncingRooms[t.roomId];var n=R.defer();return e._syncingRooms[t.roomId]=n.promise,e.roomInitialSync(t.roomId,8).done(function(r){t.timeline=[],f(e,t,r.state,r.messages),t.recalculate(e.credentials.userId),e.store.storeRoom(t),e.emit("Room",t),n.resolve(t),e._syncingRooms[t.roomId]=void 0},function(r){n.reject(r),e._syncingRooms[t.roomId]=void 0}),n.promise}function f(e,t,n,r){var o=O.map(O.deepCopy(n),w(e)),i=O.map(n,w(e));t.oldState.setStateEvents(o),t.currentState.setStateEvents(i),m(e,t),t.addEventsToTimeline(O.map(r?r.chunk:[],w(e)).reverse(),!0),r&&(t.oldState.paginationToken=r.start)}function h(e,t,n){O.forEach(n,function(n){t.on(n,function(){for(var t=[n],r=0;r<arguments.length;r++)t.push(arguments[r]);e.emit.apply(e,t)})})}function m(e,t){t&&e._config.resolveInvitesToProfiles&&t.getMembersWithMembership("invite").forEach(function(n){if(!n._requestedProfileInfo){n._requestedProfileInfo=!0;var r,o=e.getUser(n.userId);r=o?R({avatar_url:o.avatarUrl,displayname:o.displayName}):e.getProfileInfo(n.userId),r.done(function(e){var r=n.events.member;"invite"===r.getContent().membership&&(r.getContent().avatar_url=e.avatar_url,r.getContent().displayname=e.displayname,n.setMembershipEvent(r,t.currentState))},function(){})}})}function v(e){var t={};e.on("event",function(n){if(0===n.getType().indexOf("m.call.")){var r,o=n.getContent(),i=o.call_id?e.callList[o.call_id]:void 0;if("m.call.invite"===n.getType()){if(n.getSender()===e.credentials.userId)return;if(n.getAge()>o.lifetime)return;if(i&&"ended"===i.state)return;if(i&&console.log("WARN: Already have a MatrixCall with id %s but got an invite. Clobbering.",o.call_id),i=M.createNewMatrixCall(e,n.getRoomId()),!i)return void console.log("Incoming call ID "+o.call_id+" but this client doesn't support WebRTC");if(i.callId=o.call_id,i._initWithInvite(n),e.callList[i.callId]=i,t[i.callId])for(r=0;r<t[i.callId].length;r++)i._gotRemoteIceCandidate(t[i.callId][r]);var s,a=O.values(e.callList);for(r=0;r<a.length;++r){var u=a[r];if(i.room_id===u.room_id&&"outbound"===u.direction&&-1!==["wait_local_media","create_offer","invite_sent"].indexOf(u.state)){s=u;break}}s?"wait_local_media"===s.state||"create_offer"===s.state||s.callId>i.callId?(console.log("Glare detected: answering incoming call "+i.callId+" and canceling outgoing call "+s.callId),s._replacedBy(i),i.answer()):(console.log("Glare detected: rejecting incoming call "+i.callId+" and keeping outgoing call "+s.callId),i.hangup()):e.emit("Call.incoming",i)}else if("m.call.answer"===n.getType()){if(!i)return;n.getSender()===e.credentials.userId?"ringing"===i.state&&i._onAnsweredElsewhere(o):i._receivedAnswer(o)}else if("m.call.candidates"===n.getType()){if(n.getSender()===e.credentials.userId)return;if(i)for(r=0;r<o.candidates.length;r++)i._gotRemoteIceCandidate(o.candidates[r]);else t[o.call_id]||(t[o.call_id]=[]),t[o.call_id]=t[o.call_id].concat(o.candidates)}else"m.call.hangup"===n.getType()&&(i?"ended"!==i.state&&(i._onHangupReceived(o),delete e.callList[o.call_id]):(i=M.createNewMatrixCall(e,n.getRoomId()),i&&(i.callId=o.call_id,i._initWithHangup(n),e.callList[o.call_id]=i)))}})}function y(e){e._supportsVoip&&e.turnServer().done(function(t){if(t.uris){console.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");var n={urls:t.uris,username:t.username,credential:t.password};e._turnServers=[n],setTimeout(function(){y(e)},1e3*(t.ttl||3600)*.9)}},function(){console.error("Failed to get TURN URIs"),setTimeout(function(){y(e)},6e4)})}function g(e,t){var n=new U(t);return h(e,n,["User.avatarUrl","User.displayName","User.presence"]),n}function _(e,t){var n=new A(t);return h(e,n,["Room.name","Room.timeline"]),h(e,n.currentState,["RoomState.events","RoomState.members","RoomState.newMember"]),n.currentState.on("RoomState.newMember",function(t,n,r){r.user=e.getUser(r.userId),h(e,r,["RoomMember.name","RoomMember.typing","RoomMember.powerLevel","RoomMember.membership"])}),n}function E(e,t,n){e&&e(n),t.reject(n)}function S(e,t,n){e&&e(null,n),t.resolve(n)}function w(e){function t(t){var n=new k(t);return"m.room.encrypted"===n.getType()?o(e,n):n}return t}var b=e("./pushprocessor"),T=e("events").EventEmitter,R=e("q"),I=e("./http-api"),k=e("./models/event").MatrixEvent,x=e("./models/event").EventStatus,C=e("./store/stub"),A=e("./models/room"),U=e("./models/user"),M=e("./webrtc/call"),O=e("./utils"),L=e("./content-repo"),P=!1;try{var q=e("olm");q.Account&&q.Session&&(P=!0)}catch(j){}var N="m.olm.v1.curve25519-aes-sha2";O.inherits(n,T),n.prototype.getHomeserverUrl=function(){return this.baseUrl},n.prototype.getIdentityServerUrl=function(){return this.idBaseUrl},n.prototype.isCryptoEnabled=function(){return P&&null!==this.sessionStore},n.prototype.uploadKeys=function(e,t){if(!P||null===this.sessionStore)return R.reject(new Error("End-to-end encryption disabled"));var n=void 0===t;t=t||R.defer();var r="/keys/upload/"+this.deviceId,o=this.sessionStore.getEndToEndAccount();if(!o)return R.reject(new Error("End-to-end account not found"));var i,s=new q.Account;try{s.unpickle(this.accountKey,o),i=JSON.parse(s.one_time_keys());var a=s.max_number_of_one_time_keys()}finally{s.free()}var u={};for(var c in i.curve25519)i.curve25519.hasOwnProperty(c)&&(u["curve25519:"+c]=i.curve25519[c]);var d={device_keys:this.deviceKeys,one_time_keys:u},l=this;return this._http.authedRequestWithPrefix(void 0,"POST",r,void 0,d,I.PREFIX_V2_ALPHA).then(function(r){var o=Math.floor(a/2),i=r.one_time_key_counts.curve25519||0,s=o>i,u=l.sessionStore.getEndToEndAccount(),c=new q.Account;try{if(c.unpickle(l.accountKey,u),c.mark_keys_as_published(),s){var d=o-i;e&&(d=Math.min(d,e)),c.generate_one_time_keys(d)}u=c.pickle(l.accountKey),l.sessionStore.storeEndToEndAccount(u)}finally{c.free()}s&&n?l.uploadKeys(e,t):t.resolve()}),t.promise},n.prototype.downloadKeys=function(e,t){if(!P||null===this.sessionStore)return R.reject(new Error("End-to-end encryption disabled"));for(var n={},r={},o=!1,i=0;i<e.length;++i){var s=e[i];if(!t){var a=this.sessionStore.getEndToEndDevicesForUser(s);if(a){n[s]=a;continue}}o=!0,r[s]={}}var u=R.defer();if(o){var c="/keys/query",d={device_keys:r},l=this;this._http.authedRequestWithPrefix(void 0,"POST",c,void 0,d,I.PREFIX_V2_ALPHA).then(function(e){for(var t in e.device_keys)t in r&&(l.sessionStore.storeEndToEndDevicesForUser(t,e.device_keys[t]),n[t]=e.device_keys[t]);u.resolve(n)})}else u.resolve(n);return u.promise},n.prototype.listDeviceKeys=function(e){if(!P)return[];var t=this.sessionStore.getEndToEndDevicesForUser(e),n=[];if(t){var r,o=[];for(r in t)t.hasOwnProperty(r)&&o.push(r);o.sort();for(var i=0;i<o.length;++i){r=o[i];var s=t[r],a=s.keys["ed25519:"+r];a&&n.push({id:r,key:a})}}return n},n.prototype.setRoomEncryption=function(e,t){if(!this.sessionStore||!P)return R.reject(new Error("End-to-End encryption disabled"));if(t.algorithm===N){if(!t.members)throw new Error("Config must include a 'members' list with a list of userIds");for(var n=[],r=[],o=0;o<t.members.length;++o){var i=t.members[o],s=this.sessionStore.getEndToEndDevicesForUser(i);if(s){for(var a in s)if(s.hasOwnProperty(a)){var u=s[a],c=u.keys["curve25519:"+a];if(c==this.deviceCurve25519Key)continue;this.sessionStore.getEndToEndSessions(c)||n.push([i,a,c])}}else r.push(i)}var d=R.defer();if(n.length>0){var l={};for(o=0;o<n.length;++o){var p=n[o],f=l[p[0]]||{};l[p[0]]=f,f[p[1]]="curve25519"}var h="/keys/claim",m={one_time_keys:l},v=this;this._http.authedRequestWithPrefix(void 0,"POST",h,void 0,m,I.PREFIX_V2_ALPHA).done(function(e){var t={};for(o=0;o<n.length;++o){var i,s=n[o],a=e.one_time_keys[s[0]]||{},u=a[s[1]];for(var c in u)0===c.indexOf("curve25519:")&&(i=u[c]);if(i){var l=new q.Session,p=new q.Account;try{var f=v.sessionStore.getEndToEndAccount();p.unpickle(v.accountKey,f),l.create_outbound(p,s[2],i);var h=l.session_id();f=l.pickle(v.accountKey),v.sessionStore.storeEndToEndSession(s[2],h,f)}finally{l.free(),p.free()}}else t[s[0]]=t[s[0]]||[],t[s[0]].push([s[1]])}d.resolve({missingUsers:r,missingDevices:t})})}else d.resolve({missingUsers:r,missingDevices:[]});return this.sessionStore.storeEndToEndRoom(e,t),d.promise}throw new Error("Unknown algorithm: "+t.algorithm)},n.prototype.disableRoomEncryption=function(e){null!==this.sessionStore&&this.sessionStore.storeEndToEndRoom(e,null)},n.prototype.isRoomEncrypted=function(e){return P&&null!==this.sessionStore?this.sessionStore.getEndToEndRoom(e)&&!0||!1:!1},n.prototype.getRoom=function(e){return this.store.getRoom(e)},n.prototype.getRooms=function(){return this.store.getRooms()},n.prototype.getUser=function(e){return this.store.getUser(e)},n.prototype.createRoom=function(e,t){return this._http.authedRequest(t,"POST","/createRoom",void 0,e)},n.prototype.joinRoom=function(e,t,n){if(O.isFunction(t))throw new Error("Expected 'opts' object, got function.");t=t||{syncRoom:!0};var r=this.getRoom(e);if(r&&r.hasMembershipState(this.credentials.userId,"join"))return R(r);var o=O.encodeUri("/join/$roomid",{$roomid:e}),i=R.defer(),s=this;return this._http.authedRequest(void 0,"POST",o,void 0,{}).then(function(e){var n=e.room_id,r=_(s,n);return t.syncRoom?p(s,r):R(r)},function(e){E(n,i,e)}).done(function(e){S(n,i,e)},function(e){E(n,i,e)}),i.promise},n.prototype.resendEvent=function(e,t){return e.status=x.SENDING,s(this,t,e)},n.prototype.setRoomName=function(e,t,n){return this.sendStateEvent(e,"m.room.name",{name:t},void 0,n)},n.prototype.setRoomTopic=function(e,t,n){return this.sendStateEvent(e,"m.room.topic",{topic:t},void 0,n)},n.prototype.setPowerLevel=function(e,t,n,r,o){var i={users:{}};r&&"m.room.power_levels"===r.getType()&&(i=O.deepCopy(r.getContent())),i.users[t]=n;var s=O.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this._http.authedRequest(o,"PUT",s,void 0,i)},n.prototype.getStateEvent=function(e,t,n,r){var o={$roomId:e,$eventType:t,$stateKey:n},i=O.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==n&&(i=O.encodeUri(i+"/$stateKey",o)),this._http.authedRequest(r,"GET",i)},n.prototype.sendStateEvent=function(e,t,n,r,o){var i={$roomId:e,$eventType:t,$stateKey:r},s=O.encodeUri("/rooms/$roomId/state/$eventType",i);return void 0!==r&&(s=O.encodeUri(s+"/$stateKey",i)),this._http.authedRequest(o,"PUT",s,void 0,n)},n.prototype.sendEvent=function(e,t,n,o,i){O.isFunction(o)&&(i=o,o=void 0),o||(o="m"+(new Date).getTime());var a=this.getRoom(e),u=new k({event_id:"~"+e+":"+o,user_id:this.credentials.userId,room_id:e,type:t,origin_server_ts:(new Date).getTime(),content:n});if(u._txnId=o,a&&(u.status=x.SENDING,a.addEventsToTimeline([u])),"m.room.message"===t&&this.sessionStore&&P){var c=this.sessionStore.getEndToEndRoom(e);if(c){var d=r(this,e,c,t,n,o,i);u.encryptedType="m.room.encrypted",u.encryptedContent=d}u.encrypted=!0}return s(this,a,u,i)},n.prototype.sendMessage=function(e,t,n,r){return O.isFunction(n)&&(r=n,n=void 0),this.sendEvent(e,"m.room.message",t,n,r)},n.prototype.sendTextMessage=function(e,t,n,r){var o={msgtype:"m.text",body:t};return this.sendMessage(e,o,n,r)},n.prototype.sendNotice=function(e,t,n,r){var o={msgtype:"m.notice",body:t};return this.sendMessage(e,o,n,r)},n.prototype.sendEmoteMessage=function(e,t,n,r){var o={msgtype:"m.emote",body:t};return this.sendMessage(e,o,n,r)},n.prototype.sendImageMessage=function(e,t,n,r,o){O.isFunction(r)&&(o=r,r=void 0),r||(r="Image");var i={msgtype:"m.image",url:t,info:n,body:r};return this.sendMessage(e,i,o)},n.prototype.sendHtmlMessage=function(e,t,n,r){var o={msgtype:"m.text",format:"org.matrix.custom.html",body:t,formatted_body:n};return this.sendMessage(e,o,r)},n.prototype.sendHtmlNotice=function(e,t,n,r){var o={msgtype:"m.notice",format:"org.matrix.custom.html",body:t,formatted_body:n};return this.sendMessage(e,o,r)},n.prototype.sendReceipt=function(e,t,n){var r=O.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()});return this._http.authedRequestWithPrefix(n,"POST",r,void 0,{},I.PREFIX_V2_ALPHA)},n.prototype.sendReadReceipt=function(e,t){return this.sendReceipt(e,"m.read",t)},n.prototype.uploadContent=function(e,t){return this._http.uploadContent(e,t)},n.prototype.sendTyping=function(e,t,n,r){var o=O.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.credentials.userId}),i={typing:t};return t&&(i.timeout=n?n:2e4),this._http.authedRequest(r,"PUT",o,void 0,i)},n.prototype.createAlias=function(e,t,n){var r=O.encodeUri("/directory/room/$alias",{$alias:e}),o={room_id:t};return this._http.authedRequest(n,"PUT",r,void 0,o)},n.prototype.getRoomIdForAlias=function(e,t){var n=O.encodeUri("/directory/room/$alias",{$alias:e});return this._http.authedRequest(t,"GET",n)},n.prototype.redactEvent=function(e,t,n){var r=O.encodeUri("/rooms/$roomId/redact/$eventId",{$roomId:e,$eventId:t});return this._http.authedRequest(n,"POST",r,void 0,{})},n.prototype.invite=function(e,t,n){return c(this,e,t,"invite",void 0,n)},n.prototype.leave=function(e,t){return c(this,e,void 0,"leave",void 0,t)},n.prototype.ban=function(e,t,n,r){return c(this,e,t,"ban",n,r)},n.prototype.unban=function(e,t,n){return u(this,e,t,"leave",void 0,n)},n.prototype.kick=function(e,t,n,r){return u(this,e,t,"leave",n,r)},n.prototype.getPushActionsForEvent=function(e){if(void 0===e._pushActions){var t=new b(this);e._pushActions=t.actionsForEvent(e.event)}return e._pushActions},n.prototype.getProfileInfo=function(e,t,n){O.isFunction(t)&&(n=t,t=void 0);var r=t?O.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):O.encodeUri("/profile/$userId",{$userId:e});return this._http.authedRequest(n,"GET",r)},n.prototype.setProfileInfo=function(e,t,n){var r=O.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this._http.authedRequest(n,"PUT",r,void 0,t)},n.prototype.setDisplayName=function(e,t){return this.setProfileInfo("displayname",{displayname:e},t)},n.prototype.setAvatarUrl=function(e,t){return this.setProfileInfo("avatar_url",{avatar_url:e},t)},n.prototype.mxcUrlToHttp=function(e,t,n,r){return L.getHttpUriForMxc(this.baseUrl,e,t,n,r)},n.prototype.getThreePids=function(e){var t="/account/3pid";return this._http.authedRequestWithPrefix(e,"GET",t,void 0,void 0,I.PREFIX_V2_ALPHA)},n.prototype.addThreePid=function(e,t,n){var r="/account/3pid",o={threePidCreds:e,bind:t};return this._http.authedRequestWithPrefix(n,"POST",r,null,o,I.PREFIX_V2_ALPHA)},n.prototype.setPassword=function(e,t,n){var r="/account/password",o={auth:e,new_password:t};return this._http.authedRequestWithPrefix(n,"POST",r,null,o,I.PREFIX_V2_ALPHA)},n.prototype.setPresence=function(e,t){var n=O.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId}),r=["offline","online","unavailable"];if(-1==r.indexOf(e))throw new Error("Bad presence value: "+e);var o={presence:e};return this._http.authedRequest(t,"PUT",n,void 0,o)},n.prototype.publicRooms=function(e){return this._http.request(e,"GET","/publicRooms")},n.prototype.loginFlows=function(e){return this._http.request(e,"GET","/login")},n.prototype.resolveRoomAlias=function(e,t){var n=O.encodeUri("/directory/room/$alias",{$alias:e});return this._http.request(t,"GET",n)},n.prototype.roomInitialSync=function(e,t,n){O.isFunction(t)&&(n=t,t=void 0);var r=O.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return t||(t=30),this._http.authedRequest(n,"GET",r,{limit:t})},n.prototype.roomState=function(e,t){var n=O.encodeUri("/rooms/$roomId/state",{$roomId:e});return this._http.authedRequest(t,"GET",n)},n.prototype.scrollback=function(e,t,n){if(O.isFunction(t)&&(n=t,t=void 0),t=t||30,null===e.oldState.paginationToken)return R(e);var r=this.store.scrollback(e,t).length;if(r===t)return R(e);t-=r;var o=O.encodeUri("/rooms/$roomId/messages",{$roomId:e.roomId}),i={from:e.oldState.paginationToken,limit:t,dir:"b"},s=R.defer(),a=this;return this._http.authedRequest(n,"GET",o,i).done(function(r){var o=O.map(r.chunk,w(a));e.addEventsToTimeline(o,!0),e.oldState.paginationToken=r.end,r.chunk.length<t&&(e.oldState.paginationToken=null),a.store.storeEvents(e,o,r.end,!0),S(n,s,e)},function(e){E(n,s,e)}),s.promise},n.prototype.login=function(e,t,n){return t.type=e,this._http.authedRequest(n,"POST","/login",void 0,t)},n.prototype.register=function(e,t,n,r,o){void 0===r&&(r={}),n&&(r.session=n);var i={auth:r};return void 0!==e&&(i.username=e),void 0!==t&&(i.password=t),this._http.requestWithPrefix(o,"POST","/register",void 0,i,I.PREFIX_V2_ALPHA)},n.prototype.loginWithPassword=function(e,t,n){return this.login("m.login.password",{user:e,password:t},n)},n.prototype.loginWithSAML2=function(e,t){return this.login("m.login.saml2",{relay_state:e},t)},n.prototype.getCasServer=function(e){return this._http.request(e,"GET","/login/cas",void 0,void 0)},n.prototype.loginWithCas=function(e,t,n){return this.login("m.login.cas",{ticket:e,service:t},n)},n.prototype.pushRules=function(e){return this._http.authedRequest(e,"GET","/pushrules/")},n.prototype.addPushRule=function(e,t,n,r,o){var i=O.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this._http.authedRequest(o,"PUT",i,void 0,r)},n.prototype.deletePushRule=function(e,t,n,r){var o=O.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this._http.authedRequest(r,"DELETE",o)},n.prototype.searchMessageText=function(e,t){return this.search({body:{search_categories:{room_events:{keys:e.keys,search_term:e.query}}}},t)},n.prototype.search=function(e,t){return this._http.authedRequest(t,"POST","/search",void 0,e.body)},n.prototype.turnServer=function(e){return this._http.authedRequest(e,"GET","/voip/turnServer")},n.prototype.getTurnServers=function(){return this._turnServers||[]},n.prototype.isLoggedIn=function(){return void 0!==this._http.opts.accessToken},n.prototype.startClient=function(e){if(!this.clientRunning){if("number"==typeof e&&(e={initialSyncLimit:e}),e=e||{},e.initialSyncLimit=e.initialSyncLimit||8,e.includeArchivedRooms=e.includeArchivedRooms||!1,e.resolveInvitesToProfiles=e.resolveInvitesToProfiles||!1,this._config=e,P&&null!==this.sessionStore&&this.uploadKeys(5),this.store.getSyncToken())return void l(this);y(this);var t=this;this.pushRules().done(function(n){t.pushRules=n,d(t,e.initialSyncLimit,e.includeArchivedRooms)},function(e){t.emit("syncError",e)})}},n.prototype.stopClient=function(){this.clientRunning=!1},n.prototype.requestEmailToken=function(e,t,n,r,o){var i={client_secret:t,email:e,send_attempt:n,next_link:r};return this._http.idServerRequest(o,"POST","/validate/email/requestToken",i,I.PREFIX_IDENTITY_V1)},n.prototype.generateClientSecret=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=0;32>n;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},t.exports.MatrixClient=n,t.exports.CRYPTO_ENABLED=P},{"./content-repo":3,"./http-api":4,"./models/event":6,"./models/room":10,"./models/user":11,"./pushprocessor":12,"./store/stub":16,"./utils":18,"./webrtc/call":19,events:21,olm:void 0,q:23}],3:[function(e,t){var n=e("./utils");t.exports={getHttpUriForMxc:function(e,t,r,o,i){if("string"!=typeof t||!t)return t;if(0!==t.indexOf("mxc://"))return t;var s=t.slice(6),a="/_matrix/media/v1/download/",u={};r&&(u.width=r),o&&(u.height=o),i&&(u.method=i),n.keys(u).length>0&&(a="/_matrix/media/v1/thumbnail/");var c=s.indexOf("#"),d="";return c>=0&&(d=s.substr(c),s=s.substr(0,c)),e+a+s+(0===n.keys(u).length?"":"?"+n.encodeParams(u))+d},getIdenticonUri:function(e,t,r,o){if(!t)return null;r||(r=96),o||(o=96);var i={width:r,height:o},s=n.encodeUri("/_matrix/media/v1/identicon/$ident",{$ident:t});return e+s+(0===n.keys(i).length?"":"?"+n.encodeParams(i))}}},{"./utils":18}],4:[function(e,t){(function(n){"use strict";var r=e("q"),o=e("./utils");t.exports.PREFIX_V1="/_matrix/client/api/v1",t.exports.PREFIX_V2_ALPHA="/_matrix/client/v2_alpha",t.exports.PREFIX_IDENTITY_V1="/_matrix/identity/api/v1",t.exports.MatrixHttpApi=function(e){o.checkObjectHasKeys(e,["baseUrl","request","prefix"]),e.onlyData=e.onlyData||!1,this.opts=e},t.exports.MatrixHttpApi.prototype={getContentUri:function(){var e={access_token:this.opts.accessToken};return{base:this.opts.baseUrl,path:"/_matrix/media/v1/upload",params:e}},uploadContent:function(e,t){if(void 0!==t&&!o.isFunction(t))throw Error("Expected callback to be a function but got "+typeof t);var s=r.defer(),a=this.opts.baseUrl+"/_matrix/media/v1/upload";if(n.XMLHttpRequest){var u=new n.XMLHttpRequest,c=i(s,t,this.opts.onlyData),d=function(){u.abort(),c(new Error("Timeout"))};u.timeout_timer=setTimeout(d,3e4),u.onreadystatechange=function(){switch(u.readyState){case n.XMLHttpRequest.DONE:if(clearTimeout(u.timeout_timer),!u.responseText)return void c(new Error("No response body."));var e=JSON.parse(u.responseText);if(void 0===e.content_uri)return void c(new Error("Bad response"));c(void 0,u,e.content_uri)}},u.upload.addEventListener("progress",function(e){clearTimeout(u.timeout_timer),u.timeout_timer=setTimeout(d,3e4),s.notify(e)}),a+="?access_token="+encodeURIComponent(this.opts.accessToken),a+="&filename="+encodeURIComponent(e.name),u.open("POST",a),e.type?u.setRequestHeader("Content-Type",e.type):u.setRequestHeader("Content-Type","application/octet-stream"),u.send(e)}else{var l={filename:e.name,access_token:this.opts.accessToken};e.stream.pipe(this.opts.request({uri:a,qs:l,method:"POST"},i(s,t,this.opts.onlyData)))}return s.promise},idServerRequest:function(e,t,n,s,a){var u=this.opts.idBaseUrl+a+n;if(void 0!==e&&!o.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);var c={uri:u,method:t,withCredentials:!1,json:!1,_matrix_opts:this.opts};"GET"==t?c.qs=s:c.form=s;var d=r.defer();return this.opts.request(c,i(d,e,this.opts.onlyData)),d.promise},authedRequest:function(e,t,n,r,o){return r||(r={}),r.access_token=this.opts.accessToken,this.request(e,t,n,r,o)},request:function(e,t,n,r,o){return this.requestWithPrefix(e,t,n,r,o,this.opts.prefix)},authedRequestWithPrefix:function(e,t,n,r,o,i){var s=this.opts.baseUrl+i+n;return r||(r={}),r.access_token=this.opts.accessToken,this._request(e,t,s,r,o)},requestWithPrefix:function(e,t,n,r,o,i){var s=this.opts.baseUrl+i+n;return r||(r={}),this._request(e,t,s,r,o)},_request:function(e,t,n,s,a){if(void 0!==e&&!o.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);if(s||(s={}),this.opts.extraParams)for(var u in this.opts.extraParams)this.opts.extraParams.hasOwnProperty(u)&&(s[u]=this.opts.extraParams[u]);var c=r.defer();try{this.opts.request({uri:n,method:t,withCredentials:!1,qs:s,body:a,json:!0,_matrix_opts:this.opts},i(c,e,this.opts.onlyData))}catch(d){c.reject(d),e&&e(d)}return c.promise}};var i=function(e,n,r){return n=n||function(){},function(o,i,s){if(!o&&i.statusCode>=400&&(o=new t.exports.MatrixError(s),o.httpStatus=i.statusCode),o)e.reject(o),n(o);else{var a={code:i.statusCode,headers:i.headers,data:s};e.resolve(r?s:a),n(null,r?s:a);
}}};t.exports.MatrixError=function(e){this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.message=e.error||"Unknown message",this.data=e},t.exports.MatrixError.prototype=Object.create(Error.prototype),t.exports.MatrixError.prototype.constructor=t.exports.MatrixError}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./utils":18,q:23}],5:[function(e,t){"use strict";t.exports.MatrixEvent=e("./models/event").MatrixEvent,t.exports.EventStatus=e("./models/event").EventStatus,t.exports.MatrixInMemoryStore=e("./store/memory").MatrixInMemoryStore,t.exports.WebStorageStore=e("./store/webstorage"),t.exports.MatrixHttpApi=e("./http-api").MatrixHttpApi,t.exports.MatrixError=e("./http-api").MatrixError,t.exports.MatrixClient=e("./client").MatrixClient,t.exports.Room=e("./models/room"),t.exports.RoomMember=e("./models/room-member"),t.exports.RoomState=e("./models/room-state"),t.exports.User=e("./models/user"),t.exports.MatrixScheduler=e("./scheduler"),t.exports.WebStorageSessionStore=e("./store/session/webstorage"),t.exports.CRYPTO_ENABLED=e("./client").CRYPTO_ENABLED,t.exports.ContentRepo=e("./content-repo"),t.exports.createNewMatrixCall=e("./webrtc/call").createNewMatrixCall;var n;t.exports.request=function(e){n=e},t.exports.createClient=function(e){return"string"==typeof e&&(e={baseUrl:e}),e.request=e.request||n,e.store=e.store||new t.exports.MatrixInMemoryStore,e.scheduler=e.scheduler||new t.exports.MatrixScheduler,new t.exports.MatrixClient(e)}},{"./client":2,"./content-repo":3,"./http-api":4,"./models/event":6,"./models/room":10,"./models/room-member":7,"./models/room-state":8,"./models/user":11,"./scheduler":13,"./store/memory":14,"./store/session/webstorage":15,"./store/webstorage":17,"./webrtc/call":19}],6:[function(e,t){"use strict";t.exports.EventStatus={NOT_SENT:"not_sent",SENDING:"sending",QUEUED:"queued"},t.exports.MatrixEvent=function(e,t){this.event=e||{},this.sender=null,this.target=null,this.status=null,this.forwardLooking=!0,this.encrypted=Boolean(t)},t.exports.MatrixEvent.prototype={getId:function(){return this.event.event_id},getSender:function(){return this.event.user_id},getType:function(){return this.event.type},getWireType:function(){return this.encryptedType||this.event.type},getRoomId:function(){return this.event.room_id},getTs:function(){return this.event.origin_server_ts},getContent:function(){return this.event.content||{}},getWireContent:function(){return this.encryptedContent||this.event.content||{}},getPrevContent:function(){return this.event.prev_content||{}},getDirectionalContent:function(){return this.forwardLooking?this.getContent():this.getPrevContent()},getAge:function(){return this.event.age},getStateKey:function(){return this.event.state_key},isState:function(){return void 0!==this.event.state_key},isEncrypted:function(){return this.encrypted}}},{}],7:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.userId=t,this.typing=!1,this.name=t,this.powerLevel=0,this.powerLevelNorm=0,this.user=null,this.membership=null,this.events={member:null},this._updateModifiedTime()}function r(e,t,n){var r=t.getDirectionalContent().displayname,o=e.userId;if(!r)return o;if(!n)return r;var i=n.getUserIdsWithDisplayName(r),s=i.filter(function(e){return e!==o});return s.length>0?r+" ("+o+")":r}var o=e("events").EventEmitter,i=e("../content-repo"),s=e("../utils");s.inherits(n,o),n.prototype.setMembershipEvent=function(e,t){if("m.room.member"===e.getType()){this.events.member=e;var n=this.membership;this.membership=e.getDirectionalContent().membership;var o=this.name;this.name=r(this,e,t),n!==this.membership&&(this._updateModifiedTime(),this.emit("RoomMember.membership",e,this)),o!==this.name&&(this._updateModifiedTime(),this.emit("RoomMember.name",e,this))}},n.prototype.setPowerLevelEvent=function(e){if("m.room.power_levels"===e.getType()){var t=e.getContent().users_default||0;s.forEach(s.values(e.getContent().users),function(e){t=Math.max(t,e)});var n=this.powerLevel,r=this.powerLevelNorm;this.powerLevel=e.getContent().users[this.userId]||e.getContent().users_default||0,this.powerLevelNorm=0,t>0&&(this.powerLevelNorm=100*this.powerLevel/t),(n!==this.powerLevel||r!==this.powerLevelNorm)&&(this._updateModifiedTime(),this.emit("RoomMember.powerLevel",e,this))}},n.prototype.setTypingEvent=function(e){if("m.typing"===e.getType()){var t=this.typing;this.typing=!1;var n=e.getContent().user_ids;s.isArray(n)&&(-1!==n.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this._updateModifiedTime(),this.emit("RoomMember.typing",e,this)))}},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},n.prototype.getAvatarUrl=function(e,t,n,r,o){if(void 0===o&&(o=!0),!this.events.member&&!o)return null;var s=this.events.member?this.events.member.getContent().avatar_url:null;return s?i.getHttpUriForMxc(e,s,t,n,r):o?i.getIdenticonUri(e,this.userId,t,n):null},t.exports=n},{"../content-repo":3,"../utils":18,events:21}],8:[function(e,t){"use strict";function n(e){this.roomId=e,this.members={},this.events={},this.paginationToken=null,this._sentinels={},this._updateModifiedTime(),this._displayNameToUserIds={},this._userIdsToDisplayNames={}}function r(e,t,n){var r=e._userIdsToDisplayNames[t];if(delete e._userIdsToDisplayNames[t],r){for(var o=e._displayNameToUserIds[r]||[],i=0;i<o.length;i++)o[i]===t&&(o.splice(i,1),i--);e._displayNameToUserIds[r]=o}e._userIdsToDisplayNames[t]=n,e._displayNameToUserIds[n]||(e._displayNameToUserIds[n]=[]),e._displayNameToUserIds[n].push(t)}var o=e("events").EventEmitter,i=e("../utils"),s=e("./room-member");i.inherits(n,o),n.prototype.getMembers=function(){return i.values(this.members)},n.prototype.getMember=function(e){return this.members[e]||null},n.prototype.getSentinelMember=function(e){return this._sentinels[e]||null},n.prototype.getStateEvents=function(e,t){if(!this.events[e])return void 0===t?[]:null;if(void 0===t)return i.values(this.events[e]);var n=this.events[e][t];return n?n:null},n.prototype.setStateEvents=function(e){var t=this;this._updateModifiedTime(),i.forEach(e,function(e){e.getRoomId()===t.roomId&&e.isState()&&(void 0===t.events[e.getType()]&&(t.events[e.getType()]={}),t.events[e.getType()][e.getStateKey()]=e,"m.room.member"===e.getType()&&r(t,e.getStateKey(),e.getContent().displayname),t.emit("RoomState.events",e,t))}),i.forEach(e,function(e){if(e.getRoomId()===t.roomId&&e.isState())if("m.room.member"===e.getType()){var n=e.getStateKey(),r=t.members[n];r||(r=new s(e.getRoomId(),n),t.emit("RoomState.newMember",e,t,r));var o=new s(e.getRoomId(),n);i.forEach([r,o],function(n){n.setMembershipEvent(e,t);var r=t.getStateEvents("m.room.power_levels","");r&&n.setPowerLevelEvent(r)}),t._sentinels[n]=o,t.members[n]=r,t.emit("RoomState.members",e,t,r)}else if("m.room.power_levels"===e.getType()){var a=i.values(t.members);i.forEach(a,function(t){t.setPowerLevelEvent(e)})}})},n.prototype.setTypingEvent=function(e){i.forEach(i.values(this.members),function(t){t.setTypingEvent(e)})},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},n.prototype.getUserIdsWithDisplayName=function(e){return this._displayNameToUserIds[e]||[]},t.exports=n},{"../utils":18,"./room-member":7,events:21}],9:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.info=t}t.exports=n},{}],10:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.name=e,this.timeline=[],this.oldState=new s(e),this.currentState=new s(e),this.summary=null,this.storageToken=t,this._redactions=[],this._receipts={},this._receiptCacheByEventId={}}function r(e,t,n){e.sender=t.getSentinelMember(e.getSender()),"m.room.member"===e.getType()&&(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}function o(e,t){var n,r=e.currentState.getStateEvents("m.room.canonical_alias","");if(r&&(n=r.getContent().alias),!n){var o=e.currentState.getStateEvents("m.room.aliases")[0];o&&c.isArray(o.getContent().aliases)&&(n=o.getContent().aliases[0])}var i=e.currentState.getStateEvents("m.room.name","");if(i)return i.getContent().name+"";if(n)return n;var s=c.filter(e.currentState.getMembers(),function(e){return e.userId!==t&&"leave"!==e.membership});if(0===s.length){var a=c.filter(e.currentState.getMembers(),function(e){return"leave"!==e.membership});return 1===a.length?"invite"===a[0].membership?a[0].events.member?"Invite from "+a[0].events.member.getSender():"Room Invite":t:"?"}return 1===s.length?s[0].name:2===s.length?s[0].name+" and "+s[1].name:s[0].name+" and "+(s.length-1)+" others"}var i=e("events").EventEmitter,s=e("./room-state"),a=e("./room-summary"),u=e("./event").MatrixEvent,c=e("../utils"),d=e("../content-repo");c.inherits(n,i),n.prototype.getAvatarUrl=function(e,t,n,r,o){var i=this.currentState.getStateEvents("m.room.avatar","");if(void 0===o&&(o=!0),!i&&!o)return null;var s=i?i.getContent().url:null;return s?d.getHttpUriForMxc(e,s,t,n,r):o?d.getIdenticonUri(e,this.roomId,t,n):null},n.prototype.getMember=function(e){var t=this.currentState.members[e];return t?t:null},n.prototype.getJoinedMembers=function(){return this.getMembersWithMembership("join")},n.prototype.getMembersWithMembership=function(e){return c.filter(this.currentState.getMembers(),function(t){return t.membership===e})},n.prototype.hasMembershipState=function(e,t){return c.filter(this.currentState.getMembers(),function(n){return n.membership===t&&n.userId===e}).length>0},n.prototype.addEventsToTimeline=function(e,t){function n(e){return function(t){return t.getId()===e.event.redacts}}for(var o=t?this.oldState:this.currentState,i=0;i<e.length;i++)if(!(t&&this._redactions.indexOf(e[i].getId())>=0)){if(r(e[i],o,t),e[i].isState()&&(o.setStateEvents([e[i]]),e[i].sender||r(e[i],o,t)),"m.room.redaction"===e[i].getType()){var s=c.removeElement(this.timeline,n(e[i]));!s&&t&&this._redactions.push(e[i].event.redacts)}t?this.timeline.unshift(e[i]):this.timeline.push(e[i]),this.emit("Room.timeline",e[i],this,Boolean(t))}},n.prototype.addEvents=function(e,t){if(t&&-1===["replace","ignore"].indexOf(t))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(var n=0;n<e.length;n++)if("m.typing"===e[n].getType())this.currentState.setTypingEvent(e[n]);else if("m.receipt"===e[n].getType())this.addReceipt(e[n]);else{if(t){for(var o=!1,i=0;i<this.timeline.length;i++)if(this.timeline[i].getId()===e[n].getId())if("replace"===t)r(e[n],this.currentState,!1),this.timeline[i].encryptedType||(this.timeline[i]=e[n]),o=!0;else if("ignore"===t){o=!0;break}if(o)continue}this.addEventsToTimeline([e[n]])}},n.prototype.recalculate=function(e){var t=this,n=this.currentState.getStateEvents("m.room.member",e);if(n&&"invite"===n.getContent().membership){var r=n.event.invite_room_state||[];c.forEach(r,function(n){var r=t.currentState.getStateEvents(n.type,n.state_key);r||t.currentState.setStateEvents([new u({type:n.type,state_key:n.state_key,content:n.content,event_id:"$fake"+Date.now(),room_id:t.roomId,user_id:e})])})}var i=this.name;this.name=o(this,e),this.summary=new a(this.roomId,{title:this.name}),i!==this.name&&this.emit("Room.name",this)},n.prototype.getUsersReadUpTo=function(e){return this.getReceiptsForEvent(e).filter(function(e){return"m.read"===e.type}).map(function(e){return e.userId})},n.prototype.getReceiptsForEvent=function(e){return this._receiptCacheByEventId[e.getId()]||[]},n.prototype.addReceipt=function(e){var t=this;c.keys(e.getContent()).forEach(function(n){c.keys(e.getContent()[n]).forEach(function(r){c.keys(e.getContent()[n][r]).forEach(function(o){var i=e.getContent()[n][r][o];t._receipts[r]||(t._receipts[r]={}),t._receipts[r][o]||(t._receipts[r][o]={}),t._receipts[r][o]={eventId:n,data:i}})})}),t._receiptCacheByEventId={},c.keys(t._receipts).forEach(function(e){c.keys(t._receipts[e]).forEach(function(n){var r=t._receipts[e][n];t._receiptCacheByEventId[r.eventId]||(t._receiptCacheByEventId[r.eventId]=[]),t._receiptCacheByEventId[r.eventId].push({userId:n,type:e,data:r.data})})})},t.exports=n},{"../content-repo":3,"../utils":18,"./event":6,"./room-state":8,"./room-summary":9,events:21}],11:[function(e,t){"use strict";function n(e){this.userId=e,this.presence="offline",this.displayName=e,this.avatarUrl=null,this.lastActiveAgo=0,this.events={presence:null,profile:null},this._updateModifiedTime()}var r=e("events").EventEmitter,o=e("../utils");o.inherits(n,r),n.prototype.setPresenceEvent=function(e){if("m.presence"===e.getType()){var t=null===this.events.presence;this.events.presence=e;var n=[];(e.getContent().presence!==this.presence||t)&&n.push("User.presence"),e.getContent().avatar_url!==this.avatarUrl&&n.push("User.avatarUrl"),e.getContent().displayname!==this.displayName&&n.push("User.displayName"),this.presence=e.getContent().presence,this.displayName=e.getContent().displayname,this.avatarUrl=e.getContent().avatar_url,this.lastActiveAgo=e.getContent().last_active_ago,n.length>0&&this._updateModifiedTime();for(var r=0;r<n.length;r++)this.emit(n[r],e,this)}},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},t.exports=n},{"../utils":18,events:21}],12:[function(e,t){function n(e){var t=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},n=function(e,t,n){for(var i=["override","content","room","sender","underride"],s=0;s<i.length;++s)for(var a=i[s],u=t[a],c=0;c<u.length;++c){var d=u[c];if(d.enabled){var l=r(a,d,n);if(l&&o(l,e))return d.kind=a,d}}return null},r=function(e,t,n){var r={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case"underride":case"override":r.conditions=t.conditions;break;case"room":if(!t.rule_id)return null;r.conditions.push({kind:"event_match",key:"room_id",pattern:t.rule_id});break;case"sender":if(!t.rule_id)return null;r.conditions.push({kind:"event_match",key:"user_id",pattern:t.rule_id});break;case"content":if(!t.pattern)return null;r.conditions.push({kind:"event_match",key:"content.body",pattern:t.pattern})}return n&&r.conditions.push({kind:"device",profile_tag:n}),r},o=function(e,t){for(var n=!0,r=0;r<e.conditions.length;++r){var o=e.conditions[r];n&=i(o,t)}return n},i=function(e,t){var n={event_match:c,device:u,contains_display_name:a,room_member_count:s};return n[e.kind]?n[e.kind](e,t):!0},s=function(t,n){if(!t.is)return!1;var r=e.getRoom(n.room_id);if(!r||!r.currentState||!r.currentState.members)return!1;var o=Object.keys(r.currentState.members).length,i=t.is.match(/^([=<>]*)([0-9]*)$/);if(!i)return!1;var s=i[1],a=parseInt(i[2]);if(isNaN(a))return!1;switch(s){case"":case"==":return o==a;case"<":return a>o;case">":return o>a;case"<=":return a>=o;case">=":return o>=a;default:return!1}},a=function(n,r){if(!r.content||!r.content.body||"string"!=typeof r.content.body)return!1;var o=e.getRoom(r.room_id);if(!(o&&o.currentState&&o.currentState.members&&o.currentState.getMember(e.credentials.userId)))return!1;var i=o.currentState.getMember(e.credentials.userId).name,s=new RegExp("\\b"+t(i)+"\\b","i");return r.content.body.search(s)>-1},u=function(){return!1},c=function(e,t){var n=l(e.key,t);if(!n||"string"!=typeof n)return!1;var r;r="content.body"==e.key?"\\b"+d(e.pattern)+"\\b":"^"+d(e.pattern)+"$";var o=new RegExp(r,"i");return!!n.match(o)},d=function(e){var n=t(e);return n=n.replace(/\\\*/,".*"),n=n.replace(/\?/,"."),n=n.replace(/\\\[(!|)(.*)\\]/,function(e,t,n){var r=t&&"^"||"",o=n.replace(/\\\-/,"-");return"["+r+o+"]"})},l=function(e,t){for(var n=e.split("."),r=t;n.length>0;){var o=n.shift();if(!r[o])return null;r=r[o]}return r},p=function(t,r){if(!r)return null;if(t.user_id==e.credentials.userId)return null;for(var o=Object.keys(r.device),i=0;i<o.length;++i){var s=o[i],a=r.device[s],u=n(a,s);if(u)return u}return n(t,r.global)},f=function(e){for(var t={notify:!1,tweaks:{}},n=0;n<e.length;++n){var r=e[n];"notify"===r?t.notify=!0:"object"==typeof r&&(void 0===r.value&&(r.value=!0),t.tweaks[r.set_tweak]=r.value)}return t},h=function(e,t){var n=p(e,t);if(!n)return{};var r=f(n.actions);return void 0===r.tweaks.highlight&&(r.tweaks.highlight="content"==n.kind),r};this.actionsForEvent=function(t){return h(t,e.pushRules)}}t.exports=n},{}],13:[function(e,t){"use strict";function n(e,t){this.retryAlgorithm=e||n.RETRY_BACKOFF_RATELIMIT,this.queueAlgorithm=t||n.QUEUE_MESSAGES,this._queues={},this._activeQueues=[],this._procFn=null}function r(e){e._procFn&&u.forEach(u.filter(u.keys(e._queues),function(t){return-1===e._activeQueues.indexOf(t)&&e._queues[t].length>0}),function(t){e._activeQueues.push(t),a("Spinning up queue: '%s'",t),o(e,t)})}function o(e,t){var n=i(e,t);if(!n){var r=e._activeQueues.indexOf(t);return r>=0&&e._activeQueues.splice(r,1),void a("Stopping queue '%s' as it is now empty",t)}a("Queue '%s' has %s pending events",t,e._queues[t].length),e._procFn(n.event).done(function(r){s(e,t),a("Queue '%s' sent event %s",t,n.event.getId()),n.defer.resolve(r),o(e,t)},function(r){n.attempts+=1;var i=e.retryAlgorithm(n.event,n.attempts,r);a("retry(%s) err=%s event_id=%s waitTime=%s",n.attempts,r,n.event.getId(),i),-1===i?(a("Queue '%s' giving up on event %s",t,n.event.getId()),s(e,t),n.defer.reject(r),o(e,t)):setTimeout(function(){o(e,t)},i)})}function i(e,t){var n=e._queues[t];return u.isArray(n)?n[0]:null}function s(e,t){var n=e._queues[t];return u.isArray(n)?n.shift():null}function a(){d&&console.log.apply(console,arguments)}var u=e("./utils"),c=e("q"),d=!1;n.prototype.getQueueForEvent=function(e){var t=this.queueAlgorithm(e);return t&&this._queues[t]?u.map(this._queues[t],function(e){return e.event}):null},n.prototype.removeEventFromQueue=function(e){var t=this.queueAlgorithm(e);if(!t||!this._queues[t])return!1;var n=!1;return u.removeElement(this._queues[t],function(t){return t.event.getId()===e.getId()?(n=!0,!0):void 0}),n},n.prototype.setProcessFunction=function(e){this._procFn=e,r(this)},n.prototype.queueEvent=function(e){var t=this.queueAlgorithm(e);if(!t)return null;this._queues[t]||(this._queues[t]=[]);var n=c.defer();return this._queues[t].push({event:e,defer:n,attempts:0}),a("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),r(this),n.promise},n.RETRY_BACKOFF_RATELIMIT=function(e,t,n){if(400===n.httpStatus||403===n.httpStatus||401===n.httpStatus)return-1;if("M_LIMIT_EXCEEDED"===n.name){var r=n.data.retry_after_ms;if(r)return r}return t>4?-1:1e3*Math.pow(2,t)},n.QUEUE_MESSAGES=function(e){return"m.room.message"===e.getType()?"message":null},t.exports=n},{"./utils":18,q:23}],14:[function(e,t){"use strict";var n=e("../utils");t.exports.MatrixInMemoryStore=function(){this.rooms={},this.users={},this.syncToken=null},t.exports.MatrixInMemoryStore.prototype={getSyncToken:function(){return this.syncToken},setSyncToken:function(e){this.syncToken=e},storeRoom:function(e){this.rooms[e.roomId]=e},getRoom:function(e){return this.rooms[e]||null},getRooms:function(){return n.values(this.rooms)},getRoomSummaries:function(){return n.map(n.values(this.rooms),function(e){return e.summary})},storeUser:function(e){this.users[e.userId]=e},getUser:function(e){return this.users[e]||null},scrollback:function(){return[]},storeEvents:function(){}}},{"../utils":18}],15:[function(e,t){"use strict";function n(e){if(this.store=e,!c.isFunction(e.getItem)||!c.isFunction(e.setItem)||!c.isFunction(e.removeItem))throw new Error("Supplied webStore does not meet the WebStorage API interface")}function r(e){return l+"devices/"+e}function o(e){return l+"sessions/"+e}function i(e){return l+"rooms/"+e}function s(e,t){try{return JSON.parse(e.getItem(t))}catch(n){u("Failed to get key %s: %s",t,n),u(n.stack)}return null}function a(e,t,n){e.setItem(t,JSON.stringify(n))}function u(){d&&console.log.apply(console,arguments)}var c=e("../../utils"),d=!1,l="session.e2e.";n.prototype={storeEndToEndAccount:function(e){this.store.setItem(p,e)},getEndToEndAccount:function(){return this.store.getItem(p)},storeEndToEndDevicesForUser:function(e,t){a(this.store,r(e),t)},getEndToEndDevicesForUser:function(e){return s(this.store,r(e))},storeEndToEndSession:function(e,t,n){var r=this.getEndToEndSessions(e)||{};r[t]=n,a(this.store,o(e),r)},getEndToEndSessions:function(e){return s(this.store,o(e))},storeEndToEndRoom:function(e,t){a(this.store,i(e),t)},getEndToEndRoom:function(e){return s(this.store,i(e))}};var p=l+"account";t.exports=n},{"../../utils":18}],16:[function(e,t){"use strict";function n(){this.fromToken=null}n.prototype={getSyncToken:function(){return this.fromToken},setSyncToken:function(e){this.fromToken=e},storeRoom:function(){},getRoom:function(){return null},getRooms:function(){return[]},getRoomSummaries:function(){return[]},storeUser:function(){},getUser:function(){return null},scrollback:function(){return[]},storeEvents:function(){}},t.exports=n},{}],17:[function(e,t){"use strict";function n(e,t){if(this.store=e,this.batchSize=t,!(f.isFunction(e.getItem)&&f.isFunction(e.setItem)&&f.isFunction(e.removeItem)&&f.isFunction(e.key)))throw new Error("Supplied webStore does not meet the WebStorage API interface");if(!parseInt(e.length)&&0!==e.length)throw new Error("Supplied webStore does not meet the WebStorage API interface (length)");this._roomIds=[],this._syncedWithStore=!1,this._tokens=[]}function r(e){this.state={events:{}},this.timeline={},this.roomId=e}function o(e,t,n,r){var o=new h(t,r.length),i=c(e,u(t,"state")),d=[];f.forEach(f.keys(i.events),function(e){f.forEach(f.keys(i.events[e]),function(t){d.push(i.events[e][t])})});var l=f.map(f.deepCopy(d),function(e){return new v(e)}),p=f.map(d,function(e){return new v(e)});o.oldState.setStateEvents(l),o.currentState.setStateEvents(p);for(var m,y,g,_=[],E=a(s(e,t)),S=E;_.length<n&&(y=u(t,"timeline",E),g=c(e,y)||[],0!==g.length);){for(m=g.length-1;m>=0;m--)if(_.unshift(new v(g[m])),_.length===n){S=E;break}E--}return o.addEventsToTimeline(_.reverse(),!0),o.oldState.paginationToken=i.pagination_token,r.push({earliestIndex:S}),o}function i(e,t){d(e,u(t.roomId,"state"),t.state),f.forEach(f.keys(t.timeline),function(n){d(e,u(t.roomId,"timeline",n),t.timeline[n])})}function s(e,t){for(var n=[],r=0;r<e.length;r++)-1!==e.key(r).indexOf(u(t,"timeline_"))&&n.push(e.key(r).replace(u(t,"timeline_"),""));return n}function a(e,t){for(var n,r,o=0;o<e.length;o++)r=parseInt(e[o]),!isNaN(r)&&(void 0===n||!t&&r>n||t&&n>r)&&(n=r);return n}function u(e,t,n){return"room_"+e+"_"+t+(void 0===n?"":"_"+n)}function c(e,t){try{return JSON.parse(e.getItem(t))}catch(n){l("Failed to get key %s: %s",t,n),l(n.stack)}return null}function d(e,t,n){e.setItem(t,JSON.stringify(n))}function l(){p&&console.log.apply(console,arguments)}var p=!1,f=e("../utils"),h=e("../models/room"),m=e("../models/user"),v=e("../models/event").MatrixEvent;n.prototype.getSyncToken=function(){return this.store.getItem("sync_token")},n.prototype.setSyncToken=function(e){this.store.setItem("sync_token",e)},n.prototype.storeRoom=function(e){var t=r.fromRoom(e,this.batchSize);i(this.store,t),-1===this._roomIds.indexOf(e.roomId)&&this._roomIds.push(e.roomId)},n.prototype.getRoom=function(e){if(!c(this.store,u(e,"state")))return l("getRoom: No room with id %s found.",e),null;var t=s(this.store,e);return-1!==t.indexOf("live")&&(l("getRoom: Live events found. Syncing timeline for %s",e),this._syncTimeline(e,t)),o(this.store,e,this.batchSize,this._tokens)},n.prototype.getRooms=function(){var e,t=[];if(!this._syncedWithStore){for(this._roomIds=[],e=0;e<this.store.length;e++)if(0===this.store.key(e).indexOf("room_")&&-1!==this.store.key(e).indexOf("_state")){var n=this.store.key(e);this._roomIds.push(n.substring("room_".length,n.length-"_state".length))}this._syncedWithStore=!0}for(e=0;e<this._roomIds.length;e++){var r=this.getRoom(this._roomIds[e]);r&&t.push(r)}return t},n.prototype.getRoomSummaries=function(){return[]},n.prototype.storeUser=function(e){d(this.store,"user_"+e.userId,{presence:e.events.presence?e.events.presence.event:null})},n.prototype.getUser=function(e){var t=c(this.store,"user_"+e);if(!t)return null;var n=new m(e);return t.presence&&n.setPresenceEvent(new v(t.presence)),n},n.prototype.scrollback=function(e,t){if(void 0===e.storageToken||e.storageToken>=this._tokens.length)return[];var n,r=this._tokens[e.storageToken]||{},o=r.earliestIndex,i=e.timeline[0]?e.timeline[0].getId():null;l("scrollback in %s (timeline=%s msgs) i=%s, timeline[0].id=%s - req %s events",e.roomId,e.timeline.length,o,i,t);var s=c(this.store,u(e.roomId,"timeline",o));if(!s)return l("No batch with index %s found.",o),[];var a=[],d=!1;for(n=s.length-1;n>=0;n--){var p=new v(s[n]);if(p.getId()!==i){if(d&&(l("Add event at position %s in batch %s",n,o),a.push(s[n]),a.length===t))break}else d=!0,l("Found timeline[0] event at position %s in batch %s",n,o)}if(a.length===t)return l("Batch has enough events to satisfy request."),a;if(!d)return l("Failed to find event ID %s in batch %s",i,o),[];for(;a.length<t;){if(o--,s=c(this.store,u(e.roomId,"timeline",o)),!s){l("No batch found at index %s",o);break}for(n=s.length-1;n>=0&&(l("Add event at position %s in batch %s",n,o),a.push(s[n]),a.length!==t);n--);}return l("Out of %s requested events, returning %s. New index=%s",t,a.length,o),e.addEventsToTimeline(f.map(a,function(e){return new v(e)}),!0),this._tokens[e.storageToken]={earliestIndex:o},a},n.prototype.storeEvents=function(e,t,n,o){if(o){var i,p,h,m=a(s(this.store,e.roomId),!0);for(i=0;i<t.length;i++){for(p=u(e.roomId,"timeline",m),h=c(this.store,p)||[];h.length<this.batchSize&&i<t.length;)h.unshift(t[i].event),i++;i--,d(this.store,p,h),m--}}else{var v=c(this.store,u(e.roomId,"timeline","live"))||[];l("Adding %s events to %s live list (which has %s already)",t.length,e.roomId,v.length);var y=!1;if(v=v.concat(f.map(t,function(e){return e.isState()&&(y=!0),e.event})),d(this.store,u(e.roomId,"timeline","live"),v),y){l("Storing state for %s as new events updated state",e.roomId);var g=r.fromRoom(e,0);d(this.store,u(g.roomId,"state"),g.state)}}},n.prototype._syncTimeline=function(e,t){t=t||s(this.store,e);for(var n=c(this.store,u(e,"timeline","live"))||[],r=a(t),o=u(e,"timeline",r),i=c(this.store,o)||[];i.length<this.batchSize&&n.length>0;)i.push(n.shift());d(this.store,o,i);for(var l=[];n.length>0;)l.push(n.shift()),(l.length===this.batchSize||0===n.length)&&(r++,o=u(e,"timeline",r),d(this.store,o,l),l=[]);d(this.store,u(e,"timeline","live"),[])},r.fromRoom=function(e,t){var n,o=new r(e.roomId);if(o.state.pagination_token=e.oldState.paginationToken,f.forEach(f.keys(e.currentState.events),function(t){f.forEach(f.keys(e.currentState.events[t]),function(n){o.state.events[t]||(o.state.events[t]={}),o.state.events[t][n]=e.currentState.events[t][n].event})}),t>0)for(n=0;n*t<e.timeline.length;)o.timeline[n]=e.timeline.slice(n*t,(n+1)*t),o.timeline[n]=f.map(o.timeline[n],function(e){return e.event}),n++;else o.timeline[0]=f.map(e.timeline,function(e){return e.event});return o},t.exports=n},{"../models/event":6,"../models/room":10,"../models/user":11,"../utils":18}],18:[function(e,t){"use strict";t.exports.encodeParams=function(e){var t="";for(var n in e)e.hasOwnProperty(n)&&(t+="&"+encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.substring(1)},t.exports.encodeUri=function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e=e.replace(n,encodeURIComponent(t[n])));return e},t.exports.map=function(e,t){for(var n=new Array(e.length),r=0;r<e.length;r++)n[r]=t(e[r]);return n},t.exports.filter=function(e,t){for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n},t.exports.keys=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t},t.exports.values=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t},t.exports.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.exports.findElement=function(e,t,n){var r;if(n){for(r=e.length-1;r>=0;r--)if(t(e[r],r,e))return e[r]}else for(r=0;r<e.length;r++)if(t(e[r],r,e))return e[r]},t.exports.removeElement=function(e,t,n){var r;if(n){for(r=e.length-1;r>=0;r--)if(t(e[r],r,e))return e.splice(r,1),!0}else for(r=0;r<e.length;r++)if(t(e[r],r,e))return e.splice(r,1),!0;return!1},t.exports.isFunction=function(e){return"[object Function]"==Object.prototype.toString.call(e)},t.exports.isArray=function(e){return Boolean(e&&e.constructor===Array)},t.exports.checkObjectHasKeys=function(e,t){for(var n=0;n<t.length;n++)if(!e.hasOwnProperty(t[n]))throw new Error("Missing required key: "+t[n])},t.exports.checkObjectHasNoAdditionalKeys=function(e,t){for(var n in e)if(e.hasOwnProperty(n)&&-1===t.indexOf(n))throw new Error("Unknown key: "+n)},t.exports.deepCopy=function(e){return JSON.parse(JSON.stringify(e))},t.exports.runPolyfills=function(){Array.prototype.filter||(Array.prototype.filter=function(e){if(void 0===this||null===this)throw new TypeError;var t=Object(this),n=t.length>>>0;if("function"!=typeof e)throw new TypeError;for(var r=[],o=arguments.length>=2?arguments[1]:void 0,i=0;n>i;i++)if(i in t){var s=t[i];e.call(o,s,i,t)&&r.push(s)}return r}),Array.prototype.map||(Array.prototype.map=function(e,t){var n,r,o;if(null===this||void 0===this)throw new TypeError(" this is null or not defined");var i=Object(this),s=i.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(n=t),r=new Array(s),o=0;s>o;){var a,u;o in i&&(a=i[o],u=e.call(n,a,o,i),r[o]=u),o++}return r})},t.exports.inherits=function(e,t){"function"!=typeof Object.create&&(Object.create=function(){function e(){}var t=Object.prototype.hasOwnProperty;return function(n){if("object"!=typeof n)throw new TypeError("Object prototype may only be an Object or null");e.prototype=n;var r=new e;if(e.prototype=null,arguments.length>1){var o=Object(arguments[1]);for(var i in o)t.call(o,i)&&(r[i]=o[i])}return r}}()),e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}},{}],19:[function(e,t){(function(n){"use strict";function r(e){this.roomId=e.roomId,this.client=e.client,this.webRtc=e.webRtc,this.URL=e.URL,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.turnServers.push({urls:[r.FALLBACK_STUN_SERVER]}),o.forEach(this.turnServers,function(e){o.checkObjectHasKeys(e,["urls"])}),this.callId="c"+(new Date).getTime(),this.state="fledgling",this.didConnect=!1,this.candidateSendQueue=[],this.candidateSendTries=0,this.screenSharingStream=null}var o=e("../utils"),i=e("events").EventEmitter,s=!0;r.CALL_TIMEOUT_MS=6e4,r.FALLBACK_STUN_SERVER="stun:stun.l.google.com:19302",r.ERR_LOCAL_OFFER_FAILED="local_offer_failed",r.ERR_NO_USER_MEDIA="no_user_media",o.inherits(r,i),r.prototype.placeVoiceCall=function(){g("placeVoiceCall"),v(this),E(this,b("voice")),this.type="voice"},r.prototype.placeVideoCall=function(e,t){g("placeVideoCall"),v(this),this.localVideoElement=t,this.remoteVideoElement=e,E(this,b("video")),this.type="video",h(this)},r.prototype.placeScreenSharingCall=function(e,t){g("placeScreenSharingCall"),v(this);var n=w(this);if(n){this.localVideoElement=t,this.remoteVideoElement=e;var o=this;this.webRtc.getUserMedia(n,function(e){o.screenSharingStream=e,g("Got screen stream, requesting audio stream...");var t=b("voice");E(o,t)},function(e){o.emit("error",y(r.ERR_NO_USER_MEDIA,"Failed to get screen-sharing stream: "+e))}),this.type="video",h(this)}},r.prototype.getLocalVideoElement=function(){return this.localVideoElement},r.prototype.getRemoteVideoElement=function(){return this.remoteVideoElement},r.prototype.getRemoteAudioElement=function(){return this.remoteAudioElement},r.prototype.setLocalVideoElement=function(e){if(this.localVideoElement=e,e&&this.localAVStream&&"video"===this.type){e.autoplay=!0,e.src=this.URL.createObjectURL(this.localAVStream),e.muted=!0;var t=this;setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)}},r.prototype.setRemoteVideoElement=function(e){this.remoteVideoElement=e,h(this)},r.prototype.setRemoteAudioElement=function(e){
this.remoteAudioElement=e,m(this)},r.prototype._initWithInvite=function(e){this.msg=e.getContent(),this.peerConn=S(this);var t=this;this.peerConn&&this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(this.msg.offer),T(t,t._onSetRemoteDescriptionSuccess),T(t,t._onSetRemoteDescriptionError)),c(this,"ringing"),this.direction="inbound",this.type=this.msg.offer&&this.msg.offer.sdp&&this.msg.offer.sdp.indexOf("m=video")>-1?"video":"voice",e.getAge()&&setTimeout(function(){"ringing"==t.state&&(g("Call invite has expired. Hanging up."),t.hangupParty="remote",c(t,"ended"),f(t),"closed"!=t.peerConn.signalingState&&t.peerConn.close(),t.emit("hangup",t))},this.msg.lifetime-e.getAge())},r.prototype._initWithHangup=function(e){this.msg=e.getContent(),c(this,"ended")},r.prototype.answer=function(){g("Answering call %s of type %s",this.callId,this.type);var e=this;this.localAVStream||this.waitForLocalAVStream?this.localAVStream?this._gotUserMediaForAnswer(this.localAVStream):this.waitForLocalAVStream&&c(this,"wait_local_media"):(this.webRtc.getUserMedia(b(this.type),T(e,e._gotUserMediaForAnswer),T(e,e._getUserMediaFailed)),c(this,"wait_local_media"))},r.prototype._replacedBy=function(e){g(this.callId+" being replaced by "+e.callId),"wait_local_media"==this.state?(g("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):"create_offer"==this.state?(g("Handing local stream to new call"),e._gotUserMediaForAnswer(this.localAVStream),delete this.localAVStream):"invite_sent"==this.state&&(g("Handing local stream to new call"),e._gotUserMediaForAnswer(this.localAVStream),delete this.localAVStream),e.localVideoElement=this.localVideoElement,e.remoteVideoElement=this.remoteVideoElement,e.remoteAudioElement=this.remoteAudioElement,this.successor=e,this.emit("replaced",e),this.hangup(!0)},r.prototype.hangup=function(e,t){g("Ending call "+this.callId),p(this,"local",e,!t);var n={version:0,call_id:this.callId,reason:e};d(this,"m.call.hangup",n)},r.prototype.setLocalVideoMuted=function(e){this.localAVStream&&a(this.localAVStream.getVideoTracks(),!e)},r.prototype.isLocalVideoMuted=function(){return this.localAVStream?!u(this.localAVStream.getVideoTracks()):!1},r.prototype.setMicrophoneMuted=function(e){this.localAVStream&&a(this.localAVStream.getAudioTracks(),!e)},r.prototype.isMicrophoneMuted=function(){return this.localAVStream?!u(this.localAVStream.getAudioTracks()):!1},r.prototype._gotUserMediaForInvite=function(e){if(this.successor)return void this.successor._gotUserMediaForAnswer(e);if("ended"!=this.state){g("_gotUserMediaForInvite -> "+this.type);var t=this,n=this.getLocalVideoElement();n&&"video"==this.type&&(n.autoplay=!0,this.screenSharingStream?(g("Setting screen sharing stream to the local video element"),n.src=this.URL.createObjectURL(this.screenSharingStream)):n.src=this.URL.createObjectURL(e),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)),this.localAVStream=e,a(e.getAudioTracks(),!0),this.peerConn=S(this),this.peerConn.addStream(e),this.screenSharingStream&&(console.log("Adding screen-sharing stream to peer connection"),this.peerConn.addStream(this.screenSharingStream),this.localAVStream=this.screenSharingStream),this.peerConn.createOffer(T(t,t._gotLocalOffer),T(t,t._getLocalOfferFailed)),c(t,"create_offer")}},r.prototype._gotUserMediaForAnswer=function(e){var t=this;if("ended"!=t.state){var n=t.getLocalVideoElement();n&&"video"==t.type&&(n.autoplay=!0,n.src=t.URL.createObjectURL(e),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)),t.localAVStream=e,a(e.getAudioTracks(),!0),t.peerConn.addStream(e);var r={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:"video"==t.type}};t.peerConn.createAnswer(function(e){g("Created answer: "+e),t.peerConn.setLocalDescription(e,function(){var e={version:0,call_id:t.callId,answer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type}};d(t,"m.call.answer",e),c(t,"connecting")},function(){g("Error setting local description!")},r)},function(e){g("Failed to create answer: "+e)}),c(t,"create_answer")}},r.prototype._gotLocalIceCandidate=function(e){if(e.candidate){g("Got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate);var t={candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex};l(this,t)}},r.prototype._gotRemoteIceCandidate=function(e){"ended"!=this.state&&(g("Got remote ICE "+e.sdpMid+" candidate: "+e.candidate),this.peerConn.addIceCandidate(new this.webRtc.RtcIceCandidate(e),function(){},function(){}))},r.prototype._receivedAnswer=function(e){if("ended"!=this.state){var t=this;this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(e.answer),T(t,t._onSetRemoteDescriptionSuccess),T(t,t._onSetRemoteDescriptionError)),c(t,"connecting")}},r.prototype._gotLocalOffer=function(e){var t=this;return g("Created offer: "+e),"ended"==t.state?void g("Ignoring newly created offer on call ID "+t.callId+" because the call has ended"):void t.peerConn.setLocalDescription(e,function(){var e={version:0,call_id:t.callId,offer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type},lifetime:r.CALL_TIMEOUT_MS};d(t,"m.call.invite",e),setTimeout(function(){"invite_sent"==t.state&&t.hangup("invite_timeout")},r.CALL_TIMEOUT_MS),c(t,"invite_sent")},function(){g("Error setting local description!")})},r.prototype._getLocalOfferFailed=function(){this.emit("error",y(r.ERR_LOCAL_OFFER_FAILED,"Failed to start audio for call!"))},r.prototype._getUserMediaFailed=function(){this.emit("error",y(r.ERR_NO_USER_MEDIA,"Couldn't start capturing media! Is your microphone set up and does this app have permission?")),this.hangup("user_media_failed")},r.prototype._onIceConnectionStateChanged=function(){"ended"!=this.state&&(g("Ice connection state changed to: "+this.peerConn.iceConnectionState),"completed"==this.peerConn.iceConnectionState||"connected"==this.peerConn.iceConnectionState?(c(this,"connected"),this.didConnect=!0):"failed"==this.peerConn.iceConnectionState&&this.hangup("ice_failed"))},r.prototype._onSignallingStateChanged=function(){g("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)},r.prototype._onSetRemoteDescriptionSuccess=function(){g("Set remote description")},r.prototype._onSetRemoteDescriptionError=function(e){g("Failed to set remote description"+e)},r.prototype._onAddStream=function(e){g("Stream id "+e.stream.id+" added");var t=e.stream;t.getVideoTracks().length>0?(this.type="video",this.remoteAVStream=t):(this.type="voice",this.remoteAStream=t);var n=this;k(t,function(e){g("Track id "+e.id+" added"),e.onstarted=T(n,n._onRemoteStreamTrackStarted)}),e.stream.onended=T(n,n._onRemoteStreamEnded),e.stream.onstarted=T(n,n._onRemoteStreamStarted),"video"===this.type?h(this):m(this)},r.prototype._onRemoteStreamStarted=function(){c(this,"connected")},r.prototype._onRemoteStreamEnded=function(){g("Remote stream ended"),this.hangupParty="remote",c(this,"ended"),f(this),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit("hangup",this)},r.prototype._onRemoteStreamTrackStarted=function(){c(this,"connected")},r.prototype._onHangupReceived=function(e){g("Hangup received"),p(this,"remote",e.reason,!0)},r.prototype._onAnsweredElsewhere=function(){g("Answered elsewhere"),p(this,"remote","answered_elsewhere",!0)};var a=function(e,t){for(var n=0;n<e.length;n++)e[n].enabled=t},u=function(e){for(var t=0;t<e.length;t++)if(e[t].enabled)return!0;return!1},c=function(e,t){var n=e.state;e.state=t,e.emit("state",t,n)},d=function(e,t,n){return e.client.sendEvent(e.roomId,t,n)},l=function(e,t){e.candidateSendQueue.push(t),0===e.candidateSendTries&&setTimeout(function(){_(e)},100)},p=function(e,t,n,r){e.getRemoteVideoElement()&&(e.getRemoteVideoElement().pause&&e.getRemoteVideoElement().pause(),e.getRemoteVideoElement().src=""),e.getRemoteAudioElement()&&(e.getRemoteAudioElement().pause&&e.getRemoteAudioElement().pause(),e.getRemoteAudioElement().src=""),e.getLocalVideoElement()&&(e.getLocalVideoElement().pause&&e.getLocalVideoElement().pause(),e.getLocalVideoElement().src=""),e.hangupParty=t,e.hangupReason=n,c(e,"ended"),f(e),e.peerConn&&"closed"!==e.peerConn.signalingState&&e.peerConn.close(),r&&e.emit("hangup",e)},f=function(e){g("stopAllMedia (stream=%s)",e.localAVStream),e.localAVStream&&(k(e.localAVStream,function(e){e.stop&&e.stop()}),e.localAVStream.stop&&e.localAVStream.stop()),e.screenSharingStream&&(k(e.screenSharingStream,function(e){e.stop&&e.stop()}),e.screenSharingStream.stop&&e.screenSharingStream.stop()),e.remoteAVStream&&k(e.remoteAVStream,function(e){e.stop&&e.stop()}),e.remoteAStream&&k(e.remoteAStream,function(e){e.stop&&e.stop()})},h=function(e){if(e.getRemoteVideoElement()&&e.remoteAVStream){var t=e.getRemoteVideoElement();t.autoplay=!0,t.src=e.URL.createObjectURL(e.remoteAVStream),setTimeout(function(){var t=e.getRemoteVideoElement();t.play&&t.play(),e.webRtc.isOpenWebRTC()&&c(e,"connected")},0)}},m=function(e){if(e.getRemoteAudioElement()&&e.remoteAStream){var t=e.getRemoteAudioElement();t.autoplay=!0,t.src=e.URL.createObjectURL(e.remoteAStream),setTimeout(function(){var t=e.getRemoteAudioElement();t.play&&t.play(),e.webRtc.isOpenWebRTC()&&c(e,"connected")},0)}},v=function(e){if(0===e.listeners("error").length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")},y=function(e,t){var n=new Error(t);return n.code=e,n},g=function(){s&&console.log.apply(console,arguments)},_=function(e){if(0!==e.candidateSendQueue.length){var t=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var n={version:0,call_id:e.callId,candidates:t};g("Attempting to send "+t.length+" candidates"),d(e,"m.call.candidates",n).then(function(){e.candidateSendTries=0,_(e)},function(){for(var n=0;n<t.length;n++)e.candidateSendQueue.push(t[n]);if(e.candidateSendTries>5)return g("Failed to send candidates on attempt %s. Giving up for now.",e.candidateSendTries),void(e.candidateSendTries=0);var r=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,g("Failed to send candidates. Retrying in "+r+"ms"),setTimeout(function(){_(e)},r)})}},E=function(e,t){e.client.callList[e.callId]=e,e.webRtc.getUserMedia(t,T(e,e._gotUserMediaForInvite),T(e,e._getUserMediaFailed)),c(e,"wait_local_media"),e.direction="outbound",e.config=t},S=function(e){var t=e.turnServers;if("mozilla"===e.webRtc.vendor){t=[];for(var n=0;n<e.turnServers.length;n++)for(var r=0;r<e.turnServers[n].urls.length;r++)t.push({url:e.turnServers[n].urls[r],username:e.turnServers[n].username,credential:e.turnServers[n].credential})}var o=new e.webRtc.RtcPeerConnection({iceServers:t});return o.oniceconnectionstatechange=T(e,e._onIceConnectionStateChanged),o.onsignalingstatechange=T(e,e._onSignallingStateChanged),o.onicecandidate=T(e,e._gotLocalIceCandidate),o.onaddstream=T(e,e._onAddStream),o},w=function(e){var t=n.screen;return t?n.window&&"https:"===n.window.location.protocol?{video:{mandatory:{chromeMediaSource:"screen",chromeMediaSourceId:""+Date.now(),maxWidth:t.width,maxHeight:t.height,minFrameRate:1,maxFrameRate:10}}}:void e.emit("error",y(r.ERR_NO_USER_MEDIA,"You need to be using HTTPS to place a screen-sharing call.")):void e.emit("error",y(r.ERR_NO_USER_MEDIA,"Couldn't determine screen sharing constaints."))},b=function(e){switch(e){case"voice":return{audio:!0,video:!1};case"video":return{audio:!0,video:{mandatory:{minWidth:640,maxWidth:640,minHeight:360,maxHeight:360}}}}},T=function(e,t){return function(){return t.apply(e,arguments)}},R=function(e,t){for(var n=e.getVideoTracks(),r=0;r<n.length;r++)t(n[r])},I=function(e,t){for(var n=e.getAudioTracks(),r=0;r<n.length;r++)t(n[r])},k=function(e,t){R(e,t),I(e,t)};t.exports.MatrixCall=r,t.exports.createNewMatrixCall=function(e,t){var o=n.window,i=n.document;if(!o||!i)return null;var s={};s.isOpenWebRTC=function(){var e=i.getElementById("script");if(!e||!e.length)return!1;for(var t=0;t<e.length;t++)if(e[t].src.indexOf("owr.js")>-1)return!0;return!1};var a=o.navigator.getUserMedia||o.navigator.webkitGetUserMedia||o.navigator.mozGetUserMedia;if(a&&(s.getUserMedia=function(){return a.apply(o.navigator,arguments)}),s.RtcPeerConnection=o.RTCPeerConnection||o.webkitRTCPeerConnection||o.mozRTCPeerConnection,s.RtcSessionDescription=o.RTCSessionDescription||o.webkitRTCSessionDescription||o.mozRTCSessionDescription,s.RtcIceCandidate=o.RTCIceCandidate||o.webkitRTCIceCandidate||o.mozRTCIceCandidate,s.vendor=null,o.mozRTCPeerConnection?s.vendor="mozilla":o.webkitRTCPeerConnection?s.vendor="webkit":o.RTCPeerConnection&&(s.vendor="generic"),!(s.RtcIceCandidate&&s.RtcSessionDescription&&s.RtcPeerConnection&&s.getUserMedia))return null;var u={webRtc:s,client:e,URL:o.URL,roomId:t,turnServers:e.getTurnServers()};return new r(u)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":18,events:21}],20:[function(e,t,n){!function(e,r){"function"==typeof define&&define.amd?define([],r):"object"==typeof n?t.exports=r():e.returnExports=r()}(this,function(){function e(o,i){if("function"!=typeof i)throw new Error("Bad callback given: "+i);if(!o)throw new Error("No options given");var a=o.onResponse;if(o="string"==typeof o?{uri:o}:JSON.parse(JSON.stringify(o)),o.onResponse=a,o.verbose&&(e.log=r()),o.url&&(o.uri=o.url,delete o.url),!o.uri&&""!==o.uri)throw new Error("options.uri is a required argument");if("string"!=typeof o.uri)throw new Error("options.uri must be a string");for(var u=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],c=0;c<u.length;c++)if(o[u[c]])throw new Error("options."+u[c]+" is not supported");if(o.callback=i,o.method=o.method||"GET",o.headers=o.headers||{},o.body=o.body||null,o.timeout=o.timeout||e.DEFAULT_TIMEOUT,o.headers.host)throw new Error("Options.headers.host is not supported");o.json&&(o.headers.accept=o.headers.accept||"application/json","GET"!==o.method&&(o.headers["content-type"]="application/json"),"boolean"!=typeof o.json?o.body=JSON.stringify(o.json):"string"!=typeof o.body&&(o.body=JSON.stringify(o.body)));var d=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")};if(o.qs){var l="string"==typeof o.qs?o.qs:d(o.qs);o.uri=-1!==o.uri.indexOf("?")?o.uri+"&"+l:o.uri+"?"+l}var p=function(e){var t={};t.boundry="-------------------------------"+Math.floor(1e9*Math.random());var n=[];for(var r in e)e.hasOwnProperty(r)&&n.push("--"+t.boundry+'\nContent-Disposition: form-data; name="'+r+'"\n\n'+e[r]+"\n");return n.push("--"+t.boundry+"--"),t.body=n.join(""),t.length=t.body.length,t.type="multipart/form-data; boundary="+t.boundry,t};if(o.form){if("string"==typeof o.form)throw"form name unsupported";if("POST"===o.method){var f=(o.encoding||"application/x-www-form-urlencoded").toLowerCase();switch(o.headers["content-type"]=f,f){case"application/x-www-form-urlencoded":o.body=d(o.form).replace(/%20/g,"+");break;case"multipart/form-data":var h=p(o.form);o.body=h.body,o.headers["content-type"]=h.type;break;default:throw new Error("unsupported encoding:"+f)}}}return o.onResponse=o.onResponse||n,o.onResponse===!0&&(o.onResponse=i,o.callback=n),!o.headers.authorization&&o.auth&&(o.headers.authorization="Basic "+s(o.auth.username+":"+o.auth.password)),t(o)}function t(t){function n(){l=!0;var n=new Error("ETIMEDOUT");return n.code="ETIMEDOUT",n.duration=t.timeout,e.log.error("Timeout",{id:d._id,milliseconds:t.timeout}),t.callback(n,d)}function r(){if(l)return e.log.debug("Ignoring timed out state change",{state:d.readyState,id:d.id});if(e.log.debug("State change",{state:d.readyState,id:d.id,timed_out:l}),d.readyState===a.OPENED){e.log.debug("Request started",{id:d.id});for(var n in t.headers)d.setRequestHeader(n,t.headers[n])}else d.readyState===a.HEADERS_RECEIVED?o():d.readyState===a.LOADING?(o(),s()):d.readyState===a.DONE&&(o(),s(),u())}function o(){if(!m.response){if(m.response=!0,e.log.debug("Got response",{id:d.id,status:d.status}),clearTimeout(d.timeoutTimer),d.statusCode=d.status,p&&0==d.statusCode){var n=new Error("CORS request rejected: "+t.uri);return n.cors="rejected",m.loading=!0,m.end=!0,t.callback(n,d)}t.onResponse(null,d)}}function s(){m.loading||(m.loading=!0,e.log.debug("Response body loading",{id:d.id}))}function u(){if(!m.end){if(m.end=!0,e.log.debug("Request done",{id:d.id}),d.body=d.responseText,t.json)try{d.body=JSON.parse(d.responseText)}catch(n){return t.callback(n,d)}t.callback(null,d,d.body)}}var d=new a,l=!1,p=i(t.uri),f="withCredentials"in d;if(c+=1,d.seq_id=c,d.id=c+": "+t.method+" "+t.uri,d._id=d.id,p&&!f){var h=new Error("Browser does not support cross-origin request: "+t.uri);return h.cors="unsupported",t.callback(h,d)}d.timeoutTimer=setTimeout(n,t.timeout);var m={response:!1,loading:!1,end:!1};return d.onreadystatechange=r,d.open(t.method,t.uri,!0),p&&(d.withCredentials=!!t.withCredentials),d.send(t.body),d}function n(){}function r(){var e,t,r={},i=["trace","debug","info","warn","error"];for(t=0;t<i.length;t++)e=i[t],r[e]=n,"undefined"!=typeof console&&console&&console[e]&&(r[e]=o(console,e));return r}function o(e,t){function n(n,r){return"object"==typeof r&&(n+=" "+JSON.stringify(r)),e[t].call(e,n)}return n}function i(e){var t,n=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/;try{t=location.href}catch(r){t=document.createElement("a"),t.href="",t=t.href}var o=n.exec(t.toLowerCase())||[],i=n.exec(e.toLowerCase()),s=!(!i||i[1]==o[1]&&i[2]==o[2]&&(i[3]||("http:"===i[1]?80:443))==(o[3]||("http:"===o[1]?80:443)));return s}function s(e){var t,n,r,o,i,s,a,u,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",d=0,l=0,p="",f=[];if(!e)return e;do t=e.charCodeAt(d++),n=e.charCodeAt(d++),r=e.charCodeAt(d++),u=t<<16|n<<8|r,o=u>>18&63,i=u>>12&63,s=u>>6&63,a=63&u,f[l++]=c.charAt(o)+c.charAt(i)+c.charAt(s)+c.charAt(a);while(d<e.length);switch(p=f.join(""),e.length%3){case 1:p=p.slice(0,-2)+"==";break;case 2:p=p.slice(0,-1)+"="}return p}var a=XMLHttpRequest;if(!a)throw new Error("missing XMLHttpRequest");e.log={trace:n,debug:n,info:n,warn:n,error:n};var u=18e4,c=0;e.withCredentials=!1,e.DEFAULT_TIMEOUT=u,e.defaults=function(t){var n=function(e){var n=function(n,r){n="string"==typeof n?{uri:n}:JSON.parse(JSON.stringify(n));for(var o in t)void 0===n[o]&&(n[o]=t[o]);return e(n,r)};return n},r=n(e);return r.get=n(e.get),r.post=n(e.post),r.put=n(e.put),r.head=n(e.head),r};var d=["get","put","post","head"];return d.forEach(function(t){var n=t.toUpperCase(),r=t.toLowerCase();e[r]=function(t){"string"==typeof t?t={method:n,uri:t}:(t=JSON.parse(JSON.stringify(t)),t.method=n);var r=[t].concat(Array.prototype.slice.apply(arguments,[1]));return e.apply(this,r)}}),e.couch=function(t,r){function o(e,t,n){if(e)return r(e,t,n);if((t.statusCode<200||t.statusCode>299)&&n.error){e=new Error("CouchDB error: "+(n.error.reason||n.error.error));for(var o in n)e[o]=n[o];return r(e,t,n)}return r(e,t,n)}"string"==typeof t&&(t={uri:t}),t.json=!0,t.body&&(t.json=t.body),delete t.body,r=r||n;var i=e(t,o);return i},e})},{}],21:[function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function o(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,o,a,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[e],s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(o=arguments.length,a=new Array(o-1),u=1;o>u;u++)a[u-1]=arguments[u];n.apply(this,a)}else if(i(n)){for(o=arguments.length,a=new Array(o-1),u=1;o>u;u++)a[u-1]=arguments[u];for(c=n.slice(),o=c.length,u=0;o>u;u++)c[u].apply(this,a)}return!0},n.prototype.addListener=function(e,t){var o;if(!r(t))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?i(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,i(this._events[e])&&!this._events[e].warned){var o;o=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,o&&o>0&&this._events[e].length>o&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())}return this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),o||(o=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var o=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,o,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],s=n.length,o=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){o=a;break}if(0>o)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0}},{}],22:[function(e,t){function n(){c=!1,s.length?u=s.concat(u):d=-1,u.length&&r()}function r(){if(!c){var e=setTimeout(n);c=!0;for(var t=u.length;t;){for(s=u,u=[];++d<t;)s[d].run();d=-1,t=u.length}s=null,c=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function i(){}var s,a=t.exports={},u=[],c=!1,d=-1;a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new o(e,t)),1!==u.length||c||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=i,a.addListener=i,a.once=i,a.off=i,a.removeListener=i,a.removeAllListeners=i,a.emit=i,a.binding=function(){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],23:[function(e,t,n){(function(e){!function(e){"use strict";if("function"==typeof bootstrap)bootstrap("promise",e);else if("object"==typeof n&&"object"==typeof t)t.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeQ=e}else{if("undefined"==typeof window&&"undefined"==typeof self)throw new Error("This environment was not anticipated by Q. Please file a bug.");var r="undefined"!=typeof window?window:self,o=r.Q;r.Q=e(),r.Q.noConflict=function(){return r.Q=o,this}}}(function(){"use strict";function t(e){return function(){return J.apply(e,arguments)}}function n(e){return e===Object(e)}function r(e){return"[object StopIteration]"===re(e)||e instanceof W}function o(e,t){if($&&t.stack&&"object"==typeof e&&null!==e&&e.stack&&-1===e.stack.indexOf(oe)){for(var n=[],r=t;r;r=r.source)r.stack&&n.unshift(r.stack);n.unshift(e.stack);var o=n.join("\n"+oe+"\n");e.stack=i(o)}}function i(e){for(var t=e.split("\n"),n=[],r=0;r<t.length;++r){var o=t[r];u(o)||s(o)||!o||n.push(o)}return n.join("\n")}function s(e){return-1!==e.indexOf("(module.js:")||-1!==e.indexOf("(node.js:")}function a(e){var t=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(e);if(t)return[t[1],Number(t[2])];var n=/at ([^ ]+):(\d+):(?:\d+)$/.exec(e);if(n)return[n[1],Number(n[2])];var r=/.*@(.+):(\d+)$/.exec(e);return r?[r[1],Number(r[2])]:void 0}function u(e){var t=a(e);if(!t)return!1;var n=t[0],r=t[1];return n===H&&r>=B&&ce>=r}function c(){if($)try{throw new Error}catch(e){var t=e.stack.split("\n"),n=t[0].indexOf("@")>0?t[1]:t[2],r=a(n);if(!r)return;return H=r[0],r[1]}}function d(e,t,n){return function(){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(t+" is deprecated, use "+n+" instead.",new Error("").stack),e.apply(e,arguments)}}function l(e){return e instanceof m?e:_(e)?x(e):k(e)}function p(){function e(e){t=e,i.source=e,z(n,function(t,n){l.nextTick(function(){e.promiseDispatch.apply(e,n)})},void 0),n=void 0,r=void 0}var t,n=[],r=[],o=ee(p.prototype),i=ee(m.prototype);if(i.promiseDispatch=function(e,o,i){var s=X(arguments);n?(n.push(s),"when"===o&&i[1]&&r.push(i[1])):l.nextTick(function(){t.promiseDispatch.apply(t,s)})},i.valueOf=function(){if(n)return i;var e=y(t);return g(e)&&(t=e),e},i.inspect=function(){return t?t.inspect():{state:"pending"}},l.longStackSupport&&$)try{throw new Error}catch(s){i.stack=s.stack.substring(s.stack.indexOf("\n")+1)}return o.promise=i,o.resolve=function(n){t||e(l(n))},o.fulfill=function(n){t||e(k(n))},o.reject=function(n){t||e(I(n))},o.notify=function(e){t||z(r,function(t,n){l.nextTick(function(){n(e)})},void 0)},o}function f(e){if("function"!=typeof e)throw new TypeError("resolver must be a function.");var t=p();try{e(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}return t.promise}function h(e){return f(function(t,n){for(var r=0,o=e.length;o>r;r++)l(e[r]).then(t,n)})}function m(e,t,n){void 0===t&&(t=function(e){return I(new Error("Promise does not support operation: "+e))}),void 0===n&&(n=function(){return{state:"unknown"}});var r=ee(m.prototype);if(r.promiseDispatch=function(n,o,i){var s;try{s=e[o]?e[o].apply(r,i):t.call(r,o,i)}catch(a){s=I(a)}n&&n(s)},r.inspect=n,n){var o=n();"rejected"===o.state&&(r.exception=o.reason),r.valueOf=function(){var e=n();return"pending"===e.state||"rejected"===e.state?r:e.value}}return r}function v(e,t,n,r){return l(e).then(t,n,r)}function y(e){if(g(e)){var t=e.inspect();if("fulfilled"===t.state)return t.value}return e}function g(e){return e instanceof m}function _(e){return n(e)&&"function"==typeof e.then}function E(e){return g(e)&&"pending"===e.inspect().state}function S(e){return!g(e)||"fulfilled"===e.inspect().state}function w(e){return g(e)&&"rejected"===e.inspect().state}function b(){ie.length=0,se.length=0,ue||(ue=!0)}function T(t,n){ue&&("object"==typeof e&&"function"==typeof e.emit&&l.nextTick.runAfter(function(){-1!==Y(se,t)&&(e.emit("unhandledRejection",n,t),ae.push(t))}),se.push(t),ie.push(n&&"undefined"!=typeof n.stack?n.stack:"(no stack) "+n))}function R(t){if(ue){var n=Y(se,t);-1!==n&&("object"==typeof e&&"function"==typeof e.emit&&l.nextTick.runAfter(function(){var r=Y(ae,t);-1!==r&&(e.emit("rejectionHandled",ie[n],t),ae.splice(r,1))}),se.splice(n,1),ie.splice(n,1))}}function I(e){var t=m({when:function(t){return t&&R(this),t?t(e):this}},function(){return this},function(){return{state:"rejected",reason:e}});return T(t,e),t}function k(e){return m({when:function(){return e},get:function(t){return e[t]},set:function(t,n){e[t]=n},"delete":function(t){delete e[t]},post:function(t,n){return null===t||void 0===t?e.apply(void 0,n):e[t].apply(e,n)},apply:function(t,n){return e.apply(t,n)},keys:function(){return ne(e)}},void 0,function(){return{state:"fulfilled",value:e}})}function x(e){var t=p();return l.nextTick(function(){try{e.then(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}}),t.promise}function C(e){return m({isDef:function(){}},function(t,n){return P(e,t,n)},function(){return l(e).inspect()})}function A(e,t,n){return l(e).spread(t,n)}function U(e){return function(){function t(e,t){var s;if("undefined"==typeof StopIteration){try{s=n[e](t)}catch(a){return I(a)}return s.done?l(s.value):v(s.value,o,i)}try{s=n[e](t)}catch(a){return r(a)?l(a.value):I(a)}return v(s,o,i)}var n=e.apply(this,arguments),o=t.bind(t,"next"),i=t.bind(t,"throw");return o()}}function M(e){l.done(l.async(e)())}function O(e){throw new W(e)}function L(e){return function(){return A([this,q(arguments)],function(t,n){return e.apply(t,n)})}}function P(e,t,n){return l(e).dispatch(t,n)}function q(e){return v(e,function(e){var t=0,n=p();return z(e,function(r,o,i){var s;g(o)&&"fulfilled"===(s=o.inspect()).state?e[i]=s.value:(++t,v(o,function(r){e[i]=r,0===--t&&n.resolve(e)},n.reject,function(e){n.notify({index:i,value:e})}))},void 0),0===t&&n.resolve(e),n.promise})}function j(e){if(0===e.length)return l.resolve();var t=l.defer(),n=0;return z(e,function(r,o,i){function s(e){t.resolve(e)}function a(){n--,0===n&&t.reject(new Error("Can't get fulfillment value from any promise, all promises were rejected."))}function u(e){t.notify({index:i,value:e})}var c=e[i];n++,v(c,s,a,u)},void 0),t.promise}function N(e){return v(e,function(e){return e=Z(e,l),v(q(Z(e,function(e){return v(e,G,G)})),function(){return e})})}function F(e){return l(e).allSettled()}function D(e,t){return l(e).then(void 0,void 0,t)}function V(e,t){return l(e).nodeify(t)}var $=!1;try{throw new Error}catch(K){$=!!K.stack}var H,W,B=c(),G=function(){},Q=function(){function t(){for(var e,t;r.next;)r=r.next,e=r.task,r.task=void 0,t=r.domain,t&&(r.domain=void 0,t.enter()),n(e,t);for(;u.length;)e=u.pop(),n(e);i=!1}function n(e,n){try{e()}catch(r){if(a)throw n&&n.exit(),setTimeout(t,0),n&&n.enter(),r;setTimeout(function(){throw r},0)}n&&n.exit()}var r={task:void 0,next:null},o=r,i=!1,s=void 0,a=!1,u=[];if(Q=function(t){o=o.next={task:t,domain:a&&e.domain,next:null},i||(i=!0,s())},"object"==typeof e&&"[object process]"===e.toString()&&e.nextTick)a=!0,s=function(){e.nextTick(t)};else if("function"==typeof setImmediate)s="undefined"!=typeof window?setImmediate.bind(window,t):function(){setImmediate(t)};else if("undefined"!=typeof MessageChannel){var c=new MessageChannel;c.port1.onmessage=function(){s=d,c.port1.onmessage=t,t()};var d=function(){c.port2.postMessage(0)};s=function(){setTimeout(t,0),d()}}else s=function(){setTimeout(t,0)};return Q.runAfter=function(e){u.push(e),i||(i=!0,s())},Q}(),J=Function.call,X=t(Array.prototype.slice),z=t(Array.prototype.reduce||function(e,t){var n=0,r=this.length;if(1===arguments.length)for(;;){if(n in this){t=this[n++];break}if(++n>=r)throw new TypeError}for(;r>n;n++)n in this&&(t=e(t,this[n],n));return t}),Y=t(Array.prototype.indexOf||function(e){for(var t=0;t<this.length;t++)if(this[t]===e)return t;return-1}),Z=t(Array.prototype.map||function(e,t){var n=this,r=[];return z(n,function(o,i,s){r.push(e.call(t,i,s,n))},void 0),r}),ee=Object.create||function(e){function t(){}return t.prototype=e,new t},te=t(Object.prototype.hasOwnProperty),ne=Object.keys||function(e){var t=[];for(var n in e)te(e,n)&&t.push(n);return t},re=t(Object.prototype.toString);W="undefined"!=typeof ReturnValue?ReturnValue:function(e){this.value=e};var oe="From previous event:";l.resolve=l,l.nextTick=Q,l.longStackSupport=!1,"object"==typeof e&&e&&e.env&&e.env.Q_DEBUG&&(l.longStackSupport=!0),
l.defer=p,p.prototype.makeNodeResolver=function(){var e=this;return function(t,n){t?e.reject(t):e.resolve(arguments.length>2?X(arguments,1):n)}},l.Promise=f,l.promise=f,f.race=h,f.all=q,f.reject=I,f.resolve=l,l.passByCopy=function(e){return e},m.prototype.passByCopy=function(){return this},l.join=function(e,t){return l(e).join(t)},m.prototype.join=function(e){return l([this,e]).spread(function(e,t){if(e===t)return e;throw new Error("Can't join: not the same: "+e+" "+t)})},l.race=h,m.prototype.race=function(){return this.then(l.race)},l.makePromise=m,m.prototype.toString=function(){return"[object Promise]"},m.prototype.then=function(e,t,n){function r(t){try{return"function"==typeof e?e(t):t}catch(n){return I(n)}}function i(e){if("function"==typeof t){o(e,a);try{return t(e)}catch(n){return I(n)}}return I(e)}function s(e){return"function"==typeof n?n(e):e}var a=this,u=p(),c=!1;return l.nextTick(function(){a.promiseDispatch(function(e){c||(c=!0,u.resolve(r(e)))},"when",[function(e){c||(c=!0,u.resolve(i(e)))}])}),a.promiseDispatch(void 0,"when",[void 0,function(e){var t,n=!1;try{t=s(e)}catch(r){if(n=!0,!l.onerror)throw r;l.onerror(r)}n||u.notify(t)}]),u.promise},l.tap=function(e,t){return l(e).tap(t)},m.prototype.tap=function(e){return e=l(e),this.then(function(t){return e.fcall(t).thenResolve(t)})},l.when=v,m.prototype.thenResolve=function(e){return this.then(function(){return e})},l.thenResolve=function(e,t){return l(e).thenResolve(t)},m.prototype.thenReject=function(e){return this.then(function(){throw e})},l.thenReject=function(e,t){return l(e).thenReject(t)},l.nearer=y,l.isPromise=g,l.isPromiseAlike=_,l.isPending=E,m.prototype.isPending=function(){return"pending"===this.inspect().state},l.isFulfilled=S,m.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},l.isRejected=w,m.prototype.isRejected=function(){return"rejected"===this.inspect().state};var ie=[],se=[],ae=[],ue=!0;l.resetUnhandledRejections=b,l.getUnhandledReasons=function(){return ie.slice()},l.stopUnhandledRejectionTracking=function(){b(),ue=!1},b(),l.reject=I,l.fulfill=k,l.master=C,l.spread=A,m.prototype.spread=function(e,t){return this.all().then(function(t){return e.apply(void 0,t)},t)},l.async=U,l.spawn=M,l["return"]=O,l.promised=L,l.dispatch=P,m.prototype.dispatch=function(e,t){var n=this,r=p();return l.nextTick(function(){n.promiseDispatch(r.resolve,e,t)}),r.promise},l.get=function(e,t){return l(e).dispatch("get",[t])},m.prototype.get=function(e){return this.dispatch("get",[e])},l.set=function(e,t,n){return l(e).dispatch("set",[t,n])},m.prototype.set=function(e,t){return this.dispatch("set",[e,t])},l.del=l["delete"]=function(e,t){return l(e).dispatch("delete",[t])},m.prototype.del=m.prototype["delete"]=function(e){return this.dispatch("delete",[e])},l.mapply=l.post=function(e,t,n){return l(e).dispatch("post",[t,n])},m.prototype.mapply=m.prototype.post=function(e,t){return this.dispatch("post",[e,t])},l.send=l.mcall=l.invoke=function(e,t){return l(e).dispatch("post",[t,X(arguments,2)])},m.prototype.send=m.prototype.mcall=m.prototype.invoke=function(e){return this.dispatch("post",[e,X(arguments,1)])},l.fapply=function(e,t){return l(e).dispatch("apply",[void 0,t])},m.prototype.fapply=function(e){return this.dispatch("apply",[void 0,e])},l["try"]=l.fcall=function(e){return l(e).dispatch("apply",[void 0,X(arguments,1)])},m.prototype.fcall=function(){return this.dispatch("apply",[void 0,X(arguments)])},l.fbind=function(e){var t=l(e),n=X(arguments,1);return function(){return t.dispatch("apply",[this,n.concat(X(arguments))])}},m.prototype.fbind=function(){var e=this,t=X(arguments);return function(){return e.dispatch("apply",[this,t.concat(X(arguments))])}},l.keys=function(e){return l(e).dispatch("keys",[])},m.prototype.keys=function(){return this.dispatch("keys",[])},l.all=q,m.prototype.all=function(){return q(this)},l.any=j,m.prototype.any=function(){return j(this)},l.allResolved=d(N,"allResolved","allSettled"),m.prototype.allResolved=function(){return N(this)},l.allSettled=F,m.prototype.allSettled=function(){return this.then(function(e){return q(Z(e,function(e){function t(){return e.inspect()}return e=l(e),e.then(t,t)}))})},l.fail=l["catch"]=function(e,t){return l(e).then(void 0,t)},m.prototype.fail=m.prototype["catch"]=function(e){return this.then(void 0,e)},l.progress=D,m.prototype.progress=function(e){return this.then(void 0,void 0,e)},l.fin=l["finally"]=function(e,t){return l(e)["finally"](t)},m.prototype.fin=m.prototype["finally"]=function(e){return e=l(e),this.then(function(t){return e.fcall().then(function(){return t})},function(t){return e.fcall().then(function(){throw t})})},l.done=function(e,t,n,r){return l(e).done(t,n,r)},m.prototype.done=function(t,n,r){var i=function(e){l.nextTick(function(){if(o(e,s),!l.onerror)throw e;l.onerror(e)})},s=t||n||r?this.then(t,n,r):this;"object"==typeof e&&e&&e.domain&&(i=e.domain.bind(i)),s.then(void 0,i)},l.timeout=function(e,t,n){return l(e).timeout(t,n)},m.prototype.timeout=function(e,t){var n=p(),r=setTimeout(function(){t&&"string"!=typeof t||(t=new Error(t||"Timed out after "+e+" ms"),t.code="ETIMEDOUT"),n.reject(t)},e);return this.then(function(e){clearTimeout(r),n.resolve(e)},function(e){clearTimeout(r),n.reject(e)},n.notify),n.promise},l.delay=function(e,t){return void 0===t&&(t=e,e=void 0),l(e).delay(t)},m.prototype.delay=function(e){return this.then(function(t){var n=p();return setTimeout(function(){n.resolve(t)},e),n.promise})},l.nfapply=function(e,t){return l(e).nfapply(t)},m.prototype.nfapply=function(e){var t=p(),n=X(e);return n.push(t.makeNodeResolver()),this.fapply(n).fail(t.reject),t.promise},l.nfcall=function(e){var t=X(arguments,1);return l(e).nfapply(t)},m.prototype.nfcall=function(){var e=X(arguments),t=p();return e.push(t.makeNodeResolver()),this.fapply(e).fail(t.reject),t.promise},l.nfbind=l.denodeify=function(e){var t=X(arguments,1);return function(){var n=t.concat(X(arguments)),r=p();return n.push(r.makeNodeResolver()),l(e).fapply(n).fail(r.reject),r.promise}},m.prototype.nfbind=m.prototype.denodeify=function(){var e=X(arguments);return e.unshift(this),l.denodeify.apply(void 0,e)},l.nbind=function(e,t){var n=X(arguments,2);return function(){function r(){return e.apply(t,arguments)}var o=n.concat(X(arguments)),i=p();return o.push(i.makeNodeResolver()),l(r).fapply(o).fail(i.reject),i.promise}},m.prototype.nbind=function(){var e=X(arguments,0);return e.unshift(this),l.nbind.apply(void 0,e)},l.nmapply=l.npost=function(e,t,n){return l(e).npost(t,n)},m.prototype.nmapply=m.prototype.npost=function(e,t){var n=X(t||[]),r=p();return n.push(r.makeNodeResolver()),this.dispatch("post",[e,n]).fail(r.reject),r.promise},l.nsend=l.nmcall=l.ninvoke=function(e,t){var n=X(arguments,2),r=p();return n.push(r.makeNodeResolver()),l(e).dispatch("post",[t,n]).fail(r.reject),r.promise},m.prototype.nsend=m.prototype.nmcall=m.prototype.ninvoke=function(e){var t=X(arguments,1),n=p();return t.push(n.makeNodeResolver()),this.dispatch("post",[e,t]).fail(n.reject),n.promise},l.nodeify=V,m.prototype.nodeify=function(e){return e?void this.then(function(t){l.nextTick(function(){e(null,t)})},function(t){l.nextTick(function(){e(t)})}):this},l.noConflict=function(){throw new Error("Q.noConflict only works when Q is used as a global")};var ce=c();return l})}).call(this,e("_process"))},{_process:22}]},{},[1]);