diff --git a/dist/min/ngWebmakerLogin.min.js b/dist/min/ngWebmakerLogin.min.js index 4081cfd..a0c4dfe 100644 --- a/dist/min/ngWebmakerLogin.min.js +++ b/dist/min/ngWebmakerLogin.min.js @@ -1,2 +1,2 @@ -!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o>18&63,h2=bits>>12&63,h3=bits>>6&63,h4=63&bits,tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4);while(i299)&&body.error){er=new Error("CouchDB error: "+(body.error.reason||body.error.error));for(var key in body)er[key]=body[key];return callback(er,resp,body)}return callback(er,resp,body)}"string"==typeof options&&(options={uri:options}),options.json=!0,options.body&&(options.json=options.body),delete options.body,callback=callback||noop;var xhr=request(options,couch_handler);return xhr},module.exports=request},{}],2:[function(require,module){!function(){var cookiejs={serialize:function(name,val,opt){opt=opt||{};var enc=opt.encode||encode,pairs=[name+"="+enc(val)];if(null!=opt.maxAge){var maxAge=opt.maxAge-0;if(isNaN(maxAge))throw new Error("maxAge should be a Number");pairs.push("Max-Age="+maxAge)}return opt.domain&&pairs.push("Domain="+opt.domain),opt.path&&pairs.push("Path="+opt.path),opt.expires&&pairs.push("Expires="+opt.expires.toUTCString()),opt.httpOnly&&pairs.push("HttpOnly"),opt.secure&&pairs.push("Secure"),pairs.join("; ")},parse:function(str,opt){opt=opt||{};var obj={},pairs=str.split(/; */),dec=opt.decode||decode;return pairs.forEach(function(pair){var eq_idx=pair.indexOf("=");if(!(0>eq_idx)){var key=pair.substr(0,eq_idx).trim(),val=pair.substr(++eq_idx,pair.length).trim();if('"'==val[0]&&(val=val.slice(1,-1)),void 0==obj[key])try{obj[key]=dec(val)}catch(e){obj[key]=val}}}),obj}},encode=encodeURIComponent,decode=decodeURIComponent;"undefined"!=typeof module&&module.exports?module.exports=cookiejs:"function"==typeof define&&define.amd?define(function(){return cookiejs}):window.cookiejs=cookiejs}()},{}],3:[function(require,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified "error" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],4:[function(require,module){!function(global,factory){"function"==typeof define&&define.amd?define(factory):"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=factory():global.analytics=factory()}(this,function(){function toTitleCase(s){var smallWords=/^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;return s=trim(s),s.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g,function(match,index,title){return index>0&&index+match.length!==title.length&&match.search(smallWords)>-1&&":"!==title.charAt(index-2)&&("-"!==title.charAt(index+match.length)||"-"===title.charAt(index-1))&&title.charAt(index-1).search(/[^\s-]/)<0?match.toLowerCase():match.substr(1).search(/[A-Z]|\../)>-1?match:match.charAt(0).toUpperCase()+match.substr(1)})}function trim(s){return s.replace(/^\s+|\s+$/g,"")}function mightBeEmail(s){return/[^@]+@[^@]+/.test(s)}function warn(msg){console.warn("[analytics] "+msg)}function _gaEvent(options){if("function"==typeof ga){var fieldObject={hitType:"event",eventCategory:_category,eventAction:options.action};options.label&&(fieldObject.eventLabel=options.label),(options.value||0===options.value)&&(fieldObject.eventValue=options.value),options.nonInteraction===!0&&(fieldObject.nonInteraction=1),ga("send",fieldObject)}var eventArgs=["_trackEvent",_category,options.action];options.label&&(eventArgs[3]=options.label),(options.value||0===options.value)&&(eventArgs[4]=options.value),options.nonInteraction===!0&&(eventArgs[5]=!0),_gaq.push(eventArgs)}function event(action,options){options=options||{};var eventOptions={},label=options.label,value=options.value,nonInteraction=options.noninteraction||options.nonInteraction;return action?(mightBeEmail(action)&&(warn("`action` arg looks like an email address, redacting."),action=_redacted),eventOptions.action=toTitleCase(action),label&&("string"!=typeof label?warn("Expected `label` arg to be a String."):(mightBeEmail(label)&&(warn("`label` arg looks like an email address, redacting."),label=_redacted),eventOptions.label=trim(label))),(value||0===value)&&("number"!=typeof value?warn("Expected `value` arg to be a Number."):eventOptions.value=0|value),nonInteraction&&("boolean"!=typeof nonInteraction?warn("Expected `noninteraction` arg to be a Boolean."):eventOptions.nonInteraction=nonInteraction===!0),void _gaEvent(eventOptions)):void warn("Expected `action` arg.")}function prefixVirtualPageview(s){return/^\/virtual\//.test(s)?s:(s=s.replace(/^[/]?/,"/"),"/virtual"+s)}function _gaVirtualPageView(options){if("function"==typeof ga){var fieldObject={hitType:"pageview",page:options.virtualPagePath};ga("send",fieldObject)}var eventArgs=["_trackPageview",options.virtualPagePath];_gaq.push(eventArgs)}function virtualPageview(virtualPagePath){if(!virtualPagePath)return void warn("Expected `virtualPagePath` arg.");virtualPagePath=trim(virtualPagePath);var eventOptions={};eventOptions.virtualPagePath=prefixVirtualPageview(virtualPagePath),_gaVirtualPageView(eventOptions)}function _optimizely(options){var eventArgs=["trackEvent",options.action];if(options.revenue){var args={revenue:options.revenue};eventArgs[2]=args}optimizely.push(eventArgs)}function conversionGoal(action,options){options=options||{};var eventOptions={},valueInCents=options.valueInCents;return action?(eventOptions.action=trim(action),valueInCents&&("number"==typeof valueInCents&&valueInCents%1===0?eventOptions.revenue=valueInCents:warn("Expected `valueInCents` arg to be an integer.")),void _optimizely(eventOptions)):void warn("Expected `action` arg.")}this._gaq||(this._gaq=[]),this.optimizely||(this.optimizely=[]);var _category=location.hostname,_redacted="REDACTED (Potential Email Address)";return{event:event,virtualPageview:virtualPageview,conversionGoal:conversionGoal}})},{}],5:[function(require){var ngModule=angular.module("ngWebmakerLogin",["templates-ngWebmakerLogin"]);ngModule.factory("loginOptions",["$rootScope",function($rootScope){return window.angularConfig?{csrfToken:window.angularConfig.csrf,paths:window.angularConfig.loginPaths}:window.eventsConfig?{csrfToken:window.eventsConfig.csrf,paths:window.eventsConfig.loginPaths}:$rootScope.WMP.config?{csrfToken:$rootScope.WMP.config.csrf,paths:$rootScope.WMP.config.loginPaths}:(console.warn("Could not locate a config on window.angularConfig, window.eventsConfig or $rootScope.WMP.config"),{})}]),ngModule.factory("focus",["$timeout",function($timeout){return function(selector){$timeout(function(){var el=angular.element(selector);el&&el[0]&&el[0].focus()},0)}}]),ngModule.directive("bindTrustedHtml",["$compile",function($compile){return function(scope,element,attrs){scope.$watch(function(scope){return scope.$eval(attrs.bindTrustedHtml)},function(value){element.html(value),$compile(element.contents())(scope)})}}]),ngModule.factory("wmLoginCore",["$rootScope","$location","$timeout","loginOptions",function($rootScope,$location,$timeout,loginOptions){function scrubSearch(){$location.search("uid",null),$location.search("token",null),$location.search("validFor",null)}var LoginCore=require("../core"),core=new LoginCore(loginOptions),searchObj=$location.search();return $rootScope._user={},searchObj.uid&&searchObj.token&&(core.on("signedIn",function(user){$timeout(function(){scrubSearch(),$rootScope._user=user},0)}),core.on("signinFailed",function(uid){$timeout(function(){console.error("login failed for uid: "+uid),scrubSearch(),$rootScope.expiredLoginLink=!0,$rootScope.signin(uid)},0)}),core.instantLogin(searchObj.uid,searchObj.token,searchObj.validFor)),core.on("verified",function(user){$timeout(function(){$rootScope._user=user?user:{},$rootScope.$broadcast("verified",user)},0)}),core.verify(),core}]),ngModule.directive("wmJoinWebmaker",[function(){return{restrict:"A",scope:{showCTA:"=showcta"},link:function($scope,$element){$element.on("click",function(){$scope.joinWebmaker()})},controller:["$rootScope","$scope","$modal","$timeout","focus","wmLoginCore",function($rootScope,$scope,$modal,$timeout,focus,wmLoginCore){function joinModalController($scope,$modalInstance,email,username,showCTA,agreeToTerms){var MODALSTATE={inputEmail:0,inputUsername:1,welcome:2};$scope.MODALSTATE=MODALSTATE,$scope.currentState=MODALSTATE.inputEmail,$scope.form={},$scope.user={},$scope.sendingRequest=!1;var joinController=wmLoginCore.joinWebmaker(showCTA);email&&($scope.user.email=email),username&&($scope.user.username=username),$scope.user.agree=agreeToTerms,joinController.on("sendingRequest",function(state){$timeout(function(){$scope.sendingRequest=state},0)}),joinController.on("displayEmailInput",function(){$timeout(function(){$scope.currentState=MODALSTATE.inputEmail,focus('input[focus-on="create-user-email"]'),void 0!==$scope.user.email&&joinController.validateEmail($scope.user.email)&&void 0!==$scope.user.agree&&(joinController.submitEmail($scope.user.agree),$scope.user.agree&&($scope.skippedEmail=!0,joinController.validateUsername(username)))},0)}),joinController.on("displayUsernameInput",function(){$timeout(function(){$scope.currentState=MODALSTATE.inputUsername,focus('input[focus-on="create-user-username"]')},0)}),joinController.on("displayWelcome",function(user,showCTA){$timeout(function(){$rootScope._user=user,showCTA?$scope.welcomeModalIdx=0:$scope.simpleCTA=!0,$scope.currentState=MODALSTATE.welcome},0)}),joinController.on("displayAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!1)},0)}),joinController.on("hideAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!0)},0)}),$scope.validateEmail=function(){$scope.user.email&&joinController.validateEmail($scope.user.email)},$scope.submitEmail=function(){joinController.submitEmail($scope.user.agree)},$scope.agreeToTermsChanged=function(){joinController.agreeToTermsChanged($scope.user.agree)},$scope.validateUsername=function(){joinController.validateUsername($scope.user.username)},$scope.submitUser=function(){joinController.submitUser($scope.user)},$scope.close=function(){$modalInstance.close()},$scope.switchToSignin=function(){$modalInstance.close(),$rootScope.signin($scope.user.email)},joinController.start()}$scope.joinWebmaker=$rootScope.joinWebmaker=function(email,username,agreeToTerms){$modal.open({templateUrl:"join-webmaker-modal.html",controller:["$scope","$modalInstance","email","username","showCTA","agreeToTerms",joinModalController],resolve:{email:function(){return email},username:function(){return username},showCTA:function(){return!!$scope.showCTA},agreeToTerms:function(){return agreeToTerms}}})}}]}}]),ngModule.directive("wmSignin",[function(){return{restrict:"A",scope:{disablePersona:"=disablepersona"},link:function($scope,$element){$element.on("click",function(){$scope.signin()})},controller:["$rootScope","$scope","$modal","$timeout","$location","focus","wmLoginCore",function($rootScope,$scope,$modal,$timeout,$location,focus,wmLoginCore){function signinModalController($scope,$modalInstance,uid,passwordWasReset,disablePersona){var MODALSTATE={enterUid:0,checkEmail:1,enterKey:2,enterPassword:3,resetRequestSent:4};$scope.MODALSTATE=MODALSTATE,$scope.currentState=MODALSTATE.enterUid,$scope.passwordWasReset=passwordWasReset,$scope.sendingRequest=!1,$scope.disablePersona=disablePersona,$scope.form={},$scope.user={},uid&&($scope.user.uid=uid);var signinController=wmLoginCore.signIn();signinController.on("sendingRequest",function(state){$timeout(function(){$scope.sendingRequest=state},0)}),signinController.on("displayEnterUid",function(){$timeout(function(){$scope.currentState=MODALSTATE.enterUid,focus('input[focus-on="login-uid"]')},0)}),signinController.on("displayEnterPassword",function(){$timeout(function(){$scope.currentState=MODALSTATE.enterPassword,focus('input[focus-on="enter-password"]')},0)}),signinController.on("displayEnterKey",function(verified){$timeout(function(){$scope.verified=verified,$scope.currentState=MODALSTATE.enterKey,focus('input[focus-on="enter-key"]')},0)}),signinController.on("displayCheckEmail",function(){$timeout(function(){$scope.currentState=MODALSTATE.checkEmail},0)}),signinController.on("displayResetSent",function(){$timeout(function(){$scope.currentState=MODALSTATE.resetRequestSent},0)}),signinController.on("displayAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!1)},0)}),signinController.on("hideAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!0)},0)}),signinController.on("signedIn",function(user){$rootScope._user=user,$modalInstance.close(),$rootScope.$broadcast("login",user)}),$scope.submitUid=function(){signinController.submitUid($scope.user.uid,$location.path())},$scope.enterKey=function(){signinController.displayEnterKey()},$scope.submitKey=function(){signinController.verifyKey($scope.user.uid,$scope.user.key,$scope.user.rememberMe)},$scope.submitPassword=function(){signinController.verifyPassword($scope.user.uid,$scope.user.password,$scope.user.rememberMe)},$scope.requestReset=function(){signinController.requestReset($scope.user.uid)},$scope.close=function(){$scope.user={},$modalInstance.close()},$scope.switchToSignup=function(){var uid=$scope.user.uid,type=signinController.getUidType(uid),email="email"===type?uid:"",username="username"===type?uid:"";$modalInstance.close(),$rootScope.joinWebmaker(email,username)},$scope.usePersona=function(){$rootScope.personaLogin(),$timeout($modalInstance.dismiss,0)},signinController.start()}$scope.signin=$rootScope.signin=function(uid,passwordWasReset){$modal.open({templateUrl:"signin-modal.html",controller:["$scope","$modalInstance","uid","passwordWasReset",signinModalController],resolve:{uid:function(){return uid},passwordWasReset:function(){return passwordWasReset},disablePersona:function(){return $scope.disablePersona}}})}}]}}]),ngModule.directive("wmPasswordReset",[function(){var triggered=!1;return{restrict:"A",controller:["$rootScope","$scope","$location","$timeout","$modal","wmLoginCore",function($rootScope,$scope,$location,$timeout,$modal,wmLoginCore){function passwordResetModalController($scope,$modalInstance,resetCode,uid){function clearSearch(){$location.search("uid",null),$location.search("resetCode",null),$modalInstance.close()}$scope.form={},$scope.password={},$scope.sendingRequest=!1,$scope.eightChars=angular.element("li.eight-chars"),$scope.oneEachCase=angular.element("li.one-each-case"),$scope.oneNumber=angular.element("li.one-number");var resetController=wmLoginCore.resetPassword();resetController.on("sendingRequest",function(state){$timeout(function(){$scope.sendingRequest=state},0)}),resetController.on("displayAlert",function(alertId){$timeout(function(){$scope.form.password.$setValidity(alertId,!1)},0)}),resetController.on("hideAlert",function(alertId){$timeout(function(){$scope.form.password.$setValidity(alertId,!0)},0)}),resetController.on("checkConfirmPassword",function(status){$timeout(function(){$scope.passwordsMatch=status},0)}),resetController.on("passwordCheckResult",function(result,blur){$timeout(function(){return result?($scope.eightCharsState=result.lengthValid?blur?"valid":"":"invalid",$scope.oneEachCaseState=result.caseValid?blur?"valid":"":"invalid",$scope.oneNumberState=result.digitValid?blur?"valid":"":"invalid",void($scope.isValidPassword=result.lengthValid&&result.caseValid&&result.digitValid)):($scope.eightCharsState=$scope.oneEachCaseState=$scope.oneNumberState="default",void($scope.isValidPassword=!1))},0)}),resetController.on("resetSucceeded",function(){$timeout(function(){clearSearch(),$rootScope.signin(uid,!0)},0)}),$scope.checkPasswordStrength=function(blur){resetController.checkPasswordStrength($scope.password.value,blur)},$scope.checkPasswordsMatch=function(blur){$scope.password.confirmValue&&resetController.passwordsMatch($scope.password.value,$scope.password.confirmValue,blur)},$scope.submitResetRequest=function(){resetController.submitResetRequest(uid,resetCode,$scope.password.value)},$scope.close=function(){clearSearch(),$modalInstance.close()}}var searchObj=$location.search();searchObj.resetCode&&searchObj.uid&&!triggered&&(triggered=!0,$modal.open({templateUrl:"reset-modal.html",controller:["$scope","$modalInstance","resetCode","uid",passwordResetModalController],resolve:{resetCode:function(){return searchObj.resetCode},uid:function(){return searchObj.uid}}}))}]}}]),ngModule.factory("wmPersona",["$rootScope","wmLoginCore",function($rootScope,wmLoginCore){var personaController=wmLoginCore.personaLogin();$rootScope.personaLogin=function(){personaController.authenticate()},personaController.on("signedIn",function(user){$rootScope._user=user}),personaController.on("newUser",function(email){$rootScope.joinWebmaker(email)})}]),ngModule.directive("wmPersonaLogin",["wmPersona",function(){return{restrict:"A",link:function($scope,$element){$element.on("click",function(){$scope.personaLogin()})}}}]),ngModule.directive("wmLogout",["$timeout","wmLoginCore",function($timeout){return{restrict:"A",link:function($rootScope,$element){$element.on("click",function(){$rootScope.logout()})},controller:["$rootScope","wmLoginCore",function($rootScope,wmLoginCore){var logoutController=wmLoginCore.logout();logoutController.on("loggedOut",function(){$timeout(function(){$rootScope._user={},$rootScope.$broadcast("logout")},0)}),$rootScope.logout=function(){logoutController.logout()}}]}}])},{"../core":6}],6:[function(require,module){var state=require("./state"),LoginAPI=require("./loginAPI"),Emitter=require("./state/emitter");module.exports=function(options){function verify(){loginAPI.verify(function(err,resp,body){if(err)return emitter.emit("error",err);try{body=JSON.parse(body)}catch(ex){return emitter.emit("error","could not parse json from verify route")}emitter.emit("verified",body.user)})}var loginAPI=new LoginAPI(options),emitter=new Emitter;return window.addEventListener("focus",verify),{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},joinWebmaker:function(showCTA){return new state.JoinController(loginAPI,!!showCTA)},signIn:function(){return new state.SignInController(loginAPI)},resetPassword:function(){return new state.ResetController(loginAPI)},personaLogin:function(){return new state.PersonaController(loginAPI)},logout:function(){return new state.LogoutController(loginAPI)},instantLogin:function(uid,password,validFor){loginAPI.verifyKey(uid,password,validFor,function(err,resp,body){return err||200!==resp.status||!body.user?emitter.emit("signinFailed",uid):void emitter.emit("signedIn",body.user)})},verify:verify}}},{"./loginAPI":7,"./state":11,"./state/emitter":10}],7:[function(require,module){var request=require("browser-request");module.exports=function(options){function doRequest(uri,payload,callback){request({method:"post",uri:uri,timeout:timeout,withCredentials:withCredentials,headers:headers,json:payload},callback)}function uidExists(uid,callback){doRequest(loginUrls.uidExists,{uid:uid},callback)}function checkUsername(username,callback){doRequest(loginUrls.checkUsername,{username:username},callback)}function createUser(user,callback){user.referrer=refferals.refValue(),doRequest(loginUrls.createUser,{user:user,audience:audience},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function sendLoginKey(uid,path,callback){doRequest(loginUrls.request,{uid:uid,path:path},callback)}function verifyKey(uid,key,validFor,callback){doRequest(loginUrls.authenticateToken,{uid:uid,token:key,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments) -})}function verifyPassword(uid,password,validFor,callback){doRequest(loginUrls.verifyPassword,{uid:uid,password:password,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function requestReset(uid,callback){doRequest(loginUrls.requestResetCode,{uid:uid},callback)}function resetPassword(uid,resetCode,password,callback){doRequest(loginUrls.resetPassword,{uid:uid,resetCode:resetCode,newPassword:password},callback)}function personaLogin(assertion,callback){doRequest(loginUrls.authenticate,{assertion:assertion,audience:audience,user:{referrer:refferals.refValue()}},callback)}function logout(callback){doRequest(loginUrls.logout,null,callback)}function verify(callback){doRequest(loginUrls.verify,null,callback)}options=options||{},options.paths=options.paths||{};var refferals=require("./referrals.js")(),loginUrls=require("./loginUrls.js")(options),withCredentials=options.withCredentials===!1?!1:!0,timeout=1e3*(options.timeout||10),headers={"X-CSRF-Token":options.csrfToken},audience=options.audience||window.location.protocol+"//"+window.location.host;return{uidExists:uidExists,checkUsername:checkUsername,createUser:createUser,sendLoginKey:sendLoginKey,verifyKey:verifyKey,verifyPassword:verifyPassword,requestReset:requestReset,resetPassword:resetPassword,personaLogin:personaLogin,logout:logout,verify:verify}}},{"./loginUrls.js":8,"./referrals.js":9,"browser-request":1}],8:[function(require,module){module.exports=function(options){var paths={},host=options.host||"";return paths=options.paths||{},paths.authenticate=options.paths.authenticate||"/authenticate",paths.legacyCreate=options.paths.legacyCreate||"/create",paths.verify=options.paths.verify||"/verify",paths.logout=options.paths.logout||"/logout",paths.checkUsername=options.paths.checkUsername||"/check-username",paths.request=options.paths.request||"/auth/v2/request",paths.uidExists=options.paths.uidExists||"/auth/v2/uid-exists",paths.createUser=options.paths.createUser||"/auth/v2/create",paths.authenticateToken=options.paths.authenticateToken||"/auth/v2/authenticateToken",paths.verifyPassword=options.paths.verifyPassword||"/auth/v2/verify-password",paths.requestResetCode=options.paths.requestResetCode||"/auth/v2/request-reset-code",paths.removePassword=options.paths.removePassword||"/auth/v2/remove-password",paths.enablePasswords=options.paths.enablePasswords||"/auth/v2/enable-passwords",paths.resetPassword=options.paths.resetPassword||"/auth/v2/reset-password",{request:host+paths.request,authenticateToken:host+paths.authenticateToken,authenticate:host+paths.authenticate,legacyCreate:host+paths.legacyCreate,createUser:host+paths.createUser,verify:host+paths.verify,logout:host+paths.logout,uidExists:host+paths.uidExists,checkUsername:host+paths.checkUsername,verifyPassword:host+paths.verifyPassword,requestResetCode:host+paths.requestResetCode,removePassword:host+paths.removePassword,enablePasswords:host+paths.enablePasswords,resetPassword:host+paths.resetPassword}}},{}],9:[function(require,module){var cookiejs=require("cookie-js");module.exports=function(){var referralCookieSettings={domain:location.hostname.split(".").slice(-2).join("."),path:"/",secure:"https:"===location.protocol,expires:new Date(Date.now()+6048e5)},refValue=/ref=((?:\w|-)+)/.exec(window.location.search),cookieRefValue=cookiejs.parse(document.cookie).webmakerReferral;return refValue&&(refValue=refValue[1],cookieRefValue!==refValue&&(document.cookie=cookiejs.serialize("webmakerReferral",refValue,referralCookieSettings),cookieRefValue=refValue)),{clearReferrerCookie:function(){referralCookieSettings.expires=new Date(Date.now()-1e4),document.cookie=cookiejs.serialize("webmakerReferral","expire",referralCookieSettings),referralCookieSettings.expires=new Date(Date.now()+6048e5)},refValue:function(){return cookieRefValue}}}},{"cookie-js":2}],10:[function(require,module){var EventEmitter=require("events").EventEmitter;module.exports=function(){var emitter=new EventEmitter;return{on:function(event,listener){emitter.addListener(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):void emitter.removeAllListeners(event)},emit:function(){emitter.emit.apply(emitter,arguments)}}}},{events:3}],11:[function(require,module){module.exports={JoinController:require("./join.js"),SignInController:require("./signin.js"),ResetController:require("./reset.js"),PersonaController:require("./persona.js"),LogoutController:require("./logout.js")}},{"./join.js":12,"./logout.js":13,"./persona.js":14,"./reset.js":15,"./signin.js":16}],12:[function(require,module){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi,showCTA){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(JOIN_EVENTS.sendingRequest,state,state?!1:!0)}function displayAlert(alertId,forceUpdate){emit(JOIN_EVENTS.displayAlert,alertId,forceUpdate)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alert){emit(JOIN_EVENTS.hideAlert,alert)})}function validateEmailCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.accountExists,!0):void 0}function usernameExistsCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.usernameTaken,!0):void emit(JOIN_EVENTS.displayUsernameInput)}var emitter=new Emitter,JOIN_ALERTS={agreeToTerms:"agreeToTerms",accountExists:"accountExists",invalidEmail:"invalidEmail",invalidUsername:"invalidUsername",usernameTaken:"usernameTaken",serverError:"serverError"},JOIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayUsernameInput:"displayUsernameInput",displayEmailInput:"displayEmailInput",displayWelcome:"displayWelcome"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):emitter.off(event)},start:function(){emit(JOIN_EVENTS.displayEmailInput)},validateEmail:function(email){clearAlerts([JOIN_ALERTS.invalidEmail,JOIN_ALERTS.accountExists,JOIN_ALERTS.serverError]);var valid=validation.isEmail(email);return valid?(setRequestState(!0),loginApi.uidExists(email,validateEmailCallback),!0):(displayAlert(JOIN_ALERTS.invalidEmail),!1)},submitEmail:function(agreeToTerms){return agreeToTerms?void emit(JOIN_EVENTS.displayUsernameInput):displayAlert(JOIN_ALERTS.agreeToTerms)},agreeToTermsChanged:function(agree){agree&&emit(JOIN_EVENTS.hideAlert,JOIN_ALERTS.agreeToTerms)},validateUsername:function(username){if(clearAlerts([JOIN_ALERTS.invalidUsername,JOIN_ALERTS.usernameTaken,JOIN_ALERTS.serverError]),username){var valid=validation.isUsername(username);if(!valid)return displayAlert(JOIN_ALERTS.invalidUsername);setRequestState(!0),loginApi.uidExists(username,usernameExistsCallback)}},submitUser:function(formData){clearAlerts([JOIN_ALERTS.agreeToTerms,JOIN_ALERTS.serverError]);var lang="en-US",html=document.querySelector("html");html.lang&&(lang=html.lang),setRequestState(!0),loginApi.createUser({email:formData.email,username:formData.username,mailingList:formData.subscribeToList,prefLocale:lang},function(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError):(analytics.event("Webmaker New User Created",{nonInteraction:!0}),analytics.conversionGoal("WebmakerNewUserCreated"),void emit(JOIN_EVENTS.displayWelcome,body.user,showCTA))})}}}},{"../validation":17,"./emitter.js":10,"webmaker-analytics":4}],13:[function(require,module){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginAPI){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter;return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},logout:function(){loginAPI.logout(function(err,resp){return err||200!==resp.status?emit("logoutFailed"):(analytics.event("Webmaker Logout Clicked"),void emit("loggedOut"))})}}}},{"./emitter.js":10,"webmaker-analytics":4}],14:[function(require,module){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter,PERSONA_EVENTS={signedIn:"signedIn",newUser:"newUser"},analyticsLabel={label:"persona"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},authenticate:function(){return window.navigator.id?(analytics.event("Persona Login Clicked"),void window.navigator.id.get(function(assertion){return assertion?void loginApi.personaLogin(assertion,function(err,resp,body){return err||200!==resp.status?void analytics.event("Webmaker Login Failed",analyticsLabel):(analytics.event("Webmaker Login Succeeded",analyticsLabel),void(body.user?emit(PERSONA_EVENTS.signedIn,body.user):body.email&&(analytics.event("Webmaker New User Started",analyticsLabel),emit(PERSONA_EVENTS.newUser,body.email))))}):void analytics.event("Webmaker Login Cancelled",analyticsLabel)})):console.error("No persona found. Did you load include.js?")}}}},{"./emitter.js":10,"webmaker-analytics":4}],15:[function(require,module){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(RESET_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(RESET_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(RESET_EVENTS.hideAlert,alertId)}var emitter=new Emitter,RESET_ALERTS={passwordsMustMatch:"passwordsMustMatch",weakPassword:"weakPassword",serverError:"serverError"},RESET_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",resetSucceeded:"resetSucceeded",passwordCheckResult:"passwordCheckResult",checkConfirmPassword:"checkConfirmPassword"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},passwordsMatch:function(password,confimValue,blur){validation.passwordsMatch(password,confimValue)?(hideAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!0)):(blur&&displayAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!1))},checkPasswordStrength:function(password,blur){emit(RESET_EVENTS.passwordCheckResult,validation.checkPasswordStrength(password),blur)},submitResetRequest:function(uid,resetCode,password){hideAlert(RESET_ALERTS.serverError),hideAlert(RESET_ALERTS.weakPassword),setRequestState(!0),loginApi.resetPassword(uid,resetCode,password,function(err,resp){return setRequestState(!1),err||200!==resp.status?displayAlert(400===resp.status?RESET_ALERTS.weakPassword:RESET_ALERTS.serverError):(analytics.event("Webmaker Password Reset Succeeded"),void emit(RESET_EVENTS.resetSucceeded))})}}}},{"../validation":17,"./emitter.js":10,"webmaker-analytics":4}],16:[function(require,module){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(SIGNIN_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(SIGNIN_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(SIGNIN_EVENTS.hideAlert,alertId)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alertId){hideAlert(alertId)})}var emitter=new Emitter,SIGNIN_ALERTS={paswordReset:"paswordReset",noAccount:"noAccount",invalidUid:"invalidUid",serverError:"serverError",invalidKey:"invalidKey",passwordSigninFailed:"passwordSigninFailed",resetRequestFailed:"resetRequestFailed"},SIGNIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayEnterUid:"displayEnterUid",displayEnterPassword:"displayEnterPassword",displayEnterKey:"displayEnterKey",displayCheckEmail:"displayCheckEmail",displayResetSent:"displayResetSent",signedIn:"signedIn"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},start:function(){emit(SIGNIN_EVENTS.displayEnterUid)},submitUid:function(uid,path){clearAlerts([SIGNIN_ALERTS.invalidUid,SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.noAccount]);var valid=validation.isEmail(uid)||validation.isUsername(uid);return valid?(setRequestState(!0),void loginApi.uidExists(uid,function(err,resp,body){if(setRequestState(!1),err||200!==resp.status)return displayAlert(SIGNIN_ALERTS.serverError);var isVerified=body.verified;return body.exists?body.usePasswordLogin?emit(SIGNIN_EVENTS.displayEnterPassword):void loginApi.sendLoginKey(uid,path,function(err){return err?displayAlert(SIGNIN_ALERTS.serverError):void(isVerified?emit(SIGNIN_EVENTS.displayEnterKey,!1):emit(SIGNIN_EVENTS.displayCheckEmail))}):displayAlert(SIGNIN_ALERTS.noAccount)})):displayAlert(SIGNIN_ALERTS.invalidUid)},displayEnterKey:function(){emit(SIGNIN_EVENTS.displayEnterKey,!0)},verifyKey:function(uid,key,rememberMe){clearAlerts([SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.invalidKey]),setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyKey(uid,key,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"key"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.invalidKey)})},verifyPassword:function(uid,password,rememberMe){setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyPassword(uid,password,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"password"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.passwordSigninFailed)})},requestReset:function(uid){setRequestState(!0),loginApi.requestReset(uid,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.status?(analytics.event("Webmaker Password Reset Requested"),void emit(SIGNIN_EVENTS.displayResetSent)):displayAlert(SIGNIN_ALERTS.resetRequestFailed)})},getUidType:function(uid){return validation.isEmail(uid)?"email":validation.isUsername(uid)?"username":null}}}},{"../validation":17,"./emitter.js":10,"webmaker-analytics":4}],17:[function(require,module){var usernameRegex=/^[a-zA-Z0-9\-]{1,20}$/,emailRegex=/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,containsBothCases=/^.*(?=.*[a-z])(?=.*[A-Z]).*$/,containsDigit=/\d/,MIN_PASSWORD_LEN=8;module.exports={isEmail:function(email){return emailRegex.test(email)},isUsername:function(username){return usernameRegex.test(username)},passwordsMatch:function(password,confirmation){return password===confirmation},checkPasswordStrength:function(password){if(!password)return!1;var lengthValid=password.length>=MIN_PASSWORD_LEN,caseValid=!!password.match(containsBothCases),digitValid=!!password.match(containsDigit);return{lengthValid:lengthValid,caseValid:caseValid,digitValid:digitValid}}}},{}]},{},[5]); \ No newline at end of file +!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o>18&63,h2=bits>>12&63,h3=bits>>6&63,h4=63&bits,tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4);while(i299)&&body.error){er=new Error("CouchDB error: "+(body.error.reason||body.error.error));for(var key in body)er[key]=body[key];return callback(er,resp,body)}return callback(er,resp,body)}"string"==typeof options&&(options={uri:options}),options.json=!0,options.body&&(options.json=options.body),delete options.body,callback=callback||noop;var xhr=request(options,couch_handler);return xhr},module.exports=request},{}],2:[function(require,module,exports){!function(){var cookiejs={serialize:function(name,val,opt){opt=opt||{};var enc=opt.encode||encode,pairs=[name+"="+enc(val)];if(null!=opt.maxAge){var maxAge=opt.maxAge-0;if(isNaN(maxAge))throw new Error("maxAge should be a Number");pairs.push("Max-Age="+maxAge)}return opt.domain&&pairs.push("Domain="+opt.domain),opt.path&&pairs.push("Path="+opt.path),opt.expires&&pairs.push("Expires="+opt.expires.toUTCString()),opt.httpOnly&&pairs.push("HttpOnly"),opt.secure&&pairs.push("Secure"),pairs.join("; ")},parse:function(str,opt){opt=opt||{};var obj={},pairs=str.split(/; */),dec=opt.decode||decode;return pairs.forEach(function(pair){var eq_idx=pair.indexOf("=");if(!(0>eq_idx)){var key=pair.substr(0,eq_idx).trim(),val=pair.substr(++eq_idx,pair.length).trim();if('"'==val[0]&&(val=val.slice(1,-1)),void 0==obj[key])try{obj[key]=dec(val)}catch(e){obj[key]=val}}}),obj}},encode=encodeURIComponent,decode=decodeURIComponent;"undefined"!=typeof module&&module.exports?module.exports=cookiejs:"function"==typeof define&&define.amd?define(function(){return cookiejs}):window.cookiejs=cookiejs}()},{}],3:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified "error" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],4:[function(require,module,exports){!function(global,factory){"function"==typeof define&&define.amd?define(factory):"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=factory():global.analytics=factory()}(this,function(){function toTitleCase(s){var smallWords=/^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;return s=trim(s),s.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g,function(match,index,title){return index>0&&index+match.length!==title.length&&match.search(smallWords)>-1&&":"!==title.charAt(index-2)&&("-"!==title.charAt(index+match.length)||"-"===title.charAt(index-1))&&title.charAt(index-1).search(/[^\s-]/)<0?match.toLowerCase():match.substr(1).search(/[A-Z]|\../)>-1?match:match.charAt(0).toUpperCase()+match.substr(1)})}function trim(s){return s.replace(/^\s+|\s+$/g,"")}function mightBeEmail(s){return/[^@]+@[^@]+/.test(s)}function warn(msg){console.warn("[analytics] "+msg)}function _gaEvent(options){if("function"==typeof ga){var fieldObject={hitType:"event",eventCategory:_category,eventAction:options.action};options.label&&(fieldObject.eventLabel=options.label),(options.value||0===options.value)&&(fieldObject.eventValue=options.value),options.nonInteraction===!0&&(fieldObject.nonInteraction=1),ga("send",fieldObject)}var eventArgs=["_trackEvent",_category,options.action];options.label&&(eventArgs[3]=options.label),(options.value||0===options.value)&&(eventArgs[4]=options.value),options.nonInteraction===!0&&(eventArgs[5]=!0),_gaq.push(eventArgs)}function event(action,options){options=options||{};var eventOptions={},label=options.label,value=options.value,nonInteraction=options.noninteraction||options.nonInteraction;return action?(mightBeEmail(action)&&(warn("`action` arg looks like an email address, redacting."),action=_redacted),eventOptions.action=toTitleCase(action),label&&("string"!=typeof label?warn("Expected `label` arg to be a String."):(mightBeEmail(label)&&(warn("`label` arg looks like an email address, redacting."),label=_redacted),eventOptions.label=trim(label))),(value||0===value)&&("number"!=typeof value?warn("Expected `value` arg to be a Number."):eventOptions.value=0|value),nonInteraction&&("boolean"!=typeof nonInteraction?warn("Expected `noninteraction` arg to be a Boolean."):eventOptions.nonInteraction=nonInteraction===!0),void _gaEvent(eventOptions)):void warn("Expected `action` arg.")}function prefixVirtualPageview(s){return/^\/virtual\//.test(s)?s:(s=s.replace(/^[/]?/,"/"),"/virtual"+s)}function _gaVirtualPageView(options){if("function"==typeof ga){var fieldObject={hitType:"pageview",page:options.virtualPagePath};ga("send",fieldObject)}var eventArgs=["_trackPageview",options.virtualPagePath];_gaq.push(eventArgs)}function virtualPageview(virtualPagePath){if(!virtualPagePath)return void warn("Expected `virtualPagePath` arg.");virtualPagePath=trim(virtualPagePath);var eventOptions={};eventOptions.virtualPagePath=prefixVirtualPageview(virtualPagePath),_gaVirtualPageView(eventOptions)}function _optimizely(options){var eventArgs=["trackEvent",options.action];if(options.revenue){var args={revenue:options.revenue};eventArgs[2]=args}optimizely.push(eventArgs)}function conversionGoal(action,options){options=options||{};var eventOptions={},valueInCents=options.valueInCents;return action?(eventOptions.action=trim(action),valueInCents&&("number"==typeof valueInCents&&valueInCents%1===0?eventOptions.revenue=valueInCents:warn("Expected `valueInCents` arg to be an integer.")),void _optimizely(eventOptions)):void warn("Expected `action` arg.")}this._gaq||(this._gaq=[]),this.optimizely||(this.optimizely=[]);var _category=location.hostname,_redacted="REDACTED (Potential Email Address)";return{event:event,virtualPageview:virtualPageview,conversionGoal:conversionGoal}})},{}],5:[function(require,module,exports){var ngModule=angular.module("ngWebmakerLogin",["templates-ngWebmakerLogin"]);ngModule.factory("loginOptions",["$rootScope",function($rootScope){return window.angularConfig?{csrfToken:window.angularConfig.csrf,paths:window.angularConfig.loginPaths}:window.eventsConfig?{csrfToken:window.eventsConfig.csrf,paths:window.eventsConfig.loginPaths}:$rootScope.WMP.config?{csrfToken:$rootScope.WMP.config.csrf,paths:$rootScope.WMP.config.loginPaths}:(console.warn("Could not locate a config on window.angularConfig, window.eventsConfig or $rootScope.WMP.config"),{})}]),ngModule.factory("focus",["$timeout",function($timeout){return function(selector){$timeout(function(){var el=angular.element(selector);el&&el[0]&&el[0].focus()},0)}}]),ngModule.directive("bindTrustedHtml",["$compile",function($compile){return function(scope,element,attrs){scope.$watch(function(scope){return scope.$eval(attrs.bindTrustedHtml)},function(value){element.html(value),$compile(element.contents())(scope)})}}]),ngModule.factory("wmLoginCore",["$rootScope","$location","$timeout","loginOptions",function($rootScope,$location,$timeout,loginOptions){function scrubSearch(){$location.search("uid",null),$location.search("token",null),$location.search("validFor",null)}var LoginCore=require("../core"),core=new LoginCore(loginOptions),searchObj=$location.search();return $rootScope._user={},searchObj.uid&&searchObj.token&&(core.on("signedIn",function(user){$timeout(function(){scrubSearch(),$rootScope._user=user},0)}),core.on("signinFailed",function(uid){$timeout(function(){console.error("login failed for uid: "+uid),scrubSearch(),$rootScope.expiredLoginLink=!0,$rootScope.signin(uid)},0)}),core.instantLogin(searchObj.uid,searchObj.token,searchObj.validFor)),core.on("verified",function(user){$timeout(function(){$rootScope._user=user?user:{},$rootScope.$broadcast("verified",user)},0)}),core.verify(),core}]),ngModule.directive("wmJoinWebmaker",[function(){return{restrict:"A",scope:{showCTA:"=showcta"},link:function($scope,$element){$element.on("click",function(){$scope.joinWebmaker()})},controller:["$rootScope","$scope","$modal","$timeout","focus","wmLoginCore",function($rootScope,$scope,$modal,$timeout,focus,wmLoginCore){function joinModalController($scope,$modalInstance,email,username,showCTA,agreeToTerms){var MODALSTATE={inputEmail:0,inputUsername:1,welcome:2};$scope.MODALSTATE=MODALSTATE,$scope.currentState=MODALSTATE.inputEmail,$scope.form={},$scope.user={},$scope.sendingRequest=!1;var joinController=wmLoginCore.joinWebmaker(showCTA);email&&($scope.user.email=email),username&&($scope.user.username=username),$scope.user.agree=agreeToTerms,joinController.on("sendingRequest",function(state){$timeout(function(){$scope.sendingRequest=state},0)}),joinController.on("displayEmailInput",function(){$timeout(function(){$scope.currentState=MODALSTATE.inputEmail,focus('input[focus-on="create-user-email"]'),void 0!==$scope.user.email&&joinController.validateEmail($scope.user.email)&&void 0!==$scope.user.agree&&(joinController.submitEmail($scope.user.agree),$scope.user.agree&&($scope.skippedEmail=!0,joinController.validateUsername(username)))},0)}),joinController.on("displayUsernameInput",function(){$timeout(function(){$scope.currentState=MODALSTATE.inputUsername,focus('input[focus-on="create-user-username"]')},0)}),joinController.on("displayWelcome",function(user,showCTA){$timeout(function(){$rootScope._user=user,showCTA?$scope.welcomeModalIdx=0:$scope.simpleCTA=!0,$scope.currentState=MODALSTATE.welcome},0)}),joinController.on("displayAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!1)},0)}),joinController.on("hideAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!0)},0)}),$scope.validateEmail=function(){$scope.user.email&&joinController.validateEmail($scope.user.email)},$scope.submitEmail=function(){joinController.submitEmail($scope.user.agree)},$scope.agreeToTermsChanged=function(){joinController.agreeToTermsChanged($scope.user.agree)},$scope.validateUsername=function(){joinController.validateUsername($scope.user.username)},$scope.submitUser=function(){joinController.submitUser($scope.user)},$scope.close=function(){$modalInstance.close()},$scope.switchToSignin=function(){$modalInstance.close(),$rootScope.signin($scope.user.email)},joinController.start()}$scope.joinWebmaker=$rootScope.joinWebmaker=function(email,username,agreeToTerms){$modal.open({templateUrl:"join-webmaker-modal.html",controller:["$scope","$modalInstance","email","username","showCTA","agreeToTerms",joinModalController],resolve:{email:function(){return email},username:function(){return username},showCTA:function(){return!!$scope.showCTA},agreeToTerms:function(){return agreeToTerms}}})}}]}}]),ngModule.directive("wmSignin",[function(){return{restrict:"A",scope:{disablePersona:"=disablepersona"},link:function($scope,$element){$element.on("click",function(){$scope.signin()})},controller:["$rootScope","$scope","$modal","$timeout","$location","focus","wmLoginCore",function($rootScope,$scope,$modal,$timeout,$location,focus,wmLoginCore){function signinModalController($scope,$modalInstance,uid,passwordWasReset,disablePersona){var MODALSTATE={enterUid:0,checkEmail:1,enterKey:2,enterPassword:3,resetRequestSent:4,enterEmail:5};$scope.MODALSTATE=MODALSTATE,$scope.currentState=MODALSTATE.enterUid,$scope.enterEmail=enterEmail,$scope.passwordWasReset=passwordWasReset,$scope.sendingRequest=!1,$scope.disablePersona=disablePersona,$scope.form={},$scope.user={},uid&&($scope.user.uid=uid);var signinController=wmLoginCore.signIn();signinController.on("sendingRequest",function(state){$timeout(function(){$scope.sendingRequest=state},0)}),signinController.on("displayEnterUid",function(){$timeout(function(){$scope.currentState=MODALSTATE.enterUid,focus('input[focus-on="login-uid"]')},0)}),signinController.on("displayEnterEmail",function(){$timeout(function(){$scope.currentState=MODALSTATE.enterEmail,focus('input[focus-on="login-uid2"]')},0)}),signinController.on("displayEnterPassword",function(){$timeout(function(){$scope.currentState=MODALSTATE.enterPassword,focus('input[focus-on="enter-password"]')},0)}),signinController.on("displayEnterKey",function(verified){$timeout(function(){$scope.verified=verified,$scope.currentState=MODALSTATE.enterKey,focus('input[focus-on="enter-key"]')},0)}),signinController.on("displayCheckEmail",function(){$timeout(function(){$scope.currentState=MODALSTATE.checkEmail},0)}),signinController.on("displayResetSent",function(){$timeout(function(){$scope.currentState=MODALSTATE.resetRequestSent},0)}),signinController.on("displayAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!1)},0)}),signinController.on("hideAlert",function(alertId){$timeout(function(){$scope.form.user.$setValidity(alertId,!0)},0)}),signinController.on("signedIn",function(user){$rootScope._user=user,$modalInstance.close(),$rootScope.$broadcast("login",user)}),$scope.submitUid=function(){signinController.submitUid($scope.user.uid,$location.path())},$scope.enterKey=function(){signinController.displayEnterKey()},$scope.enterEmail=function(){signinController.displayEnterEmail()},$scope.submitKey=function(){signinController.verifyKey($scope.user.uid,$scope.user.key,$scope.user.rememberMe)},$scope.submitPassword=function(){signinController.verifyPassword($scope.user.uid,$scope.user.password,$scope.user.rememberMe)},$scope.requestReset=function(){signinController.requestReset($scope.user.uid)},$scope.close=function(){$scope.user={},$modalInstance.close()},$scope.switchToSignup=function(){var uid=$scope.user.uid,type=($scope.user.id,signinController.getUidType(uid)),email="email"===type?uid:"",username="username"===type?uid:"";$modalInstance.close(),$rootScope.joinWebmaker(email,username)},$scope.usePersona=function(){$rootScope.personaLogin(),$timeout($modalInstance.dismiss,0)},signinController.start()}$scope.signin=$rootScope.signin=function(uid,passwordWasReset){$modal.open({templateUrl:"signin-modal.html",controller:["$scope","$modalInstance","uid","passwordWasReset",signinModalController],resolve:{uid:function(){return uid},passwordWasReset:function(){return passwordWasReset},disablePersona:function(){return $scope.disablePersona}},backdrop:"static",keyboard:!1})}}]}}]),ngModule.directive("wmPasswordReset",[function(){var triggered=!1;return{restrict:"A",controller:["$rootScope","$scope","$location","$timeout","$modal","wmLoginCore",function($rootScope,$scope,$location,$timeout,$modal,wmLoginCore){function passwordResetModalController($scope,$modalInstance,resetCode,uid){function clearSearch(){$location.search("uid",null),$location.search("resetCode",null),$modalInstance.close()}$scope.form={},$scope.password={},$scope.sendingRequest=!1,$scope.eightChars=angular.element("li.eight-chars"),$scope.oneEachCase=angular.element("li.one-each-case"),$scope.oneNumber=angular.element("li.one-number");var resetController=wmLoginCore.resetPassword();resetController.on("sendingRequest",function(state){$timeout(function(){$scope.sendingRequest=state},0)}),resetController.on("displayAlert",function(alertId){$timeout(function(){$scope.form.password.$setValidity(alertId,!1)},0)}),resetController.on("hideAlert",function(alertId){$timeout(function(){$scope.form.password.$setValidity(alertId,!0)},0)}),resetController.on("checkConfirmPassword",function(status){$timeout(function(){$scope.passwordsMatch=status},0)}),resetController.on("passwordCheckResult",function(result,blur){$timeout(function(){return result?($scope.eightCharsState=result.lengthValid?blur?"valid":"":"invalid",$scope.oneEachCaseState=result.caseValid?blur?"valid":"":"invalid",$scope.oneNumberState=result.digitValid?blur?"valid":"":"invalid",void($scope.isValidPassword=result.lengthValid&&result.caseValid&&result.digitValid)):($scope.eightCharsState=$scope.oneEachCaseState=$scope.oneNumberState="default",void($scope.isValidPassword=!1))},0)}),resetController.on("resetSucceeded",function(){$timeout(function(){clearSearch(),$rootScope.signin(uid,!0)},0)}),$scope.checkPasswordStrength=function(blur){resetController.checkPasswordStrength($scope.password.value,blur)},$scope.checkPasswordsMatch=function(blur){$scope.password.confirmValue&&resetController.passwordsMatch($scope.password.value,$scope.password.confirmValue,blur)},$scope.submitResetRequest=function(){var uid=$scope.user.uid;resetController.submitResetRequest(uid,resetCode,$scope.password.value)},$scope.close=function(){clearSearch(),$modalInstance.close()}}var searchObj=$location.search();searchObj.resetCode&&searchObj.uid&&!triggered&&(triggered=!0,$modal.open({templateUrl:"reset-modal.html",controller:["$scope","$modalInstance","resetCode","uid",passwordResetModalController],resolve:{resetCode:function(){return searchObj.resetCode},uid:function(){return searchObj.uid}}}))}]}}]),ngModule.factory("wmPersona",["$rootScope","wmLoginCore",function($rootScope,wmLoginCore){var personaController=wmLoginCore.personaLogin();$rootScope.personaLogin=function(){personaController.authenticate()},personaController.on("signedIn",function(user){$rootScope._user=user}),personaController.on("newUser",function(email){$rootScope.joinWebmaker(email)})}]),ngModule.directive("wmPersonaLogin",["wmPersona",function(){return{restrict:"A",link:function($scope,$element){$element.on("click",function(){$scope.personaLogin()})}}}]),ngModule.directive("wmLogout",["$timeout","wmLoginCore",function($timeout){return{restrict:"A",link:function($rootScope,$element){$element.on("click",function(){$rootScope.logout()})},controller:["$rootScope","wmLoginCore",function($rootScope,wmLoginCore){var logoutController=wmLoginCore.logout();logoutController.on("loggedOut",function(){$timeout(function(){$rootScope._user={},$rootScope.$broadcast("logout")},0)}),$rootScope.logout=function(){logoutController.logout()}}]}}])},{"../core":6}],6:[function(require,module,exports){var state=require("./state"),LoginAPI=require("./loginAPI"),Emitter=require("./state/emitter");module.exports=function(options){function verify(){loginAPI.verify(function(err,resp,body){if(err)return emitter.emit("error",err);try{body=JSON.parse(body)}catch(ex){return emitter.emit("error","could not parse json from verify route")}emitter.emit("verified",body.user)})}var loginAPI=new LoginAPI(options),emitter=new Emitter;return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},joinWebmaker:function(showCTA){return new state.JoinController(loginAPI,!!showCTA)},signIn:function(){return new state.SignInController(loginAPI)},resetPassword:function(){return new state.ResetController(loginAPI)},personaLogin:function(){return new state.PersonaController(loginAPI)},logout:function(){return new state.LogoutController(loginAPI)},instantLogin:function(uid,password,validFor){loginAPI.verifyKey(uid,password,validFor,function(err,resp,body){return err||200!==resp.status||!body.user?emitter.emit("signinFailed",uid):void emitter.emit("signedIn",body.user)})},verify:verify}}},{"./loginAPI":7,"./state":11,"./state/emitter":10}],7:[function(require,module,exports){var request=require("browser-request");module.exports=function(options){function doRequest(uri,payload,callback){request({method:"post",uri:uri,timeout:timeout,withCredentials:withCredentials,headers:headers,json:payload},callback)}function uidExists(uid,callback){doRequest(loginUrls.uidExists,{uid:uid},callback)}function checkUsername(username,callback){doRequest(loginUrls.checkUsername,{username:username},callback)}function createUser(user,callback){user.referrer=refferals.refValue(),doRequest(loginUrls.createUser,{ +user:user,audience:audience},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function sendLoginKey(uid,path,callback){doRequest(loginUrls.request,{uid:uid,path:path},callback)}function verifyKey(uid,key,validFor,callback){doRequest(loginUrls.authenticateToken,{uid:uid,token:key,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function verifyPassword(uid,password,validFor,callback){doRequest(loginUrls.verifyPassword,{uid:uid,password:password,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function requestReset(uid,callback){doRequest(loginUrls.requestResetCode,{uid:uid},callback)}function requestEmail(uid,callback){doRequest(loginUrls.requestResetCode,{uid:uid},callback)}function resetPassword(uid,resetCode,password,callback){doRequest(loginUrls.resetPassword,{uid:uid,resetCode:resetCode,newPassword:password},callback)}function personaLogin(assertion,callback){doRequest(loginUrls.authenticate,{assertion:assertion,audience:audience,user:{referrer:refferals.refValue()}},callback)}function logout(callback){doRequest(loginUrls.logout,null,callback)}function verify(callback){doRequest(loginUrls.verify,null,callback)}options=options||{},options.paths=options.paths||{};var refferals=require("./referrals.js")(),loginUrls=require("./loginUrls.js")(options),withCredentials=options.withCredentials!==!1,timeout=1e3*(options.timeout||10),headers={"X-CSRF-Token":options.csrfToken},audience=options.audience||window.location.protocol+"//"+window.location.host;return{uidExists:uidExists,checkUsername:checkUsername,createUser:createUser,sendLoginKey:sendLoginKey,verifyKey:verifyKey,verifyPassword:verifyPassword,requestReset:requestReset,requestEmail:requestEmail,resetPassword:resetPassword,personaLogin:personaLogin,logout:logout,verify:verify}}},{"./loginUrls.js":8,"./referrals.js":9,"browser-request":1}],8:[function(require,module,exports){module.exports=function(options){var paths={},host=options.host||"";return paths=options.paths||{},paths.authenticate=options.paths.authenticate||"/authenticate",paths.legacyCreate=options.paths.legacyCreate||"/create",paths.verify=options.paths.verify||"/verify",paths.logout=options.paths.logout||"/logout",paths.checkUsername=options.paths.checkUsername||"/check-username",paths.request=options.paths.request||"/auth/v2/request",paths.uidExists=options.paths.uidExists||"/auth/v2/uid-exists",paths.createUser=options.paths.createUser||"/auth/v2/create",paths.authenticateToken=options.paths.authenticateToken||"/auth/v2/authenticateToken",paths.verifyPassword=options.paths.verifyPassword||"/auth/v2/verify-password",paths.requestResetCode=options.paths.requestResetCode||"/auth/v2/request-reset-code",paths.removePassword=options.paths.removePassword||"/auth/v2/remove-password",paths.enablePasswords=options.paths.enablePasswords||"/auth/v2/enable-passwords",paths.resetPassword=options.paths.resetPassword||"/auth/v2/reset-password",{request:host+paths.request,authenticateToken:host+paths.authenticateToken,authenticate:host+paths.authenticate,legacyCreate:host+paths.legacyCreate,createUser:host+paths.createUser,verify:host+paths.verify,logout:host+paths.logout,uidExists:host+paths.uidExists,checkUsername:host+paths.checkUsername,verifyPassword:host+paths.verifyPassword,requestResetCode:host+paths.requestResetCode,removePassword:host+paths.removePassword,enablePasswords:host+paths.enablePasswords,resetPassword:host+paths.resetPassword}}},{}],9:[function(require,module,exports){var cookiejs=require("cookie-js");module.exports=function(){var referralCookieSettings={domain:location.hostname.split(".").slice(-2).join("."),path:"/",secure:"https:"===location.protocol,expires:new Date(Date.now()+6048e5)},refValue=/ref=((?:\w|-)+)/.exec(window.location.search),cookieRefValue=cookiejs.parse(document.cookie).webmakerReferral;return refValue&&(refValue=refValue[1],cookieRefValue!==refValue&&(document.cookie=cookiejs.serialize("webmakerReferral",refValue,referralCookieSettings),cookieRefValue=refValue)),{clearReferrerCookie:function(){referralCookieSettings.expires=new Date(Date.now()-1e4),document.cookie=cookiejs.serialize("webmakerReferral","expire",referralCookieSettings),referralCookieSettings.expires=new Date(Date.now()+6048e5)},refValue:function(){return cookieRefValue}}}},{"cookie-js":2}],10:[function(require,module,exports){var EventEmitter=require("events").EventEmitter;module.exports=function(){var emitter=new EventEmitter;return{on:function(event,listener){emitter.addListener(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):void emitter.removeAllListeners(event)},emit:function(){emitter.emit.apply(emitter,arguments)}}}},{events:3}],11:[function(require,module,exports){module.exports={JoinController:require("./join.js"),SignInController:require("./signin.js"),ResetController:require("./reset.js"),PersonaController:require("./persona.js"),LogoutController:require("./logout.js")}},{"./join.js":12,"./logout.js":13,"./persona.js":14,"./reset.js":15,"./signin.js":16}],12:[function(require,module,exports){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi,showCTA){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(JOIN_EVENTS.sendingRequest,state,!state)}function displayAlert(alertId,forceUpdate){emit(JOIN_EVENTS.displayAlert,alertId,forceUpdate)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alert){emit(JOIN_EVENTS.hideAlert,alert)})}function validateEmailCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.accountExists,!0):void 0}function usernameExistsCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.usernameTaken,!0):void emit(JOIN_EVENTS.displayUsernameInput)}var emitter=new Emitter,JOIN_ALERTS={agreeToTerms:"agreeToTerms",accountExists:"accountExists",invalidEmail:"invalidEmail",invalidUsername:"invalidUsername",usernameTaken:"usernameTaken",serverError:"serverError"},JOIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayUsernameInput:"displayUsernameInput",displayEmailInput:"displayEmailInput",displayWelcome:"displayWelcome"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):emitter.off(event)},start:function(){emit(JOIN_EVENTS.displayEmailInput)},validateEmail:function(email){clearAlerts([JOIN_ALERTS.invalidEmail,JOIN_ALERTS.accountExists,JOIN_ALERTS.serverError]);var valid=validation.isEmail(email);return valid?(setRequestState(!0),loginApi.uidExists(email,validateEmailCallback),!0):(displayAlert(JOIN_ALERTS.invalidEmail),!1)},submitEmail:function(agreeToTerms){return agreeToTerms?void emit(JOIN_EVENTS.displayUsernameInput):displayAlert(JOIN_ALERTS.agreeToTerms)},agreeToTermsChanged:function(agree){agree&&emit(JOIN_EVENTS.hideAlert,JOIN_ALERTS.agreeToTerms)},validateUsername:function(username){if(clearAlerts([JOIN_ALERTS.invalidUsername,JOIN_ALERTS.usernameTaken,JOIN_ALERTS.serverError]),username){var valid=validation.isUsername(username);if(!valid)return displayAlert(JOIN_ALERTS.invalidUsername);setRequestState(!0),loginApi.uidExists(username,usernameExistsCallback)}},submitUser:function(formData){clearAlerts([JOIN_ALERTS.agreeToTerms,JOIN_ALERTS.serverError]);var lang="en-US",html=document.querySelector("html");html.lang&&(lang=html.lang),setRequestState(!0),loginApi.createUser({email:formData.email,username:formData.username,mailingList:formData.subscribeToList,prefLocale:lang},function(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError):(analytics.event("Webmaker New User Created",{nonInteraction:!0}),analytics.conversionGoal("WebmakerNewUserCreated"),void emit(JOIN_EVENTS.displayWelcome,body.user,showCTA))})}}}},{"../validation":17,"./emitter.js":10,"webmaker-analytics":4}],13:[function(require,module,exports){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginAPI){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter;return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},logout:function(){loginAPI.logout(function(err,resp,body){return err||200!==resp.status?emit("logoutFailed"):(analytics.event("Webmaker Logout Clicked"),void emit("loggedOut"))})}}}},{"./emitter.js":10,"webmaker-analytics":4}],14:[function(require,module,exports){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter,PERSONA_EVENTS={signedIn:"signedIn",newUser:"newUser"},analyticsLabel={label:"persona"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},authenticate:function(){return window.navigator.id?(analytics.event("Persona Login Clicked"),void window.navigator.id.get(function(assertion){return assertion?void loginApi.personaLogin(assertion,function(err,resp,body){return err||200!==resp.status?void analytics.event("Webmaker Login Failed",analyticsLabel):(analytics.event("Webmaker Login Succeeded",analyticsLabel),void(body.user?emit(PERSONA_EVENTS.signedIn,body.user):body.email&&(analytics.event("Webmaker New User Started",analyticsLabel),emit(PERSONA_EVENTS.newUser,body.email))))}):void analytics.event("Webmaker Login Cancelled",analyticsLabel)})):console.error("No persona found. Did you load include.js?")}}}},{"./emitter.js":10,"webmaker-analytics":4}],15:[function(require,module,exports){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(RESET_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(RESET_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(RESET_EVENTS.hideAlert,alertId)}var emitter=new Emitter,RESET_ALERTS={passwordsMustMatch:"passwordsMustMatch",weakPassword:"weakPassword",serverError:"serverError"},RESET_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",resetSucceeded:"resetSucceeded",passwordCheckResult:"passwordCheckResult",checkConfirmPassword:"checkConfirmPassword"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},passwordsMatch:function(password,confimValue,blur){validation.passwordsMatch(password,confimValue)?(hideAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!0)):(blur&&displayAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!1))},checkPasswordStrength:function(password,blur){emit(RESET_EVENTS.passwordCheckResult,validation.checkPasswordStrength(password),blur)},submitResetRequest:function(uid,resetCode,password){hideAlert(RESET_ALERTS.serverError),hideAlert(RESET_ALERTS.weakPassword),setRequestState(!0),loginApi.resetPassword(uid,resetCode,password,function(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(400===resp.status?RESET_ALERTS.weakPassword:RESET_ALERTS.serverError):(analytics.event("Webmaker Password Reset Succeeded"),void(window.location="/"))})}}}},{"../validation":17,"./emitter.js":10,"webmaker-analytics":4}],16:[function(require,module,exports){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(SIGNIN_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(SIGNIN_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(SIGNIN_EVENTS.hideAlert,alertId)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alertId){hideAlert(alertId)})}var emitter=new Emitter,SIGNIN_ALERTS={paswordReset:"paswordReset",noAccount:"noAccount",invalidUid:"invalidUid",serverError:"serverError",invalidKey:"invalidKey",passwordSigninFailed:"passwordSigninFailed",resetRequestFailed:"resetRequestFailed"},SIGNIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayEnterUid:"displayEnterUid",displayEnterPassword:"displayEnterPassword",displayEnterKey:"displayEnterKey",displayCheckEmail:"displayCheckEmail",displayResetSent:"displayResetSent",signedIn:"signedIn",displayEnterEmail:"displayEnterEmail"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},start:function(){emit(SIGNIN_EVENTS.displayEnterUid)},submitUid:function(uid,path){clearAlerts([SIGNIN_ALERTS.invalidUid,SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.noAccount]);var valid=validation.isEmail(uid)||validation.isUsername(uid);return valid?(setRequestState(!0),void loginApi.uidExists(uid,function(err,resp,body){if(setRequestState(!1),err||200!==resp.status)return displayAlert(SIGNIN_ALERTS.serverError);var isVerified=body.verified;return body.exists?body.usePasswordLogin?!1:void loginApi.sendLoginKey(uid,path,function(err,resp,body){return err?displayAlert(SIGNIN_ALERTS.serverError):void(isVerified?emit(SIGNIN_EVENTS.displayEnterKey,!1):emit(SIGNIN_EVENTS.displayCheckEmail))}):displayAlert(SIGNIN_ALERTS.noAccount)})):displayAlert(SIGNIN_ALERTS.invalidUid)},displayEnterKey:function(){emit(SIGNIN_EVENTS.displayEnterKey,!0)},verifyKey:function(uid,key,rememberMe){clearAlerts([SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.invalidKey]),setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyKey(uid,key,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"key"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.invalidKey)})},verifyPassword:function(uid,password,rememberMe){setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyPassword(uid,password,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"password"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.passwordSigninFailed)})},requestEmail:function(uid){setRequestState(!1),emit(SIGNIN_EVENTS.displayEnterEmail)},requestReset:function(uid){setRequestState(!0),loginApi.requestReset(uid,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):(hideAlert(SIGNIN_ALERTS.serverError),body.status?(hideAlert(SIGNIN_ALERTS.resetRequestFailed),analytics.event("Webmaker Password Reset Requested"),void emit(SIGNIN_EVENTS.displayResetSent)):displayAlert(SIGNIN_ALERTS.resetRequestFailed))})},getUidType:function(uid){return validation.isEmail(uid)?"email":validation.isUsername(uid)?"username":null}}}},{"../validation":17,"./emitter.js":10,"webmaker-analytics":4}],17:[function(require,module,exports){var usernameRegex=/^[a-zA-Z0-9\-]{1,20}$/,emailRegex=/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,containsBothCases=/^.*(?=.*[a-z])(?=.*[A-Z]).*$/,containsDigit=/\d/,MIN_PASSWORD_LEN=8;module.exports={isEmail:function(email){return emailRegex.test(email)},isUsername:function(username){return usernameRegex.test(username)},passwordsMatch:function(password,confirmation){return password===confirmation},checkPasswordStrength:function(password){if(!password)return!1;var lengthValid=password.length>=MIN_PASSWORD_LEN,caseValid=!!password.match(containsBothCases),digitValid=!!password.match(containsDigit);return{lengthValid:lengthValid,caseValid:caseValid,digitValid:digitValid}}}},{}]},{},[5]); \ No newline at end of file diff --git a/dist/min/ngWebmakerLogin.templates.min.js b/dist/min/ngWebmakerLogin.templates.min.js index d703f0f..43b9425 100644 --- a/dist/min/ngWebmakerLogin.templates.min.js +++ b/dist/min/ngWebmakerLogin.templates.min.js @@ -1 +1,2 @@ -angular.module("templates-ngWebmakerLogin",["join-webmaker-modal.html","modal-wrapper.html","reset-modal.html","signin-modal.html"]),angular.module("join-webmaker-modal.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("join-webmaker-modal.html",'\n\n')}]),angular.module("modal-wrapper.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("modal-wrapper.html",'\n\n')}]),angular.module("reset-modal.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("reset-modal.html",'\n\n')}]),angular.module("signin-modal.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("signin-modal.html",'\n\n')}]); \ No newline at end of file +angular.module("templates-ngWebmakerLogin",["join-webmaker-modal.html","modal-wrapper.html","reset-modal.html","signin-modal.html"]),angular.module("join-webmaker-modal.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("join-webmaker-modal.html",'\n\n')}]),angular.module("modal-wrapper.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("modal-wrapper.html",'\n\n')}]),angular.module("reset-modal.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("reset-modal.html",'\n\n')}]),angular.module("signin-modal.html",[]).run(["$templateCache",function($templateCache){$templateCache.put("signin-modal.html",'\n\n'); +}]); \ No newline at end of file diff --git a/dist/min/webmakerLogin.min.js b/dist/min/webmakerLogin.min.js index cb054b4..2b8b676 100644 --- a/dist/min/webmakerLogin.min.js +++ b/dist/min/webmakerLogin.min.js @@ -1,7 +1,7 @@ -!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;oget help.',description:"Error message displayed if an error occurs on the server."},webmakerAuthCreateWelcome:{message:"Create a Webmaker account",description:"Header text for the join webmaker modal dialog"},webmakerAuthChooseUsername:{message:"Choose A Username",description:"Label text for the username selection input"},webmakerAuthTakenError:{message:' That username is taken. Try adding your favourite number at the end.',description:"Error message displayed when the entered username is not available for use."},webmakerAuthUsernameInvalid:{message:' Uh oh! All usernames must be between 1-20 characters, and only include "-" and alphanumeric symbols',description:"Error message displayed when the username entered contains symbols that are not allowed."},webmakerAuthMailingList:{message:"Send me email updates about Webmaker and other Mozilla projects",description:"Message about opting in for a Mozilla mailing list"},webmakerAuthAgreeToTerms:{message:"I agree to Mozilla Webmaker's Terms and Privacy Policy",description:"I agree to Mozilla Webmaker's terms and privacy policy."},webmakerAuthAgreeError:{message:' Oh snap! You must agree to our terms and conditions.',description:"Error message displayed if the terms and conditions checkbox isn't toggled on."},webmakerAuthCreateAccount:{message:"Create Account",description:"The button text for finishing the join Webmaker process."},Cancel:{message:"Cancel",description:"Cancel button text"},Email:{message:"Enter Your Email",description:"Label text for the email input"},EmailOrUsername:{message:"Email or Username",description:"Label text for the sign in input, asks for the username or email of the user's account."},NotAnEmail:{message:' Uh Oh! That doesn\'t look like an email address.',description:"Error message when the text entered in an email input is not an email address"},WebmakerAccountExists:{message:' Heads up! That email already has an account. Did you mean to sign in?',description:"That email already has an accout. Did you mean to sign in?"},ChooseUsername:{message:"Choose Username",description:" Label text for selecting a username"},"Language Preference":{message:"Language Preference",description:"Label text for selecting the preferred language for the user."},"Sign in to Webmaker":{message:"Sign In To Webmaker",description:"Header text for the sign in modal dialog"},"Sign in":{message:"Sign In",description:"Sign in Button text"},"Sign up":{message:"Join",description:"Join button text"},passLoginFailed:{message:' Authentication failed!',description:"Error message when a password login attempt fails"},resetMessage:{message:"Check your email for a password reset link.",description:"Directs the user to check their email for a password reset link"},resetRequestFailed:{message:' Uh oh! Something went wrong! Try requesting the password reset again. Or, get help.',description:"Error displayed if a password reset request fails."},Password:{message:"Password",description:"Label text for the password input"},"Forgot your password?":{message:"Forgot your password?",description:"button text for the password reset function"},checkEmail:{message:"Check Your Email",description:"Message instructing the user to check their email"},tokenMessage:{message:"Please check your email to confirm your account.",description:"Message instructing the user to check their email for an account confirmation link"},"That does not look like an email address or username":{message:' Uh oh! That doesn\'t look like an email address or username.',description:"Error message displayed when the input doesn't match a username or email"},"No account found for your uid":{message:' We couldn\'t find your username or email address. Did you mean to create an account? Trouble? Get help.',description:"Error message displayed when the given username or email doesn't have a Webmaker account and asks if they would like to sign up."},"problem sending token":{message:' There was a problem sending a login key to you, please try again. Get help.',description:"Error message displayed when the request for a login key fails for some reason."},incorrectToken:{message:' Uh oh! That key is not correct.',description:"Error message displayed when the token used to log in is rejected."},"Visit Email":{message:"Visit your email to retrieve your key",description:"Label text above the login key input field"},"Verified Visit Email":{message:"We emailed you a link & key to sign in",description:"Message instructing the user to check their email for an account confirmation link"},"Enter key":{message:'Enter key ',description:"Label to enter key that was sent to user's email"},"you can switch to webmaker login":{message:"You can switch back to our Webmaker Login experience. We will send you login emails so you do not need a password.",description:"Message reminding users that they can switch back to the Webmaker Login Key system instead of using a password."},Submit:{message:"Submit",description:"Label text for the submit new password button in the Reset Password Modal Dialog"},or:{message:"or",description:"Text beside the button that initiates a persona login"},"log in with Persona":{message:"log in with Persona",description:"Text for the button that initiates a persona login"},"trouble with email":{message:'Trouble with email? Check your spam or get help',description:"Text that allows users to get help"},aboutWebmaker:{message:"Make your own web pages, interactive videos, remixes and mobile apps.",description:"Short description of Webmaker"},"XRay-Goggles":{message:"X-Ray Goggles",description:"The X-Ray Goggles Tool"},AboutGoggles:{message:"X-Ray Goggles allow you to see and change the building blocks that make up websites on the Internet. Activate the goggles to play with the code behind any webpage.",description:"A short description of the X-Ray Goggles"},TryGoggles:{message:"Try Goggles now",description:"Text for the button that takes the user to the X-Ray Goggles homepage"},ExploreWebmaker:{message:"Explore the rest of Webmaker",description:"Text for the button which takes the user to webmaker.org/explore"},Resources:{message:"Resources",description:"The Resources section of Webmaker"},AboutResources:{message:"Teach and learn digital skills and web literacy. Webmaker Resources are full of fun things to discover, make and teach.",description:"A short description about the Resources section"},VisitResources:{message:"Visit Resources",description:"Text for the button that takes the user to the X-Ray Goggles homepage"},"passwords do not match":{message:' Uh oh! The passwords do not match!',description:"Error message displayed when the password input and password confirmation input do not match"},"error setting password":{message:' Uh oh! There was an error trying to set your password, please try again.',description:"Error displayed if there was a problem setting the new password"},"Confirm your password":{message:"Confirm Your Password",description:"Label text for the password confirmation input"},"Reset Password":{message:"Reset Password",description:"Reset Password Modal title"},"Set a Password":{message:"Set A Password",description:"Label text for the password input box (reset password modal)"},"Password Reset Success":{message:' Success! You\'ve successfully reset your password, please sign in!',description:"Alert displayed after successfully resetting a password"},"Password too weak":{message:" Uh oh! The password you've entered is too weak. Make sure it doesn't contain any common words or patterns, and doesn't contain your email or username",description:"Error message displayed if the server determined the password entered is too weak."},"Minimum password requirements":{message:"Minimum password requirements",description:"Text above the list of minimum requirements that a password must satisfy"},"At least 8 characters":{message:"At least 8 characters",description:"A password must contain 8 or more characters"},"At least 1 upper and lower case character":{message:"At least 1 uppercase and lowercase character",description:"A password must contain at least 1 upper and lower case character"},"At least 1 number":{message:"At least 1 number",description:"a password must contain at least one number character"},resetRequestFailed:{message:' Uh oh! There was a problem processing your request, please try again.',description:"Error message displayed if the reset request fails for some reason"},Next:{message:"Next",description:"Go to the next screen"},Cancel:{message:"Cancel",description:"Cancel sign up or sign in"},Done:{message:"Done",description:"Done, close the window."},"Remember me for one year":{message:"Remember me",description:"Message displayed next to the remember me checkbox"},"Lets Go!":{message:"Let's Go!",description:"Button text for closing the modal dialog after account creation"},"Expired Login Link":{message:"Uh Oh! Your login link expired. Request a new email to sign in.",description:"Error message displayed if a login link is expired"}}},{}],2:[function(require,module,exports){"use strict";function compile(src){var cached;if("string"!=typeof src)throw new TypeError("src must be a string, instead saw '"+typeof src+"'");return compile.cache?(cached=compile.cache[src],cached||(cached=compile.cache[src]=parser.parse(src)),cached):parser.parse(src)}function getFilter(name){return filters[name]}var parse=require("./parse.js"),filters={},Lexer=parse.Lexer,Parser=parse.Parser,lexer=new Lexer({}),parser=new Parser(lexer,getFilter);compile.cache={},exports.Lexer=Lexer,exports.Parser=Parser,exports.compile=compile,exports.filters=filters},{"./parse.js":3}],3:[function(require,module,exports){"use strict";function noop(){}function extend(dst,obj){var key;for(key in obj)obj.hasOwnProperty(key)&&(dst[key]=obj[key]);return dst}function isDefined(value){return"undefined"!=typeof value}function valueFn(value){return function(){return value}}function $parseMinErr(module,message){var args=arguments;throw message=message.replace(/{(\d)}/g,function(match){return args[2+parseInt(match[1])]}),new SyntaxError(message)}function lowercase(string){return"string"==typeof string?string.toLowerCase():string}function forEach(arr,iterator){arr.forEach(iterator)}function ensureSafeMemberName(name,fullExpression){if("constructor"===name)throw $parseMinErr("isecfld",'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',fullExpression);return name}function ensureSafeObject(obj,fullExpression){if(obj){if(obj.constructor===obj)throw $parseMinErr("isecfn","Referencing Function in Angular expressions is disallowed! Expression: {0}",fullExpression);if(obj.document&&obj.location&&obj.alert&&obj.setInterval)throw $parseMinErr("isecwindow","Referencing the Window in Angular expressions is disallowed! Expression: {0}",fullExpression);if(obj.children&&(obj.nodeName||obj.prop&&obj.attr&&obj.find))throw $parseMinErr("isecdom","Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}",fullExpression)}return obj}function setter(obj,path,setValue,fullExp){for(var key,element=path.split("."),i=0;element.length>1;i++){key=ensureSafeMemberName(element.shift(),fullExp);var propertyObj=obj[key];propertyObj||(propertyObj={},obj[key]=propertyObj),obj=propertyObj}return key=ensureSafeMemberName(element.shift(),fullExp),obj[key]=setValue,setValue}function cspSafeGetterFn(key0,key1,key2,key3,key4,fullExp){return ensureSafeMemberName(key0,fullExp),ensureSafeMemberName(key1,fullExp),ensureSafeMemberName(key2,fullExp),ensureSafeMemberName(key3,fullExp),ensureSafeMemberName(key4,fullExp),function(scope,locals){var pathVal=locals&&locals.hasOwnProperty(key0)?locals:scope;return null==pathVal?pathVal:(pathVal=pathVal[key0],key1?null==pathVal?void 0:(pathVal=pathVal[key1],key2?null==pathVal?void 0:(pathVal=pathVal[key2],key3?null==pathVal?void 0:(pathVal=pathVal[key3],key4?null==pathVal?void 0:pathVal=pathVal[key4]:pathVal):pathVal):pathVal):pathVal)}}function simpleGetterFn1(key0,fullExp){return ensureSafeMemberName(key0,fullExp),function(scope,locals){return null==scope?void 0:(locals&&locals.hasOwnProperty(key0)?locals:scope)[key0]}}function simpleGetterFn2(key0,key1,fullExp){return ensureSafeMemberName(key0,fullExp),ensureSafeMemberName(key1,fullExp),function(scope,locals){return null==scope?void 0:(scope=(locals&&locals.hasOwnProperty(key0)?locals:scope)[key0],null==scope?void 0:scope[key1])}}function getterFn(path,options,fullExp){if(getterFnCache.hasOwnProperty(path))return getterFnCache[path];var fn,pathKeys=path.split("."),pathKeysLength=pathKeys.length;if(1===pathKeysLength)fn=simpleGetterFn1(pathKeys[0],fullExp);else if(2===pathKeysLength)fn=simpleGetterFn2(pathKeys[0],pathKeys[1],fullExp);else if(options.csp)fn=6>pathKeysLength?cspSafeGetterFn(pathKeys[0],pathKeys[1],pathKeys[2],pathKeys[3],pathKeys[4],fullExp,options):function(scope,locals){var val,i=0;do val=cspSafeGetterFn(pathKeys[i++],pathKeys[i++],pathKeys[i++],pathKeys[i++],pathKeys[i++],fullExp,options)(scope,locals),locals=void 0,scope=val;while(pathKeysLength>i);return val};else{var code="var p;\n";forEach(pathKeys,function(key,index){ensureSafeMemberName(key,fullExp),code+="if(s == null) return undefined;\ns="+(index?"s":'((k&&k.hasOwnProperty("'+key+'"))?k:s)')+'["'+key+'"];\n'}),code+="return s;";var evaledFnGetter=new Function("s","k","pw",code);evaledFnGetter.toString=valueFn(code),fn=evaledFnGetter}return"hasOwnProperty"!==path&&(getterFnCache[path]=fn),fn}var OPERATORS={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:noop,"+":function(self,locals,a,b){return a=a(self,locals),b=b(self,locals),isDefined(a)?isDefined(b)?a+b:a:isDefined(b)?b:void 0},"-":function(self,locals,a,b){return a=a(self,locals),b=b(self,locals),(isDefined(a)?a:0)-(isDefined(b)?b:0)},"*":function(self,locals,a,b){return a(self,locals)*b(self,locals)},"/":function(self,locals,a,b){return a(self,locals)/b(self,locals)},"%":function(self,locals,a,b){return a(self,locals)%b(self,locals)},"^":function(self,locals,a,b){return a(self,locals)^b(self,locals)},"=":noop,"===":function(self,locals,a,b){return a(self,locals)===b(self,locals)},"!==":function(self,locals,a,b){return a(self,locals)!==b(self,locals)},"==":function(self,locals,a,b){return a(self,locals)==b(self,locals)},"!=":function(self,locals,a,b){return a(self,locals)!=b(self,locals)},"<":function(self,locals,a,b){return a(self,locals)":function(self,locals,a,b){return a(self,locals)>b(self,locals)},"<=":function(self,locals,a,b){return a(self,locals)<=b(self,locals)},">=":function(self,locals,a,b){return a(self,locals)>=b(self,locals)},"&&":function(self,locals,a,b){return a(self,locals)&&b(self,locals)},"||":function(self,locals,a,b){return a(self,locals)||b(self,locals)},"&":function(self,locals,a,b){return a(self,locals)&b(self,locals)},"|":function(self,locals,a,b){return b(self,locals)(self,locals,a(self,locals))},"!":function(self,locals,a){return!a(self,locals)}},ESCAPE={n:"\n",f:"\f",r:"\r",t:" ",v:" ","'":"'",'"':'"'},Lexer=function(options){this.options=options};Lexer.prototype={constructor:Lexer,lex:function(text){this.text=text,this.index=0,this.ch=void 0,this.lastCh=":",this.tokens=[];for(var token,json=[];this.index="0"&&"9">=ch},isWhitespace:function(ch){return" "===ch||"\r"===ch||" "===ch||"\n"===ch||" "===ch||" "===ch},isIdent:function(ch){return ch>="a"&&"z">=ch||ch>="A"&&"Z">=ch||"_"===ch||"$"===ch},isExpOperator:function(ch){return"-"===ch||"+"===ch||this.isNumber(ch)},throwError:function(error,start,end){end=end||this.index;var colStr=isDefined(start)?"s "+start+"-"+this.index+" ["+this.text.substring(start,end)+"]":" "+end;throw $parseMinErr("lexerr","Lexer Error: {0} at column{1} in expression [{2}].",error,colStr,this.text)},readNumber:function(){for(var number="",start=this.index;this.index0){var token=this.tokens[0],t=token.text;if(t===e1||t===e2||t===e3||t===e4||!e1&&!e2&&!e3&&!e4)return token}return!1},expect:function(e1,e2,e3,e4){var token=this.peek(e1,e2,e3,e4);return token?(this.tokens.shift(),token):!1},consume:function(e1){this.expect(e1)||this.throwError("is unexpected, expecting ["+e1+"]",this.peek())},unaryFn:function(fn,right){return extend(function(self,locals){return fn(self,locals,right)},{constant:right.constant})},ternaryFn:function(left,middle,right){return extend(function(self,locals){return left(self,locals)?middle(self,locals):right(self,locals)},{constant:left.constant&&middle.constant&&right.constant})},binaryFn:function(left,fn,right){return extend(function(self,locals){return fn(self,locals,left,right)},{constant:left.constant&&right.constant})},statements:function(){for(var statements=[];;)if(this.tokens.length>0&&!this.peek("}",")",";","]")&&statements.push(this.filterChain()),!this.expect(";"))return 1===statements.length?statements[0]:function(self,locals){for(var value,i=0;i","<=",">="))&&(left=this.binaryFn(left,token.fn,this.relational())),left},additive:function(){for(var token,left=this.multiplicative();token=this.expect("+","-");)left=this.binaryFn(left,token.fn,this.multiplicative());return left},multiplicative:function(){for(var token,left=this.unary();token=this.expect("*","/","%");)left=this.binaryFn(left,token.fn,this.unary());return left},unary:function(){var token;return this.expect("+")?this.primary():(token=this.expect("-"))?this.binaryFn(Parser.ZERO,token.fn,this.unary()):(token=this.expect("!"))?this.unaryFn(token.fn,this.unary()):this.primary()},fieldAccess:function(object){var parser=this,field=this.expect().text,getter=getterFn(field,this.options,this.text);return extend(function(scope,locals,self){return getter(self||object(scope,locals))},{assign:function(scope,value,locals){return setter(object(scope,locals),field,value,parser.text,parser.options)}})},objectIndex:function(obj){var parser=this,indexFn=this.expression();return this.consume("]"),extend(function(self,locals){var v,o=obj(self,locals),i=indexFn(self,locals);return o?v=ensureSafeObject(o[i],parser.text):void 0},{assign:function(self,value,locals){var key=indexFn(self,locals),safe=ensureSafeObject(obj(self,locals),parser.text);return safe[key]=value}})},functionCall:function(fn,contextGetter){var argsFn=[];if(")"!==this.peekToken().text)do argsFn.push(this.expression());while(this.expect(","));this.consume(")");var parser=this;return function(scope,locals){for(var args=[],context=contextGetter?contextGetter(scope,locals):scope,i=0;i>18&63,h2=bits>>12&63,h3=bits>>6&63,h4=63&bits,tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4);while(i299)&&body.error){er=new Error("CouchDB error: "+(body.error.reason||body.error.error));for(var key in body)er[key]=body[key];return callback(er,resp,body)}return callback(er,resp,body)}"string"==typeof options&&(options={uri:options}),options.json=!0,options.body&&(options.json=options.body),delete options.body,callback=callback||noop;var xhr=request(options,couch_handler);return xhr},module.exports=request},{}],5:[function(require,module){!function(){var cookiejs={serialize:function(name,val,opt){opt=opt||{};var enc=opt.encode||encode,pairs=[name+"="+enc(val)];if(null!=opt.maxAge){var maxAge=opt.maxAge-0;if(isNaN(maxAge))throw new Error("maxAge should be a Number");pairs.push("Max-Age="+maxAge)}return opt.domain&&pairs.push("Domain="+opt.domain),opt.path&&pairs.push("Path="+opt.path),opt.expires&&pairs.push("Expires="+opt.expires.toUTCString()),opt.httpOnly&&pairs.push("HttpOnly"),opt.secure&&pairs.push("Secure"),pairs.join("; ")},parse:function(str,opt){opt=opt||{};var obj={},pairs=str.split(/; */),dec=opt.decode||decode;return pairs.forEach(function(pair){var eq_idx=pair.indexOf("=");if(!(0>eq_idx)){var key=pair.substr(0,eq_idx).trim(),val=pair.substr(++eq_idx,pair.length).trim();if('"'==val[0]&&(val=val.slice(1,-1)),void 0==obj[key])try{obj[key]=dec(val)}catch(e){obj[key]=val}}}),obj}},encode=encodeURIComponent,decode=decodeURIComponent;"undefined"!=typeof module&&module.exports?module.exports=cookiejs:"function"==typeof define&&define.amd?define(function(){return cookiejs}):window.cookiejs=cookiejs}()},{}],6:[function(require,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified "error" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],7:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],8:[function(require,module){function noop(){}var process=module.exports={};process.nextTick=function(){var canSetImmediate="undefined"!=typeof window&&window.setImmediate,canPost="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(canSetImmediate)return function(f){return window.setImmediate(f)};if(canPost){var queue=[];return window.addEventListener("message",function(ev){var source=ev.source;if((source===window||null===source)&&"process-tick"===ev.data&&(ev.stopPropagation(),queue.length>0)){var fn=queue.shift();fn()}},!0),function(fn){queue.push(fn),window.postMessage("process-tick","*")}}return function(fn){setTimeout(fn,0)}}(),process.title="browser",process.browser=!0,process.env={},process.argv=[],process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.binding=function(){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(){throw new Error("process.chdir is not supported")}},{}],9:[function(require,module,exports){(function(global){!function(root){function error(type){throw RangeError(errors[type])}function map(array,fn){for(var length=array.length;length--;)array[length]=fn(array[length]);return array}function mapDomain(string,fn){return map(string.split(regexSeparators),fn).join(".")}function ucs2decode(string){for(var value,extra,output=[],counter=0,length=string.length;length>counter;)value=string.charCodeAt(counter++),value>=55296&&56319>=value&&length>counter?(extra=string.charCodeAt(counter++),56320==(64512&extra)?output.push(((1023&value)<<10)+(1023&extra)+65536):(output.push(value),counter--)):output.push(value);return output}function ucs2encode(array){return map(array,function(value){var output="";return value>65535&&(value-=65536,output+=stringFromCharCode(value>>>10&1023|55296),value=56320|1023&value),output+=stringFromCharCode(value)}).join("")}function basicToDigit(codePoint){return 10>codePoint-48?codePoint-22:26>codePoint-65?codePoint-65:26>codePoint-97?codePoint-97:base}function digitToBasic(digit,flag){return digit+22+75*(26>digit)-((0!=flag)<<5)}function adapt(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);delta>baseMinusTMin*tMax>>1;k+=base)delta=floor(delta/baseMinusTMin);return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var out,basic,j,index,oldi,w,k,digit,t,baseMinusT,output=[],inputLength=input.length,i=0,n=initialN,bias=initialBias;for(basic=input.lastIndexOf(delimiter),0>basic&&(basic=0),j=0;basic>j;++j)input.charCodeAt(j)>=128&&error("not-basic"),output.push(input.charCodeAt(j));for(index=basic>0?basic+1:0;inputLength>index;){for(oldi=i,w=1,k=base;index>=inputLength&&error("invalid-input"),digit=basicToDigit(input.charCodeAt(index++)),(digit>=base||digit>floor((maxInt-i)/w))&&error("overflow"),i+=digit*w,t=bias>=k?tMin:k>=bias+tMax?tMax:k-bias,!(t>digit);k+=base)baseMinusT=base-t,w>floor(maxInt/baseMinusT)&&error("overflow"),w*=baseMinusT;out=output.length+1,bias=adapt(i-oldi,out,0==oldi),floor(i/out)>maxInt-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,inputLength,handledCPCountPlusOne,baseMinusT,qMinusT,output=[];for(input=ucs2decode(input),inputLength=input.length,n=initialN,delta=0,bias=initialBias,j=0;inputLength>j;++j)currentValue=input[j],128>currentValue&&output.push(stringFromCharCode(currentValue));for(handledCPCount=basicLength=output.length,basicLength&&output.push(delimiter);inputLength>handledCPCount;){for(m=maxInt,j=0;inputLength>j;++j)currentValue=input[j],currentValue>=n&&m>currentValue&&(m=currentValue);for(handledCPCountPlusOne=handledCPCount+1,m-n>floor((maxInt-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m,j=0;inputLength>j;++j)if(currentValue=input[j],n>currentValue&&++delta>maxInt&&error("overflow"),currentValue==n){for(q=delta,k=base;t=bias>=k?tMin:k>=bias+tMax?tMax:k-bias,!(t>q);k+=base)qMinusT=q-t,baseMinusT=base-t,output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0))),q=floor(qMinusT/baseMinusT);output.push(stringFromCharCode(digitToBasic(q,0))),bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength),delta=0,++handledCPCount}++delta,++n}return output.join("")}function toUnicode(domain){return mapDomain(domain,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}function toASCII(domain){return mapDomain(domain,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})}var freeExports="object"==typeof exports&&exports,freeModule="object"==typeof module&&module&&module.exports==freeExports&&module,freeGlobal="object"==typeof global&&global;(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)&&(root=freeGlobal);var punycode,key,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^ -~]/,regexSeparators=/\x2E|\u3002|\uFF0E|\uFF61/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;if(punycode={version:"1.2.4",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return punycode});else if(freeExports&&!freeExports.nodeType)if(freeModule)freeModule.exports=punycode;else for(key in punycode)punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);else root.punycode=punycode}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],10:[function(require,module){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;maxKeys>0&&len>maxKeys&&(len=maxKeys);for(var i=0;len>i;++i){var kstr,vstr,k,v,x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq);idx>=0?(kstr=x.substr(0,idx),vstr=x.substr(idx+1)):(kstr=x,vstr=""),k=decodeURIComponent(kstr),v=decodeURIComponent(vstr),hasOwnProperty(obj,k)?isArray(obj[k])?obj[k].push(v):obj[k]=[obj[k],v]:obj[k]=v}return obj};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)}},{}],11:[function(require,module){"use strict";function map(xs,f){if(xs.map)return xs.map(f);for(var res=[],i=0;i",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var rest=url;rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);!slashes||proto&&hostlessProtocol[proto]||(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0;ihec)&&(hostEnd=hec)}var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0;ihec)&&(hostEnd=hec)}-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length;l>i;i++){var part=hostparts[i];if(part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;k>j;j++)newpart+=part.charCodeAt(j)>127?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}}if(this.hostname=this.hostname.length>hostnameMaxLen?"":this.hostname.toLowerCase(),!ipv6Hostname){for(var domainArray=this.hostname.split("."),newOut=[],i=0;ii;i++){var ae=autoEscape[i],esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1!==qm?(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)):parseQueryString&&(this.search="",this.query={}),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&host!==!1?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):host||(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}var result=new Url;if(Object.keys(this).forEach(function(k){result[k]=this[k]},this),result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol)return Object.keys(relative).forEach(function(k){"protocol"!==k&&(result[k]=relative[k])}),slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result;if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol])return Object.keys(relative).forEach(function(k){result[k]=relative[k]}),result.href=result.format(),result;if(result.protocol=relative.protocol,relative.host||hostlessProtocol[relative.protocol])result.pathname=relative.pathname;else{for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),relPath.length<2&&relPath.unshift(""),result.pathname=relPath.join("/")}if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):!1;authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,isNull(result.pathname)&&isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.path=result.search?"/"+result.search:null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;i>=0;i--)last=srcPath[i],"."==last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");!mustEndAbs||""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0)||srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):!1;authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),isNull(result.pathname)&&isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{punycode:9,querystring:12}],14:[function(require,module){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],15:[function(require,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str){return str}function arrayToHash(array){var hash={};return array.forEach(function(val){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date"); -if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;l>i;++i)output.push(hasOwnProperty(value,String(i))?formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0):"");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),str.indexOf("\n")>-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];len>i;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(process.noDeprecation===!0)return fn;var warned=!1;return deprecated};var debugEnviron,debugs={};exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":14,_process:8,inherits:7}],16:[function(require,module){!function(){var modules={};!function(){function extend(cls,name,props){var F=function(){};F.prototype=cls.prototype;var prototype=new F,fnTest=/xyz/.test(function(){xyz})?/\bparent\b/:/.*/;props=props||{};for(var k in props){var src=props[k],parent=prototype[k];prototype[k]="function"==typeof parent&&"function"==typeof src&&fnTest.test(src)?function(src,parent){return function(){var tmp=this.parent;this.parent=parent;var res=src.apply(this,arguments);return this.parent=tmp,res}}(src,parent):src}prototype.typename=name;var new_cls=function(){prototype.init&&prototype.init.apply(this,arguments)};return new_cls.prototype=prototype,new_cls.prototype.constructor=new_cls,new_cls.extend=function(name,props){return"object"==typeof name&&(props=name,name="anonymous"),extend(new_cls,name,props)},new_cls}modules.object=extend(Object,"Object",{})}(),function(){var ArrayProto=Array.prototype,ObjProto=Object.prototype,escapeMap={"&":"&",'"':""","'":"'","<":"<",">":">"},escapeRegex=/[&"'<>]/g,lookupEscape=function(ch){return escapeMap[ch]},exports=modules.lib={};exports.withPrettyErrors=function(path,withInternals,func){try{return func()}catch(e){if(e.Update||(e=new exports.TemplateError(e)),e.Update(path),!withInternals){var old=e;e=new Error(old.message),e.name=old.name}throw e}},exports.TemplateError=function(message,lineno,colno){var err=this;return message instanceof Error?(err=message,message=message.name+": "+message.message):Error.captureStackTrace&&Error.captureStackTrace(err),err.name="Template render error",err.message=message,err.lineno=lineno,err.colno=colno,err.firstUpdate=!0,err.Update=function(path){var message="("+(path||"unknown path")+")";return this.firstUpdate&&(this.lineno&&this.colno?message+=" [Line "+this.lineno+", Column "+this.colno+"]":this.lineno&&(message+=" [Line "+this.lineno+"]")),message+="\n ",this.firstUpdate&&(message+=" "),this.message=message+(this.message||""),this.firstUpdate=!1,this},err},exports.TemplateError.prototype=Error.prototype,exports.escape=function(val){return val.replace(escapeRegex,lookupEscape)},exports.isFunction=function(obj){return"[object Function]"==ObjProto.toString.call(obj)},exports.isArray=Array.isArray||function(obj){return"[object Array]"==ObjProto.toString.call(obj)},exports.isString=function(obj){return"[object String]"==ObjProto.toString.call(obj)},exports.isObject=function(obj){return"[object Object]"==ObjProto.toString.call(obj)},exports.groupBy=function(obj,val){for(var result={},iterator=exports.isFunction(val)?val:function(obj){return obj[val]},i=0;ii;i++)str+=char_;return str},exports.each=function(obj,func,context){if(null!=obj)if(ArrayProto.each&&obj.each==ArrayProto.each)obj.forEach(func,context);else if(obj.length===+obj.length)for(var i=0,l=obj.length;l>i;i++)func.call(context,obj[i],i,obj)},exports.map=function(obj,func){var results=[];if(null==obj)return results;if(ArrayProto.map&&obj.map===ArrayProto.map)return obj.map(func);for(var i=0;ii?iter(k,obj[k],i,len,next):cb()}var keys=exports.keys(obj),len=keys.length,i=-1;next()},Array.prototype.indexOf||(Array.prototype.indexOf=function(array,searchElement){if(null==array)throw new TypeError;var t=Object(array),len=t.length>>>0;if(0===len)return-1;var n=0;if(arguments.length>2&&(n=Number(arguments[2]),n!=n?n=0:0!=n&&1/0!=n&&n!=-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=len)return-1;for(var k=n>=0?n:Math.max(len-Math.abs(n),0);len>k;k++)if(k in t&&t[k]===searchElement)return k;return-1}),Array.prototype.map||(Array.prototype.map=function(){throw new Error("map is unimplemented for this js engine")}),exports.keys=function(obj){if(Object.prototype.keys)return obj.keys();var keys=[];for(var k in obj)obj.hasOwnProperty(k)&&keys.push(k);return keys}}(),function(){function traverseAndCheck(obj,type,results){obj instanceof type&&results.push(obj),obj instanceof Node&&obj.findAll(type,results)}function printNodes(node,indent){function print(str,indent,inline){for(var lines=str.split("\n"),i=0;i0||!inline))for(var j=0;indent>j;j++)util.print(" ");i===lines.length-1?util.print(lines[i]):util.puts(lines[i])}}if(indent=indent||0,print(node.typename+": ",indent),node instanceof NodeList)print("\n"),lib.each(node.children,function(n){printNodes(n,indent+2)});else if(node instanceof CallExtension)print(node.extName+"."+node.prop),print("\n"),node.args&&printNodes(node.args,indent+2),node.contentArgs&&lib.each(node.contentArgs,function(n){printNodes(n,indent+2)});else{var nodes=null,props=null;if(node.iterFields(function(val,field){val instanceof Node?(nodes=nodes||{},nodes[field]=val):(props=props||{},props[field]=val)}),props?print(util.inspect(props,!0,null)+"\n",null,!0):print("\n"),nodes)for(var k in nodes)printNodes(nodes[k],indent+2)}}var util=modules.util,lib=modules.lib,Object=modules.object,Node=Object.extend("Node",{init:function(lineno,colno){this.lineno=lineno,this.colno=colno;for(var fields=this.fields,i=0,l=fields.length;l>i;i++){var field=fields[i],val=arguments[i+2];void 0===val&&(val=null),this[field]=val}},findAll:function(type,results){if(results=results||[],this instanceof NodeList)for(var children=this.children,i=0,l=children.length;l>i;i++)traverseAndCheck(children[i],type,results);else for(var fields=this.fields,i=0,l=fields.length;l>i;i++)traverseAndCheck(this[fields[i]],type,results);return results},iterFields:function(func){lib.each(this.fields,function(field){func(this[field],field)},this)}}),Value=Node.extend("Value",{fields:["value"]}),NodeList=Node.extend("NodeList",{fields:["children"],init:function(lineno,colno,nodes){this.parent(lineno,colno,nodes||[])},addChild:function(node){this.children.push(node)}}),Root=NodeList.extend("Root"),Literal=Value.extend("Literal"),Symbol=Value.extend("Symbol"),Group=NodeList.extend("Group"),Array=NodeList.extend("Array"),Pair=Node.extend("Pair",{fields:["key","value"]}),Dict=NodeList.extend("Dict"),LookupVal=Node.extend("LookupVal",{fields:["target","val"]}),If=Node.extend("If",{fields:["cond","body","else_"]}),IfAsync=If.extend("IfAsync"),InlineIf=Node.extend("InlineIf",{fields:["cond","body","else_"]}),For=Node.extend("For",{fields:["arr","name","body"]}),AsyncEach=For.extend("AsyncEach"),AsyncAll=For.extend("AsyncAll"),Macro=Node.extend("Macro",{fields:["name","args","body"]}),Import=Node.extend("Import",{fields:["template","target"]}),FromImport=Node.extend("FromImport",{fields:["template","names"],init:function(lineno,colno,template,names){this.parent(lineno,colno,template,names||new NodeList)}}),FunCall=Node.extend("FunCall",{fields:["name","args"]}),Filter=FunCall.extend("Filter"),FilterAsync=Filter.extend("FilterAsync",{fields:["name","args","symbol"]}),KeywordArgs=Dict.extend("KeywordArgs"),Block=Node.extend("Block",{fields:["name","body"]}),Super=Node.extend("Super",{fields:["blockName","symbol"]}),TemplateRef=Node.extend("TemplateRef",{fields:["template"]}),Extends=TemplateRef.extend("Extends"),Include=TemplateRef.extend("Include"),Set=Node.extend("Set",{fields:["targets","value"]}),Output=NodeList.extend("Output"),TemplateData=Literal.extend("TemplateData"),UnaryOp=Node.extend("UnaryOp",{fields:["target"]}),BinOp=Node.extend("BinOp",{fields:["left","right"]}),Or=BinOp.extend("Or"),And=BinOp.extend("And"),Not=UnaryOp.extend("Not"),Add=BinOp.extend("Add"),Sub=BinOp.extend("Sub"),Mul=BinOp.extend("Mul"),Div=BinOp.extend("Div"),FloorDiv=BinOp.extend("FloorDiv"),Mod=BinOp.extend("Mod"),Pow=BinOp.extend("Pow"),Neg=UnaryOp.extend("Neg"),Pos=UnaryOp.extend("Pos"),Compare=Node.extend("Compare",{fields:["expr","ops"]}),CompareOperand=Node.extend("CompareOperand",{fields:["expr","type"]}),CallExtension=(Node.extend("CustomTag",{init:function(lineno,colno,name){this.lineno=lineno,this.colno=colno,this.name=name}}),Node.extend("CallExtension",{fields:["extName","prop","args","contentArgs"],init:function(ext,prop,args,contentArgs){this.extName=ext._name||ext,this.prop=prop,this.args=args||new NodeList,this.contentArgs=contentArgs||[],this.autoescape=ext.autoescape}})),CallExtensionAsync=CallExtension.extend("CallExtensionAsync");modules.nodes={Node:Node,Root:Root,NodeList:NodeList,Value:Value,Literal:Literal,Symbol:Symbol,Group:Group,Array:Array,Pair:Pair,Dict:Dict,Output:Output,TemplateData:TemplateData,If:If,IfAsync:IfAsync,InlineIf:InlineIf,For:For,AsyncEach:AsyncEach,AsyncAll:AsyncAll,Macro:Macro,Import:Import,FromImport:FromImport,FunCall:FunCall,Filter:Filter,FilterAsync:FilterAsync,KeywordArgs:KeywordArgs,Block:Block,Super:Super,Extends:Extends,Include:Include,Set:Set,LookupVal:LookupVal,BinOp:BinOp,Or:Or,And:And,Not:Not,Add:Add,Sub:Sub,Mul:Mul,Div:Div,FloorDiv:FloorDiv,Mod:Mod,Pow:Pow,Neg:Neg,Pos:Pos,Compare:Compare,CompareOperand:CompareOperand,CallExtension:CallExtension,CallExtensionAsync:CallExtensionAsync,printNodes:printNodes}}(),function(){function makeMacro(argNames,kwargNames,func){return function(){var args,argCount=numArgs(arguments),kwargs=getKeywordArgs(arguments);if(argCount>argNames.length){args=Array.prototype.slice.call(arguments,0,argNames.length);for(var vals=Array.prototype.slice.call(arguments,args.length,argCount),i=0;i=","//","**"],curComplex=cur+this.current();switch(-1!==complexOps.indexOf(curComplex)&&(this.forward(),cur=curComplex),cur){case"(":type=TOKEN_LEFT_PAREN;break;case")":type=TOKEN_RIGHT_PAREN;break;case"[":type=TOKEN_LEFT_BRACKET;break;case"]":type=TOKEN_RIGHT_BRACKET;break;case"{":type=TOKEN_LEFT_CURLY;break;case"}":type=TOKEN_RIGHT_CURLY;break;case",":type=TOKEN_COMMA;break;case":":type=TOKEN_COLON;break;case"|":type=TOKEN_PIPE;break;default:type=TOKEN_OPERATOR}return token(type,cur,lineno,colno)}if(tok=this._extractUntil(whitespaceChars+delimChars),tok.match(/^[-+]?[0-9]+$/)){if("."==this.current()){this.forward();var dec=this._extract(intChars);return token(TOKEN_FLOAT,tok+"."+dec,lineno,colno)}return token(TOKEN_INT,tok,lineno,colno)}if(tok.match(/^(true|false)$/))return token(TOKEN_BOOLEAN,tok,lineno,colno);if(tok)return token(TOKEN_SYMBOL,tok,lineno,colno);throw new Error("Unexpected value while parsing: "+tok)}var tok,beginChars=BLOCK_START.charAt(0)+VARIABLE_START.charAt(0)+COMMENT_START.charAt(0)+COMMENT_END.charAt(0);if(this.is_finished())return null;if((tok=this._extractString(BLOCK_START+"-"))||(tok=this._extractString(BLOCK_START)))return this.in_code=!0,token(TOKEN_BLOCK_START,tok,lineno,colno);if(tok=this._extractString(VARIABLE_START))return this.in_code=!0,token(TOKEN_VARIABLE_START,tok,lineno,colno);tok="";var data,in_comment=!1;for(this._matches(COMMENT_START)&&(in_comment=!0,tok=this._extractString(COMMENT_START));null!==(data=this._extractUntil(beginChars))&&(tok+=data,!(this._matches(BLOCK_START)||this._matches(VARIABLE_START)||this._matches(COMMENT_START))||in_comment);){if(this._matches(COMMENT_END)){if(!in_comment)throw new Error("unexpected end of comment");tok+=this._extractString(COMMENT_END);break}tok+=this.current(),this.forward()}if(null===data&&in_comment)throw new Error("expected end of comment, got end of file");return token(in_comment?TOKEN_COMMENT:TOKEN_DATA,tok,lineno,colno)},Tokenizer.prototype.parseString=function(delimiter){this.forward();for(var str=(this.lineno,this.colno,"");!this.is_finished()&&this.current()!=delimiter;){var cur=this.current();if("\\"==cur){switch(this.forward(),this.current()){case"n":str+="\n";break;case"t":str+=" ";break;case"r":str+="\r";break;default:str+=this.current()}this.forward()}else str+=cur,this.forward()}return this.forward(),str},Tokenizer.prototype._matches=function(str){if(this.index+str.length>this.length)return null;var m=this.str.slice(this.index,this.index+str.length);return m==str},Tokenizer.prototype._extractString=function(str){return this._matches(str)?(this.index+=str.length,str):null},Tokenizer.prototype._extractUntil=function(charString){return this._extractMatching(!0,charString||"")},Tokenizer.prototype._extract=function(charString){return this._extractMatching(!1,charString)},Tokenizer.prototype._extractMatching=function(breakOnMatch,charString){if(this.is_finished())return null;var first=charString.indexOf(this.current());if(breakOnMatch&&-1==first||!breakOnMatch&&-1!=first){var t=this.current();this.forward();for(var idx=charString.indexOf(this.current());(breakOnMatch&&-1==idx||!breakOnMatch&&-1!=idx)&&!this.is_finished();)t+=this.current(),this.forward(),idx=charString.indexOf(this.current());return t}return""},Tokenizer.prototype.is_finished=function(){return this.index>=this.len},Tokenizer.prototype.forwardN=function(n){for(var i=0;n>i;i++)this.forward()},Tokenizer.prototype.forward=function(){this.index++,"\n"==this.previous()?(this.lineno++,this.colno=0):this.colno++},Tokenizer.prototype.back=function(){if(this.index--,"\n"==this.current()){this.lineno--;var idx=this.src.lastIndexOf("\n",this.index-1);this.colno=-1==idx?this.index:this.index-idx}else this.colno--},Tokenizer.prototype.current=function(){return this.is_finished()?"":this.str.charAt(this.index)},Tokenizer.prototype.previous=function(){return this.str.charAt(this.index-1)},modules.lexer={lex:function(src){return new Tokenizer(src)},setTags:function(tags){BLOCK_START=tags.blockStart||BLOCK_START,BLOCK_END=tags.blockEnd||BLOCK_END,VARIABLE_START=tags.variableStart||VARIABLE_START,VARIABLE_END=tags.variableEnd||VARIABLE_END,COMMENT_START=tags.commentStart||COMMENT_START,COMMENT_END=tags.commentEnd||COMMENT_END},TOKEN_STRING:TOKEN_STRING,TOKEN_WHITESPACE:TOKEN_WHITESPACE,TOKEN_DATA:TOKEN_DATA,TOKEN_BLOCK_START:TOKEN_BLOCK_START,TOKEN_BLOCK_END:TOKEN_BLOCK_END,TOKEN_VARIABLE_START:TOKEN_VARIABLE_START,TOKEN_VARIABLE_END:TOKEN_VARIABLE_END,TOKEN_COMMENT:TOKEN_COMMENT,TOKEN_LEFT_PAREN:TOKEN_LEFT_PAREN,TOKEN_RIGHT_PAREN:TOKEN_RIGHT_PAREN,TOKEN_LEFT_BRACKET:TOKEN_LEFT_BRACKET,TOKEN_RIGHT_BRACKET:TOKEN_RIGHT_BRACKET,TOKEN_LEFT_CURLY:TOKEN_LEFT_CURLY,TOKEN_RIGHT_CURLY:TOKEN_RIGHT_CURLY,TOKEN_OPERATOR:TOKEN_OPERATOR,TOKEN_COMMA:TOKEN_COMMA,TOKEN_COLON:TOKEN_COLON,TOKEN_PIPE:TOKEN_PIPE,TOKEN_INT:TOKEN_INT,TOKEN_FLOAT:TOKEN_FLOAT,TOKEN_BOOLEAN:TOKEN_BOOLEAN,TOKEN_SYMBOL:TOKEN_SYMBOL,TOKEN_SPECIAL:TOKEN_SPECIAL}}(),function(){var lexer=modules.lexer,nodes=modules.nodes,Object=modules.object,lib=modules.lib,Parser=Object.extend({init:function(tokens){this.tokens=tokens,this.peeked=null,this.breakOnBlocks=null,this.dropLeadingWhitespace=!1,this.extensions=[]},nextToken:function(withWhitespace){var tok;if(this.peeked){if(withWhitespace||this.peeked.type!=lexer.TOKEN_WHITESPACE)return tok=this.peeked,this.peeked=null,tok;this.peeked=null}if(tok=this.tokens.nextToken(),!withWhitespace)for(;tok&&tok.type==lexer.TOKEN_WHITESPACE;)tok=this.tokens.nextToken();return tok},peekToken:function(){return this.peeked=this.peeked||this.nextToken(),this.peeked},pushToken:function(tok){if(this.peeked)throw new Error("pushToken: can only push one token on between reads");this.peeked=tok},fail:function(msg,lineno,colno){if((void 0===lineno||void 0===colno)&&this.peekToken()){var tok=this.peekToken();lineno=tok.lineno,colno=tok.colno}throw void 0!==lineno&&(lineno+=1),void 0!==colno&&(colno+=1),new lib.TemplateError(msg,lineno,colno)},skip:function(type){var tok=this.nextToken();return tok&&tok.type==type?!0:(this.pushToken(tok),!1)},expect:function(type){var tok=this.nextToken();return tok.type!==type&&this.fail("expected "+type+", got "+tok.type,tok.lineno,tok.colno),tok},skipValue:function(type,val){var tok=this.nextToken();return tok&&tok.type==type&&tok.value==val?!0:(this.pushToken(tok),!1)},skipWhitespace:function(){return this.skip(lexer.TOKEN_WHITESPACE)},skipSymbol:function(val){return this.skipValue(lexer.TOKEN_SYMBOL,val)},advanceAfterBlockEnd:function(name){if(!name){var tok=this.peekToken();tok||this.fail("unexpected end of file"),tok.type!=lexer.TOKEN_SYMBOL&&this.fail("advanceAfterBlockEnd: expected symbol token or explicit name to be passed"),name=this.nextToken().value}var tok=this.nextToken();tok&&tok.type==lexer.TOKEN_BLOCK_END?"-"===tok.value.charAt(0)&&(this.dropLeadingWhitespace=!0):this.fail("expected block end in "+name+" statement")},advanceAfterVariableEnd:function(){this.skip(lexer.TOKEN_VARIABLE_END)||this.fail("expected variable end")},parseFor:function(){var node,endBlock,forTok=this.peekToken();this.skipSymbol("for")?(node=new nodes.For(forTok.lineno,forTok.colno),endBlock="endfor"):this.skipSymbol("asyncEach")?(node=new nodes.AsyncEach(forTok.lineno,forTok.colno),endBlock="endeach"):this.skipSymbol("asyncAll")?(node=new nodes.AsyncAll(forTok.lineno,forTok.colno),endBlock="endall"):this.fail("parseFor: expected for{Async}",forTok.lineno,forTok.colno),node.name=this.parsePrimary(),node.name instanceof nodes.Symbol||this.fail("parseFor: variable name expected for loop");var type=this.peekToken().type;if(type==lexer.TOKEN_COMMA){var key=node.name;for(node.name=new nodes.Array(key.lineno,key.colno),node.name.addChild(key);this.skip(lexer.TOKEN_COMMA);){var prim=this.parsePrimary();node.name.addChild(prim)}}return this.skipSymbol("in")||this.fail('parseFor: expected "in" keyword for loop',forTok.lineno,forTok.colno),node.arr=this.parseExpression(),this.advanceAfterBlockEnd(forTok.value),node.body=this.parseUntilBlocks(endBlock),this.advanceAfterBlockEnd(),node},parseMacro:function(){var macroTok=this.peekToken();this.skipSymbol("macro")||this.fail("expected macro");var name=this.parsePrimary(!0),args=this.parseSignature(),node=new nodes.Macro(macroTok.lineno,macroTok.colno,name,args);return this.advanceAfterBlockEnd(macroTok.value),node.body=this.parseUntilBlocks("endmacro"),this.advanceAfterBlockEnd(),node},parseImport:function(){var importTok=this.peekToken();this.skipSymbol("import")||this.fail("parseImport: expected import",importTok.lineno,importTok.colno);var template=this.parseExpression();this.skipSymbol("as")||this.fail('parseImport: expected "as" keyword',importTok.lineno,importTok.colno);var target=this.parsePrimary(),node=new nodes.Import(importTok.lineno,importTok.colno,template,target); -return this.advanceAfterBlockEnd(importTok.value),node},parseFrom:function(){var fromTok=this.peekToken();this.skipSymbol("from")||this.fail("parseFrom: expected from");var template=this.parsePrimary(),node=new nodes.FromImport(fromTok.lineno,fromTok.colno,template,new nodes.NodeList);this.skipSymbol("import")||this.fail("parseFrom: expected import",fromTok.lineno,fromTok.colno);for(var names=node.names;;){var nextTok=this.peekToken();if(nextTok.type==lexer.TOKEN_BLOCK_END){names.children.length||this.fail("parseFrom: Expected at least one import name",fromTok.lineno,fromTok.colno),"-"==nextTok.value.charAt(0)&&(this.dropLeadingWhitespace=!0),this.nextToken();break}names.children.length>0&&!this.skip(lexer.TOKEN_COMMA)&&this.fail("parseFrom: expected comma",fromTok.lineno,fromTok.colno);var name=this.parsePrimary();if("_"==name.value.charAt(0)&&this.fail("parseFrom: names starting with an underscore cannot be imported",name.lineno,name.colno),this.skipSymbol("as")){var alias=this.parsePrimary();names.addChild(new nodes.Pair(name.lineno,name.colno,name,alias))}else names.addChild(name)}return node},parseBlock:function(){var tag=this.peekToken();this.skipSymbol("block")||this.fail("parseBlock: expected block",tag.lineno,tag.colno);var node=new nodes.Block(tag.lineno,tag.colno);return node.name=this.parsePrimary(),node.name instanceof nodes.Symbol||this.fail("parseBlock: variable name expected",tag.lineno,tag.colno),this.advanceAfterBlockEnd(tag.value),node.body=this.parseUntilBlocks("endblock"),this.peekToken()||this.fail("parseBlock: expected endblock, got end of file"),this.advanceAfterBlockEnd(),node},parseTemplateRef:function(tagName,nodeType){var tag=this.peekToken();this.skipSymbol(tagName)||this.fail("parseTemplateRef: expected "+tagName);var node=new nodeType(tag.lineno,tag.colno);return node.template=this.parseExpression(),this.advanceAfterBlockEnd(tag.value),node},parseExtends:function(){return this.parseTemplateRef("extends",nodes.Extends)},parseInclude:function(){return this.parseTemplateRef("include",nodes.Include)},parseIf:function(){var node,tag=this.peekToken();this.skipSymbol("if")||this.skipSymbol("elif")?node=new nodes.If(tag.lineno,tag.colno):this.skipSymbol("ifAsync")?node=new nodes.IfAsync(tag.lineno,tag.colno):this.fail("parseIf: expected if or elif",tag.lineno,tag.colno),node.cond=this.parseExpression(),this.advanceAfterBlockEnd(tag.value),node.body=this.parseUntilBlocks("elif","else","endif");var tok=this.peekToken();switch(tok&&tok.value){case"elif":node.else_=this.parseIf();break;case"else":this.advanceAfterBlockEnd(),node.else_=this.parseUntilBlocks("endif"),this.advanceAfterBlockEnd();break;case"endif":node.else_=null,this.advanceAfterBlockEnd();break;default:this.fail("parseIf: expected endif, else, or endif, got end of file")}return node},parseSet:function(){var tag=this.peekToken();this.skipSymbol("set")||this.fail("parseSet: expected set",tag.lineno,tag.colno);for(var target,node=new nodes.Set(tag.lineno,tag.colno,[]);(target=this.parsePrimary())&&(node.targets.push(target),this.skip(lexer.TOKEN_COMMA)););return this.skipValue(lexer.TOKEN_OPERATOR,"=")||this.fail("parseSet: expected = in set tag",tag.lineno,tag.colno),node.value=this.parseExpression(),this.advanceAfterBlockEnd(tag.value),node},parseStatement:function(){var node,tok=this.peekToken();if(tok.type!=lexer.TOKEN_SYMBOL&&this.fail("tag name expected",tok.lineno,tok.colno),this.breakOnBlocks&&-1!==this.breakOnBlocks.indexOf(tok.value))return null;switch(tok.value){case"raw":return this.parseRaw();case"if":case"ifAsync":return this.parseIf();case"for":case"asyncEach":case"asyncAll":return this.parseFor();case"block":return this.parseBlock();case"extends":return this.parseExtends();case"include":return this.parseInclude();case"set":return this.parseSet();case"macro":return this.parseMacro();case"import":return this.parseImport();case"from":return this.parseFrom();default:if(this.extensions.length)for(var i=0;i1&&this.fail("invalid index"),node=new nodes.LookupVal(tok.lineno,tok.colno,node,lookup.children[0])}else{if(tok.type!=lexer.TOKEN_OPERATOR||"."!=tok.value)break;this.nextToken();var val=this.nextToken();val.type!=lexer.TOKEN_SYMBOL&&this.fail("expected name as lookup value, got "+val.value,val.lineno,val.colno);var lookup=new nodes.Literal(val.lineno,val.colno,val.value);node=new nodes.LookupVal(tok.lineno,tok.colno,node,lookup)}tok=this.peekToken()}return node},parseExpression:function(){var node=this.parseInlineIf();return node},parseInlineIf:function(){var node=this.parseOr();if(this.skipSymbol("if")){var cond_node=this.parseOr(),body_node=node;node=new nodes.InlineIf(node.lineno,node.colno),node.body=body_node,node.cond=cond_node,node.else_=this.skipSymbol("else")?this.parseOr():null}return node},parseOr:function(){for(var node=this.parseAnd();this.skipSymbol("or");){var node2=this.parseAnd();node=new nodes.Or(node.lineno,node.colno,node,node2)}return node},parseAnd:function(){for(var node=this.parseNot();this.skipSymbol("and");){var node2=this.parseNot();node=new nodes.And(node.lineno,node.colno,node,node2)}return node},parseNot:function(){var tok=this.peekToken();return this.skipSymbol("not")?new nodes.Not(tok.lineno,tok.colno,this.parseNot()):this.parseCompare()},parseCompare:function(){for(var compareOps=["==","!=","<",">","<=",">="],expr=this.parseAdd(),ops=[];;){var tok=this.nextToken();if(!tok)break;if(-1!==compareOps.indexOf(tok.value))ops.push(new nodes.CompareOperand(tok.lineno,tok.colno,this.parseAdd(),tok.value));else if(tok.type==lexer.TOKEN_SYMBOL&&"in"==tok.value)ops.push(new nodes.CompareOperand(tok.lineno,tok.colno,this.parseAdd(),"in"));else{if(tok.type!=lexer.TOKEN_SYMBOL||"not"!=tok.value||!this.skipSymbol("in")){this.pushToken(tok);break}ops.push(new nodes.CompareOperand(tok.lineno,tok.colno,this.parseAdd(),"notin"))}}return ops.length?new nodes.Compare(ops[0].lineno,ops[0].colno,expr,ops):expr},parseAdd:function(){for(var node=this.parseSub();this.skipValue(lexer.TOKEN_OPERATOR,"+");){var node2=this.parseSub();node=new nodes.Add(node.lineno,node.colno,node,node2)}return node},parseSub:function(){for(var node=this.parseMul();this.skipValue(lexer.TOKEN_OPERATOR,"-");){var node2=this.parseMul();node=new nodes.Sub(node.lineno,node.colno,node,node2)}return node},parseMul:function(){for(var node=this.parseDiv();this.skipValue(lexer.TOKEN_OPERATOR,"*");){var node2=this.parseDiv();node=new nodes.Mul(node.lineno,node.colno,node,node2)}return node},parseDiv:function(){for(var node=this.parseFloorDiv();this.skipValue(lexer.TOKEN_OPERATOR,"/");){var node2=this.parseFloorDiv();node=new nodes.Div(node.lineno,node.colno,node,node2)}return node},parseFloorDiv:function(){for(var node=this.parseMod();this.skipValue(lexer.TOKEN_OPERATOR,"//");){var node2=this.parseMod();node=new nodes.FloorDiv(node.lineno,node.colno,node,node2)}return node},parseMod:function(){for(var node=this.parsePow();this.skipValue(lexer.TOKEN_OPERATOR,"%");){var node2=this.parsePow();node=new nodes.Mod(node.lineno,node.colno,node,node2)}return node},parsePow:function(){for(var node=this.parseUnary();this.skipValue(lexer.TOKEN_OPERATOR,"**");){var node2=this.parseUnary();node=new nodes.Pow(node.lineno,node.colno,node,node2)}return node},parseUnary:function(noFilters){var node,tok=this.peekToken();return node=this.skipValue(lexer.TOKEN_OPERATOR,"-")?new nodes.Neg(tok.lineno,tok.colno,this.parseUnary(!0)):this.skipValue(lexer.TOKEN_OPERATOR,"+")?new nodes.Pos(tok.lineno,tok.colno,this.parseUnary(!0)):this.parsePrimary(),noFilters||(node=this.parseFilter(node)),node},parsePrimary:function(noPostfix){var tok=this.nextToken(),val=null,node=null;return tok?tok.type==lexer.TOKEN_STRING?val=tok.value:tok.type==lexer.TOKEN_INT?val=parseInt(tok.value,10):tok.type==lexer.TOKEN_FLOAT?val=parseFloat(tok.value):tok.type==lexer.TOKEN_BOOLEAN&&("true"==tok.value?val=!0:"false"==tok.value?val=!1:this.fail("invalid boolean: "+tok.val,tok.lineno,tok.colno)):this.fail("expected expression, got end of file"),null!==val?node=new nodes.Literal(tok.lineno,tok.colno,val):tok.type==lexer.TOKEN_SYMBOL?(node=new nodes.Symbol(tok.lineno,tok.colno,tok.value),noPostfix||(node=this.parsePostfix(node))):(this.pushToken(tok),node=this.parseAggregate()),node?node:void this.fail("unexpected token: "+tok.value,tok.lineno,tok.colno)},parseFilter:function(node){for(;this.skip(lexer.TOKEN_PIPE);){for(var tok=this.expect(lexer.TOKEN_SYMBOL),name=tok.value;this.skipValue(lexer.TOKEN_OPERATOR,".");)name+="."+this.expect(lexer.TOKEN_SYMBOL).value;if(node=new nodes.Filter(tok.lineno,tok.colno,new nodes.Symbol(tok.lineno,tok.colno,name),new nodes.NodeList(tok.lineno,tok.colno,[node])),this.peekToken().type==lexer.TOKEN_LEFT_PAREN){var call=this.parsePostfix(node);node.args.children=node.args.children.concat(call.args.children)}}return node},parseAggregate:function(){var node,tok=this.nextToken();switch(tok.type){case lexer.TOKEN_LEFT_PAREN:node=new nodes.Group(tok.lineno,tok.colno);break;case lexer.TOKEN_LEFT_BRACKET:node=new nodes.Array(tok.lineno,tok.colno);break;case lexer.TOKEN_LEFT_CURLY:node=new nodes.Dict(tok.lineno,tok.colno);break;default:return null}for(;;){var type=this.peekToken().type;if(type==lexer.TOKEN_RIGHT_PAREN||type==lexer.TOKEN_RIGHT_BRACKET||type==lexer.TOKEN_RIGHT_CURLY){this.nextToken();break}if(node.children.length>0&&(this.skip(lexer.TOKEN_COMMA)||this.fail("parseAggregate: expected comma after expression",tok.lineno,tok.colno)),node instanceof nodes.Dict){var key=this.parsePrimary();this.skip(lexer.TOKEN_COLON)||this.fail("parseAggregate: expected colon after dict key",tok.lineno,tok.colno);var value=this.parseExpression();node.addChild(new nodes.Pair(key.lineno,key.colno,key,value))}else{var expr=this.parseExpression();node.addChild(expr)}}return node},parseSignature:function(tolerant,noParens){var tok=this.peekToken();if(!noParens&&tok.type!=lexer.TOKEN_LEFT_PAREN){if(tolerant)return null;this.fail("expected arguments",tok.lineno,tok.colno)}tok.type==lexer.TOKEN_LEFT_PAREN&&(tok=this.nextToken());for(var args=new nodes.NodeList(tok.lineno,tok.colno),kwargs=new nodes.KeywordArgs(tok.lineno,tok.colno),checkComma=!1;;){if(tok=this.peekToken(),!noParens&&tok.type==lexer.TOKEN_RIGHT_PAREN){this.nextToken();break}if(noParens&&tok.type==lexer.TOKEN_BLOCK_END)break;if(checkComma&&!this.skip(lexer.TOKEN_COMMA))this.fail("parseSignature: expected comma after expression",tok.lineno,tok.colno);else{var arg=this.parseExpression();this.skipValue(lexer.TOKEN_OPERATOR,"=")?kwargs.addChild(new nodes.Pair(arg.lineno,arg.colno,arg,this.parseExpression())):args.addChild(arg)}checkComma=!0}return kwargs.children.length&&args.addChild(kwargs),args},parseUntilBlocks:function(){var prev=this.breakOnBlocks;this.breakOnBlocks=lib.toArray(arguments);var ret=this.parse();return this.breakOnBlocks=prev,ret},parseNodes:function(){for(var tok,buf=[];tok=this.nextToken();)if(tok.type==lexer.TOKEN_DATA){var data=tok.value,nextToken=this.peekToken(),nextVal=nextToken&&nextToken.value;this.dropLeadingWhitespace&&(data=data.replace(/^\s*/,""),this.dropLeadingWhitespace=!1),nextToken&&nextToken.type==lexer.TOKEN_BLOCK_START&&"-"==nextVal.charAt(nextVal.length-1)&&(data=data.replace(/\s*$/,"")),buf.push(new nodes.Output(tok.lineno,tok.colno,[new nodes.TemplateData(tok.lineno,tok.colno,data)]))}else if(tok.type==lexer.TOKEN_BLOCK_START){var n=this.parseStatement();if(!n)break;buf.push(n)}else if(tok.type==lexer.TOKEN_VARIABLE_START){var e=this.parseExpression();this.advanceAfterVariableEnd(),buf.push(new nodes.Output(tok.lineno,tok.colno,[e]))}else tok.type!=lexer.TOKEN_COMMENT&&this.fail("Unexpected token at top-level: "+tok.type,tok.lineno,tok.colno);return buf},parse:function(){return new nodes.NodeList(0,0,this.parseNodes())},parseAsRoot:function(){return new nodes.Root(0,0,this.parseNodes())}});modules.parser={parse:function(src,extensions){var p=new Parser(lexer.lex(src));return void 0!==extensions&&(p.extensions=extensions),p.parseAsRoot()}}}(),function(){function gensym(){return"hole_"+sym++}function mapCOW(arr,func){for(var res=null,i=0;i":">","<=":"<=",">=":">="},Compiler=Object.extend({init:function(){this.codebuf=[],this.lastId=0,this.buffer=null,this.bufferStack=[],this.isChild=!1,this.scopeClosers=""},fail:function(msg,lineno,colno){throw void 0!==lineno&&(lineno+=1),void 0!==colno&&(colno+=1),new lib.TemplateError(msg,lineno,colno)},pushBufferId:function(id){this.bufferStack.push(this.buffer),this.buffer=id,this.emit("var "+this.buffer+' = "";')},popBufferId:function(){this.buffer=this.bufferStack.pop()},emit:function(code){this.codebuf.push(code)},emitLine:function(code){this.emit(code+"\n")},emitLines:function(){lib.each(lib.toArray(arguments),function(line){this.emitLine(line)},this)},emitFuncBegin:function(name){this.buffer="output",this.scopeClosers="",this.emitLine("function "+name+"(env, context, frame, runtime, cb) {"),this.emitLine("var lineno = null;"),this.emitLine("var colno = null;"),this.emitLine("var "+this.buffer+' = "";'),this.emitLine("try {")},emitFuncEnd:function(noReturn){noReturn||this.emitLine("cb(null, "+this.buffer+");"),this.closeScopeLevels(),this.emitLine("} catch (e) {"),this.emitLine(" cb(runtime.handleError(e, lineno, colno));"),this.emitLine("}"),this.emitLine("}"),this.buffer=null},addScopeLevel:function(){this.scopeClosers+="})"},closeScopeLevels:function(){this.emitLine(this.scopeClosers+";"),this.scopeClosers=""},withScopedSyntax:function(func){var scopeClosers=this.scopeClosers;this.scopeClosers="",func.call(this),this.closeScopeLevels(),this.scopeClosers=scopeClosers},makeCallback:function(res){var err=this.tmpid();return"function("+err+(res?","+res:"")+") {\nif("+err+") { cb("+err+"); return; }"},tmpid:function(){return this.lastId++,"t_"+this.lastId},_bufferAppend:function(func){this.emit(this.buffer+" += runtime.suppressValue("),func.call(this),this.emit(", env.autoesc);\n")},_compileChildren:function(node,frame){for(var children=node.children,i=0,l=children.length;l>i;i++)this.compile(children[i],frame)},_compileAggregate:function(node,frame,startChar,endChar){startChar&&this.emit(startChar);for(var i=0;i0&&this.emit(","),this.compile(node.children[i],frame);endChar&&this.emit(endChar)},_compileExpression:function(node,frame){this.assertType(node,nodes.Literal,nodes.Symbol,nodes.Group,nodes.Array,nodes.Dict,nodes.FunCall,nodes.Filter,nodes.LookupVal,nodes.Compare,nodes.InlineIf,nodes.And,nodes.Or,nodes.Not,nodes.Add,nodes.Sub,nodes.Mul,nodes.Div,nodes.FloorDiv,nodes.Mod,nodes.Pow,nodes.Neg,nodes.Pos,nodes.Compare,nodes.NodeList),this.compile(node,frame)},assertType:function(node){for(var types=lib.toArray(arguments).slice(1),success=!1,i=0;i0&&this.emit(","),arg){var id=this.tmpid();this.emitLine("function(cb) {"),this.emitLine("if(!cb) { cb = function(err) { if(err) { throw err; }}}"),this.pushBufferId(id),this.withScopedSyntax(function(){this.compile(arg,frame),this.emitLine("cb(null, "+id+");")}),this.popBufferId(),this.emitLine("return "+id+";"),this.emitLine("}")}else this.emit("null")},this),async){var res=this.tmpid();this.emitLine(", "+this.makeCallback(res)),this.emitLine(this.buffer+" += runtime.suppressValue("+res+", "+autoescape+" && env.autoesc);"),this.addScopeLevel()}else this.emit(")"),this.emit(", "+autoescape+" && env.autoesc);\n")},compileCallExtensionAsync:function(node,frame){this.compileCallExtension(node,frame,!0)},compileNodeList:function(node,frame){this._compileChildren(node,frame)},compileLiteral:function(node){if("string"==typeof node.value){var val=node.value.replace(/\\/g,"\\\\");val=val.replace(/"/g,'\\"'),val=val.replace(/\n/g,"\\n"),val=val.replace(/\r/g,"\\r"),val=val.replace(/\t/g,"\\t"),this.emit('"'+val+'"')}else this.emit(node.value.toString())},compileSymbol:function(node,frame){var v,name=node.value;this.emit((v=frame.lookup(name))?v:'runtime.contextOrFrameLookup(context, frame, "'+name+'")')},compileGroup:function(node,frame){this._compileAggregate(node,frame,"(",")")},compileArray:function(node,frame){this._compileAggregate(node,frame,"[","]")},compileDict:function(node,frame){this._compileAggregate(node,frame,"{","}")},compilePair:function(node,frame){var key=node.key,val=node.value;key instanceof nodes.Symbol?key=new nodes.Literal(key.lineno,key.colno,key.value):key instanceof nodes.Literal&&"string"==typeof key.value||this.fail("compilePair: Dict keys must be strings or names",key.lineno,key.colno),this.compile(key,frame),this.emit(": "),this._compileExpression(val,frame)},compileInlineIf:function(node,frame){this.emit("("),this.compile(node.cond,frame),this.emit("?"),this.compile(node.body,frame),this.emit(":"),null!==node.else_?this.compile(node.else_,frame):this.emit('""'),this.emit(")")},compileOr:binOpEmitter(" || "),compileAnd:binOpEmitter(" && "),compileAdd:binOpEmitter(" + "),compileSub:binOpEmitter(" - "),compileMul:binOpEmitter(" * "),compileDiv:binOpEmitter(" / "),compileMod:binOpEmitter(" % "),compileNot:function(node,frame){this.emit("!"),this.compile(node.target,frame)},compileFloorDiv:function(node,frame){this.emit("Math.floor("),this.compile(node.left,frame),this.emit(" / "),this.compile(node.right,frame),this.emit(")")},compilePow:function(node,frame){this.emit("Math.pow("),this.compile(node.left,frame),this.emit(", "),this.compile(node.right,frame),this.emit(")")},compileNeg:function(node,frame){this.emit("-"),this.compile(node.target,frame)},compilePos:function(node,frame){this.emit("+"),this.compile(node.target,frame)},compileCompare:function(node,frame){this.compile(node.expr,frame);for(var i=0;ii;i++)tmp.push(fill_with);res.push(tmp)}return res},capitalize:function(str){var ret=str.toLowerCase();return r.copySafeness(str,ret.charAt(0).toUpperCase()+ret.slice(1))},center:function(str,width){if(width=width||80,str.length>=width)return str;var spaces=width-str.length,pre=lib.repeat(" ",spaces/2-spaces%2),post=lib.repeat(" ",spaces/2);return r.copySafeness(str,pre+str+post)},"default":function(val,def){return val?val:def},dictsort:function(val,case_sensitive,by){if(!lib.isObject(val))throw new lib.TemplateError("dictsort filter: val must be an object");var array=[];for(var k in val)array.push([k,val[k]]);var si;if(void 0===by||"key"===by)si=0;else{if("value"!==by)throw new lib.TemplateError("dictsort filter: You can only sort by either key or value");si=1}return array.sort(function(t1,t2){var a=t1[si],b=t2[si];return case_sensitive||(lib.isString(a)&&(a=a.toUpperCase()),lib.isString(b)&&(b=b.toUpperCase())),a>b?1:a==b?0:-1}),array},escape:function(str){return"string"==typeof str||str instanceof r.SafeString?lib.escape(str):str},safe:function(str){return r.markSafe(str)},first:function(arr){return arr[0]},groupby:function(arr,attr){return lib.groupBy(arr,attr)},indent:function(str,width,indentfirst){width=width||4;for(var res="",lines=str.split("\n"),sp=lib.repeat(" ",width),i=0;i=maxCount);)last=res,res=res.replace(old,new_),count++;return r.copySafeness(str,res)},reverse:function(val){var arr;return arr=lib.isString(val)?filters.list(val):lib.map(val,function(v){return v}),arr.reverse(),lib.isString(val)?r.copySafeness(val,arr.join("")):arr},round:function(val,precision,method){precision=precision||0;var rounder,factor=Math.pow(10,precision);return rounder="ceil"==method?Math.ceil:"floor"==method?Math.floor:Math.round,rounder(val*factor)/factor},slice:function(arr,slices,fillWith){for(var sliceLength=Math.floor(arr.length/slices),extra=arr.length%slices,offset=0,res=[],i=0;slices>i;i++){var start=offset+i*sliceLength;extra>i&&offset++;var end=offset+(i+1)*sliceLength,slice=arr.slice(start,end);fillWith&&i>=extra&&slice.push(fillWith),res.push(slice)}return res},sort:function(arr,reverse,caseSens,attr){return arr=lib.map(arr,function(v){return v}),arr.sort(function(a,b){var x,y;return attr?(x=a[attr],y=b[attr]):(x=a,y=b),!caseSens&&lib.isString(x)&&lib.isString(y)&&(x=x.toLowerCase(),y=y.toLowerCase()),y>x?reverse?1:-1:x>y?reverse?-1:1:0}),arr},string:function(obj){return r.copySafeness(obj,obj)},title:function(str){for(var words=str.split(" "),i=0;i"+possibleUrl.substr(0,length)+"":wwwRE.test(possibleUrl)?'"+possibleUrl.substr(0,length)+"":emailRE.test(possibleUrl)?''+possibleUrl+"":tldRE.test(possibleUrl)?'"+possibleUrl.substr(0,length)+"":possibleUrl});return words.join(" ")},wordcount:function(str){var words=str?str.match(/\w+/g):null;return words?words.length:null},"float":function(val,def){var res=parseFloat(val);return isNaN(res)?def:res},"int":function(val,def){var res=parseInt(val,10);return isNaN(res)?def:res}};filters.d=filters["default"],filters.e=filters.escape,modules.filters=filters}(),function(){function cycler(items){var index=-1,current=null;return{reset:function(){index=-1,current=null},next:function(){return index++,index>=items.length&&(index=0),current=items[index]}}}function joiner(sep){sep=sep||",";var first=!0;return function(){var val=first?"":sep;return first=!1,val}}var globals={range:function(start,stop,step){stop?step||(step=1):(stop=start,start=0,step=1);for(var arr=[],i=start;stop>i;i+=step)arr.push(i);return arr},cycler:function(){return cycler(Array.prototype.slice.call(arguments))},joiner:function(sep){return joiner(sep)}};modules.globals=globals}(),function(){var Obj=modules.object,lib=modules.lib,Loader=Obj.extend({on:function(name,func){this.listeners=this.listeners||{},this.listeners[name]=this.listeners[name]||[],this.listeners[name].push(func)},emit:function(name){var args=Array.prototype.slice.call(arguments,1);this.listeners&&this.listeners[name]&&lib.each(this.listeners[name],function(listener){listener.apply(null,args)})}});modules.loader=Loader}(),function(){var Loader=modules.loader,WebLoader=Loader.extend({init:function(baseURL,neverUpdate){this.precompiled=window.nunjucksPrecompiled||{},this.baseURL=baseURL||"",this.neverUpdate=neverUpdate},getSource:function(name){if(this.precompiled[name])return{src:{type:"code",obj:this.precompiled[name]},path:name};var src=this.fetch(this.baseURL+"/"+name);return src?{src:src,path:name,noCache:!this.neverUpdate}:null},fetch:function(url){var ajax,src,loading=!0;return window.XMLHttpRequest?ajax=new XMLHttpRequest:window.ActiveXObject&&(ajax=new ActiveXObject("Microsoft.XMLHTTP")),ajax.onreadystatechange=function(){4!==ajax.readyState||0!==ajax.status&&200!==ajax.status||!loading||(loading=!1,src=ajax.responseText)},url+=(-1===url.indexOf("?")?"?":"&")+"s="+(new Date).getTime(),ajax.open("GET",url,!1),ajax.send(),src}});modules["web-loaders"]={WebLoader:WebLoader}}(),function(){modules.loaders="undefined"==typeof window||window!==this?modules["node-loaders"]:modules["web-loaders"]}(),function(){var path=modules.path,lib=modules.lib,Obj=modules.object,lexer=modules.lexer,compiler=modules.compiler,builtin_filters=modules.filters,builtin_loaders=modules.loaders,runtime=modules.runtime,globals=modules.globals,Frame=runtime.Frame,Environment=Obj.extend({init:function(loaders,opts){opts=opts||{},this.dev=!!opts.dev,this.autoesc=!!opts.autoescape,this.loaders=loaders?lib.isArray(loaders)?loaders:[loaders]:builtin_loaders.FileSystemLoader?[new builtin_loaders.FileSystemLoader("views")]:[new builtin_loaders.WebLoader("/views")],this.initCache(),this.filters={},this.asyncFilters=[],this.extensions={},this.extensionsList=[],opts.tags&&lexer.setTags(opts.tags);for(var name in builtin_filters)this.addFilter(name,builtin_filters[name])},initCache:function(){var cache={};lib.each(this.loaders,function(loader){"function"==typeof loader.on&&loader.on("update",function(template){cache[template]=null})}),this.cache=cache},addExtension:function(name,extension){extension._name=name,this.extensions[name]=extension,this.extensionsList.push(extension)},getExtension:function(name){return this.extensions[name]},addGlobal:function(name,value){globals[name]=value},addFilter:function(name,func,async){var wrapped=func;async&&this.asyncFilters.push(name),this.filters[name]=wrapped},getFilter:function(name){if(!this.filters[name])throw new Error("filter not found: "+name);return this.filters[name]},getTemplate:function(name,eagerCompile,cb){if(name&&name.raw&&(name=name.raw),lib.isFunction(eagerCompile)&&(cb=eagerCompile,eagerCompile=!1),"string"!=typeof name)throw new Error("template names must be a string: "+name);var tmpl=this.cache[name];if(!tmpl){var syncResult;return lib.asyncIter(this.loaders,function(loader,i,next,done){function handle(src){src?done(src):next()}loader.async?loader.getSource(name,function(err,src){if(err)throw err;handle(src)}):handle(loader.getSource(name))},function(info){if(info){var tmpl=new Template(info.src,this,info.path,eagerCompile);info.noCache||(this.cache[name]=tmpl),cb?cb(null,tmpl):syncResult=tmpl}else{var err=new Error("template not found: "+name);if(!cb)throw err;cb(err)}}.bind(this)),syncResult}return eagerCompile&&tmpl.compile(),cb?void cb(null,tmpl):tmpl},express:function(app){function NunjucksView(name,opts){if(this.name=name,this.path=name,this.defaultEngine=opts.defaultEngine,this.ext=path.extname(name),!this.ext&&!this.defaultEngine)throw new Error("No default engine was specified and no extension was provided.");this.ext||(this.name+=this.ext=("."!==this.defaultEngine[0]?".":"")+this.defaultEngine)}var env=this;NunjucksView.prototype.render=function(opts,cb){env.render(this.name,opts,cb)},app.set("view",NunjucksView)},render:function(name,ctx,cb){lib.isFunction(ctx)&&(cb=ctx,ctx=null);var syncResult=null;return this.getTemplate(name,function(err,tmpl){if(err&&cb)cb(err);else{if(err)throw err;tmpl.render(ctx,cb||function(err,res){if(err)throw err;syncResult=res})}}),syncResult},renderString:function(src,ctx,cb){var tmpl=new Template(src,this);return tmpl.render(ctx,cb)}}),Context=Obj.extend({init:function(ctx,blocks){this.ctx=ctx,this.blocks={},this.exported=[];for(var name in blocks)this.addBlock(name,blocks[name])},lookup:function(name){return name in globals&&!(name in this.ctx)?globals[name]:this.ctx[name]},setVariable:function(name,val){this.ctx[name]=val},getVariables:function(){return this.ctx},addBlock:function(name,block){this.blocks[name]=this.blocks[name]||[],this.blocks[name].push(block)},getBlock:function(name){if(!this.blocks[name])throw new Error('unknown block "'+name+'"');return this.blocks[name][0]},getSuper:function(env,name,block,frame,runtime,cb){var idx=(this.blocks[name]||[]).indexOf(block),blk=this.blocks[name][idx+1],context=this;if(-1==idx||!blk)throw new Error('no super block available for "'+name+'"');blk(env,context,frame,runtime,cb)},addExport:function(name){this.exported.push(name)},getExported:function(){for(var exported={},i=0;i0&&index+match.length!==title.length&&match.search(smallWords)>-1&&":"!==title.charAt(index-2)&&("-"!==title.charAt(index+match.length)||"-"===title.charAt(index-1))&&title.charAt(index-1).search(/[^\s-]/)<0?match.toLowerCase():match.substr(1).search(/[A-Z]|\../)>-1?match:match.charAt(0).toUpperCase()+match.substr(1)})}function trim(s){return s.replace(/^\s+|\s+$/g,"")}function mightBeEmail(s){return/[^@]+@[^@]+/.test(s)}function warn(msg){console.warn("[analytics] "+msg)}function _gaEvent(options){if("function"==typeof ga){var fieldObject={hitType:"event",eventCategory:_category,eventAction:options.action};options.label&&(fieldObject.eventLabel=options.label),(options.value||0===options.value)&&(fieldObject.eventValue=options.value),options.nonInteraction===!0&&(fieldObject.nonInteraction=1),ga("send",fieldObject)}var eventArgs=["_trackEvent",_category,options.action];options.label&&(eventArgs[3]=options.label),(options.value||0===options.value)&&(eventArgs[4]=options.value),options.nonInteraction===!0&&(eventArgs[5]=!0),_gaq.push(eventArgs)}function event(action,options){options=options||{};var eventOptions={},label=options.label,value=options.value,nonInteraction=options.noninteraction||options.nonInteraction;return action?(mightBeEmail(action)&&(warn("`action` arg looks like an email address, redacting."),action=_redacted),eventOptions.action=toTitleCase(action),label&&("string"!=typeof label?warn("Expected `label` arg to be a String."):(mightBeEmail(label)&&(warn("`label` arg looks like an email address, redacting."),label=_redacted),eventOptions.label=trim(label))),(value||0===value)&&("number"!=typeof value?warn("Expected `value` arg to be a Number."):eventOptions.value=0|value),nonInteraction&&("boolean"!=typeof nonInteraction?warn("Expected `noninteraction` arg to be a Boolean."):eventOptions.nonInteraction=nonInteraction===!0),void _gaEvent(eventOptions)):void warn("Expected `action` arg.")}function prefixVirtualPageview(s){return/^\/virtual\//.test(s)?s:(s=s.replace(/^[/]?/,"/"),"/virtual"+s)}function _gaVirtualPageView(options){if("function"==typeof ga){var fieldObject={hitType:"pageview",page:options.virtualPagePath};ga("send",fieldObject)}var eventArgs=["_trackPageview",options.virtualPagePath];_gaq.push(eventArgs)}function virtualPageview(virtualPagePath){if(!virtualPagePath)return void warn("Expected `virtualPagePath` arg.");virtualPagePath=trim(virtualPagePath);var eventOptions={};eventOptions.virtualPagePath=prefixVirtualPageview(virtualPagePath),_gaVirtualPageView(eventOptions)}function _optimizely(options){var eventArgs=["trackEvent",options.action];if(options.revenue){var args={revenue:options.revenue};eventArgs[2]=args}optimizely.push(eventArgs)}function conversionGoal(action,options){options=options||{};var eventOptions={},valueInCents=options.valueInCents;return action?(eventOptions.action=trim(action),valueInCents&&("number"==typeof valueInCents&&valueInCents%1===0?eventOptions.revenue=valueInCents:warn("Expected `valueInCents` arg to be an integer.")),void _optimizely(eventOptions)):void warn("Expected `action` arg.")}this._gaq||(this._gaq=[]),this.optimizely||(this.optimizely=[]);var _category=location.hostname,_redacted="REDACTED (Potential Email Address)";return{event:event,virtualPageview:virtualPageview,conversionGoal:conversionGoal}})},{}],18:[function(require,module){function _each(baseEl,selector,cb){if(baseEl){var els=baseEl.querySelectorAll(selector);if(els)for(var i=0;i\n \n \n \n\n\n',template_options),login:template.renderString('\n\n',template_options),reset:template.renderString('\n\n',template_options),wrapper:'\n\n'},_create_modal_fragment=function(template){var range=document.createRange(); -range.selectNode(document.body);var modal_fragment=range.createContextualFragment(ui.wrapper);return modal_fragment.querySelector(".modal-content").appendChild(range.createContextualFragment(template)),modal_fragment},_translate_ng_html_expressions=function(modal_fragment){var elements=modal_fragment.querySelectorAll("[ng-bind-html]"),i=0;for(i=0;i div.modal-backdrop")),document.body.removeChild(document.querySelector("body > div.modal"))},_attach_close=function(modal){_each(modal,"[ng-click='close()']",function(i,el){el.addEventListener("click",function(event){event.preventDefault(),_close_modal()},!1)})},WebmakerLogin=function(options){var wmLogin=this.wmLogin=new wmLoginCore(options);this.showCTA=!!options.showCTA,this.disablePersona=!!options.disablePersona,EventEmitter.call(this);var query=url.parse(window.location.href,!0).query;query.uid&&query.resetCode?this.request_password_reset(query.uid,query.resetCode):query.uid&&query.token&&(wmLogin.instantLogin(query.uid,query.token,query.validFor),wmLogin.on("signedIn",function(user){this.emit("login",user)}.bind(this)),wmLogin.on("signinFailed",function(uid){console.log("Instant signin failed for uid %s",uid),this.login(uid,{expired:!0})}.bind(this))),wmLogin.on("verified",function(user){this.emit("verified",user)}.bind(this)),wmLogin.on("error",function(err){this.emit("error",err)}.bind(this)),wmLogin.verify()};util.inherits(WebmakerLogin,EventEmitter),WebmakerLogin.prototype.create=function(email_hint,username_hint,agreeToTerms_hint){var controller=this.wmLogin.joinWebmaker(this.showCTA),scope={MODALSTATE:{inputEmail:0,inputUsername:1,welcome:2},currentState:-1,form:{user:{$error:{}}},user:{},sendingRequest:!1,welcomeModalIdx:-1},modal_fragment=_create_modal_fragment(ui.create);_translate_ng_html_expressions(modal_fragment);var usernameWithUrl=modal_fragment.querySelector(".username-with-url");email_hint&&(scope.user.email=email_hint,modal_fragment.querySelector('input[name="email"]').value=email_hint),username_hint&&(scope.user.username=username_hint,modal_fragment.querySelector('input[name="username"]').value=username_hint,usernameWithUrl.textContent=scope.user.username),scope.user.agree=agreeToTerms_hint,controller.on("sendingRequest",function(state){scope.sendingRequest=state,_run_expressions(modal,scope)}),controller.on("displayEmailInput",function(){scope.currentState=scope.MODALSTATE.inputEmail,_run_expressions(modal,scope),modal.querySelector('input[focus-on="create-user-email"]').focus(),void 0!==scope.user.email&&controller.validateEmail(scope.user.email)&&void 0!==scope.user.agree&&(controller.submitEmail(scope.user.agree),scope.user.agree&&(scope.skippedEmail="true",controller.validateUsername(scope.user.username)))}),controller.on("displayUsernameInput",function(){scope.currentState=scope.MODALSTATE.inputUsername,_run_expressions(modal,scope),modal.querySelector('input[focus-on="create-user-username"]').focus()}),controller.on("displayWelcome",function(user,showCTA){this.emit("login",user),showCTA?scope.welcomeModalIdx=0:scope.simpleCTA=!0,scope.currentState=scope.MODALSTATE.welcome,_run_expressions(modal,scope)}.bind(this)),controller.on("displayAlert",function(alertId){scope.form.user.$error[alertId]=!0,_run_expressions(modal,scope)}),controller.on("hideAlert",function(alertId){scope.form.user.$error[alertId]=!1,_run_expressions(modal,scope)}),modal_fragment.querySelector('a[ng-click="switchToSignin();"]').addEventListener("click",function(event){event.preventDefault(),_close_modal(),setTimeout(function(){this.login(scope.user.email)}.bind(this),0)}.bind(this)),modal_fragment.querySelector('input[name="email"]').addEventListener("keyup",function(e){scope.user.email=e.target.value,e.target.value&&controller.validateEmail(scope.user.email)}),modal_fragment.querySelector('input[name="agree"]').addEventListener("change",function(e){scope.user.agree=e.target.checked,controller.agreeToTermsChanged(scope.user.agree),_run_expressions(modal,scope)}),modal_fragment.querySelector('input[name="subscribeToList"]').addEventListener("change",function(e){scope.user.subscribeToList=e.target.checked}),_each(modal_fragment,'button[ng-click="submitEmail()"]',function(i,el){el.addEventListener("click",function(){controller.submitEmail(scope.user.agree)})}),modal_fragment.querySelector('input[name="username"]').addEventListener("input",function(e){scope.user.username=e.target.value,controller.validateUsername(scope.user.username),usernameWithUrl.textContent=scope.user.username}),_each(modal_fragment,'button[ng-click="submitUser()"]',function(i,el){el.addEventListener("click",function(){controller.submitUser(scope.user)})}),_run_expressions(modal_fragment,scope),_open_modal(modal_fragment);var modal=document.querySelector("body > div.modal");_attach_close(modal),document.querySelector("body > div.modal > .modal-dialog").addEventListener("click",function(e){e.stopPropagation()}),document.querySelector("body > div.modal").addEventListener("click",function(){_close_modal()}),controller.start()},WebmakerLogin.prototype.login=function(uid_hint,options){options=options||{};var controller=this.wmLogin.signIn(),scope={MODALSTATE:{enterUid:0,checkEmail:1,enterKey:2,enterPassword:3,resetRequestSent:4},currentState:0,form:{user:{$error:{}}},user:{},passwordWasReset:!!options.password_was_reset,expiredLoginLink:!!options.expired,sendingRequest:!1,disablePersona:this.disablePersona},modal_fragment=_create_modal_fragment(ui.login);_translate_ng_html_expressions(modal_fragment),uid_hint&&(scope.user.uid=uid_hint,modal_fragment.querySelector('input[name="uid"]').value=uid_hint),controller.on("sendingRequest",function(state){scope.sendingRequest=state,_run_expressions(modal,scope)}),controller.on("displayEnterUid",function(){scope.currentState=scope.MODALSTATE.enterUid,_run_expressions(modal,scope),modal.querySelector('input[focus-on="login-uid"]').focus()}),controller.on("displayEnterPassword",function(){scope.currentState=scope.MODALSTATE.enterPassword,_run_expressions(modal,scope),modal.querySelector('input[focus-on="enter-password"]').focus()}),controller.on("displayEnterKey",function(verified){scope.verified=verified,scope.currentState=scope.MODALSTATE.enterKey,_run_expressions(modal,scope),modal.querySelector('input[focus-on="enter-key"]').focus()}),controller.on("displayCheckEmail",function(){scope.currentState=scope.MODALSTATE.checkEmail,_run_expressions(modal,scope)}),controller.on("displayResetSent",function(){scope.currentState=scope.MODALSTATE.resetRequestSent,_run_expressions(modal,scope)}),controller.on("displayAlert",function(alertId){scope.form.user.$error[alertId]=!0,_run_expressions(modal,scope)}),controller.on("hideAlert",function(alertId){scope.form.user.$error[alertId]=!1,_run_expressions(modal,scope)}),controller.on("signedIn",function(user){this.emit("login",user),_close_modal()}.bind(this)),modal_fragment.querySelector('input[name="uid"]').addEventListener("input",function(e){scope.user.uid=e.target.value,_run_expressions(modal,scope)}),_each(modal_fragment,'input[name="rememberMe"]',function(i,el){el.addEventListener("change",function(e){scope.user.rememberMe=e.target.checked,_run_expressions(modal,scope)})}),_each(modal_fragment,'button[ng-click="submitUid()"]',function(i,el){el.addEventListener("click",function(){controller.submitUid(scope.user.uid,window.location.pathname)})}),_each(modal_fragment,'input[name="key"]',function(i,el){el.addEventListener("input",function(e){scope.user.key=e.target.value,_run_expressions(modal,scope)})}),_each(modal_fragment,'a[ng-click="enterKey()"]',function(i,el){el.addEventListener("click",function(event){event.preventDefault(),controller.displayEnterKey()})}),_each(modal_fragment,'button[ng-click="user.key && submitKey()"]',function(i,el){el.addEventListener("click",function(){controller.verifyKey(scope.user.uid,scope.user.key,scope.user.rememberMe)})}),modal_fragment.querySelector('input[name="password"]').addEventListener("input",function(e){scope.user.password=e.target.value,_run_expressions(modal,scope)}),_each(modal_fragment,'button[ng-click="user.password && submitPassword()"]',function(i,el){el.addEventListener("click",function(){controller.verifyPassword(scope.user.uid,scope.user.password,scope.user.rememberMe)})}),modal_fragment.querySelector('a[ng-click="requestReset()"]').addEventListener("click",function(event){event.preventDefault(),controller.requestReset(scope.user.uid)}),modal_fragment.querySelector('a[ng-click="switchToSignup();"]').addEventListener("click",function(event){event.preventDefault(),_close_modal(),setTimeout(function(){var uid=scope.user.uid,type=controller.getUidType(uid),email="email"===type?uid:"",username="username"===type?uid:"";this.create(email,username)}.bind(this),0)}.bind(this)),modal_fragment.querySelector('button[ng-click="usePersona();"]').addEventListener("click",function(event){event.preventDefault(),_close_modal(),setTimeout(function(){this._persona_login()}.bind(this),0)}.bind(this)),modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && !sendingRequest && submitUid()"]').addEventListener("keyup",function(event){13!==event.keyCode||scope.sendingRequest||controller.submitUid(scope.user.uid,window.location.pathname)}.bind(this)),modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && user.key && !sendingRequest && submitKey()"]').addEventListener("keyup",function(event){13===event.keyCode&&scope.user.key&&!scope.sendingRequest&&controller.verifyKey(scope.user.uid,scope.user.key,scope.user.rememberMe)}.bind(this)),modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && user.password && !sendingRequest && submitPassword()"]').addEventListener("keyup",function(event){13===event.keyCode&&scope.user.password&&!scope.sendingRequest&&controller.verifyPassword(scope.user.uid,scope.user.password,scope.user.rememberMe)}.bind(this)),_run_expressions(modal_fragment,scope),_open_modal(modal_fragment);var modal=document.querySelector("body > div.modal");_attach_close(modal),document.querySelector("body > div.modal > .modal-dialog").addEventListener("click",function(e){e.stopPropagation()}),document.querySelector("body > div.modal").addEventListener("click",function(){_close_modal()}),controller.start()},WebmakerLogin.prototype._persona_login=function(){var controller=this.wmLogin.personaLogin();controller.on("signedIn",function(user){this.emit("login",user)}.bind(this)),controller.on("newUser",function(email){this.create(email)}.bind(this)),controller.authenticate()},WebmakerLogin.prototype.request_password_reset=function(uid,token){var controller=this.wmLogin.resetPassword(),scope={form:{password:{$error:{}}},password:{},sendingRequest:!1},modal_fragment=_create_modal_fragment(ui.reset);_translate_ng_html_expressions(modal_fragment),controller.on("sendingRequest",function(state){scope.sendingRequest=state,_run_expressions(modal,scope)}),controller.on("displayAlert",function(alertId){scope.form.password.$error[alertId]=!0,_run_expressions(modal,scope)}),controller.on("hideAlert",function(alertId){scope.form.password.$error[alertId]=!1,_run_expressions(modal,scope)}),controller.on("checkConfirmPassword",function(status){scope.passwordsMatch=status,_run_expressions(modal,scope)}),controller.on("passwordCheckResult",function(result,blur){return result?(scope.eightCharsState=result.lengthValid?blur?"valid":"":"invalid",scope.oneEachCaseState=result.caseValid?blur?"valid":"":"invalid",scope.oneNumberState=result.digitValid?blur?"valid":"":"invalid",scope.isValidPassword=result.lengthValid&&result.caseValid&&result.digitValid,void _run_expressions(modal,scope)):(scope.eightCharsState=scope.oneEachCaseState=scope.oneNumberState="default",void(scope.isValidPassword=!1))}),controller.on("resetSucceeded",function(){_close_modal(),setTimeout(function(){this.login(uid,{password_was_reset:!0})}.bind(this),0)}.bind(this)),modal_fragment.querySelector('input[name="value"]').addEventListener("input",function(e){scope.password.value=e.target.value,controller.checkPasswordStrength(scope.password.value,!1)}),modal_fragment.querySelector('input[name="value"]').addEventListener("blur",function(e){scope.password.value=e.target.value,controller.checkPasswordStrength(scope.password.value,!0)}),modal_fragment.querySelector('input[name="confirmValue"]').addEventListener("input",function(e){scope.password.confirmValue=e.target.value,controller.passwordsMatch(scope.password.value,scope.password.confirmValue,!1)}),modal_fragment.querySelector('input[name="confirmValue"]').addEventListener("blur",function(e){scope.password.confirmValue=e.target.value,controller.passwordsMatch(scope.password.value,scope.password.confirmValue,!0)}),modal_fragment.querySelector('button[ng-click="submitResetRequest()"]').addEventListener("click",function(){controller.submitResetRequest(uid,token,scope.password.value)}),_run_expressions(modal_fragment,scope),_open_modal(modal_fragment);var modal=document.querySelector("body > div.modal");_attach_close(modal),document.querySelector("body > div.modal > .modal-dialog").addEventListener("click",function(e){e.stopPropagation()}),document.querySelector("body > div.modal").addEventListener("click",function(){_close_modal()})},WebmakerLogin.prototype.logout=function(){var controller=this.wmLogin.logout();controller.on("loggedOut",function(){this.emit("logout")}.bind(this)),controller.logout()},window.WebmakerLogin=WebmakerLogin,module.exports=WebmakerLogin},{"../../locale/en_US/webmaker-login.json":1,"../core":19,"angular-expressions":2,events:6,nunjucks:16,url:13,util:15}],19:[function(require,module){var state=require("./state"),LoginAPI=require("./loginAPI"),Emitter=require("./state/emitter");module.exports=function(options){function verify(){loginAPI.verify(function(err,resp,body){if(err)return emitter.emit("error",err);try{body=JSON.parse(body)}catch(ex){return emitter.emit("error","could not parse json from verify route")}emitter.emit("verified",body.user)})}var loginAPI=new LoginAPI(options),emitter=new Emitter;return window.addEventListener("focus",verify),{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},joinWebmaker:function(showCTA){return new state.JoinController(loginAPI,!!showCTA)},signIn:function(){return new state.SignInController(loginAPI)},resetPassword:function(){return new state.ResetController(loginAPI)},personaLogin:function(){return new state.PersonaController(loginAPI)},logout:function(){return new state.LogoutController(loginAPI)},instantLogin:function(uid,password,validFor){loginAPI.verifyKey(uid,password,validFor,function(err,resp,body){return err||200!==resp.status||!body.user?emitter.emit("signinFailed",uid):void emitter.emit("signedIn",body.user)})},verify:verify}}},{"./loginAPI":20,"./state":24,"./state/emitter":23}],20:[function(require,module){var request=require("browser-request");module.exports=function(options){function doRequest(uri,payload,callback){request({method:"post",uri:uri,timeout:timeout,withCredentials:withCredentials,headers:headers,json:payload},callback)}function uidExists(uid,callback){doRequest(loginUrls.uidExists,{uid:uid},callback)}function checkUsername(username,callback){doRequest(loginUrls.checkUsername,{username:username},callback)}function createUser(user,callback){user.referrer=refferals.refValue(),doRequest(loginUrls.createUser,{user:user,audience:audience},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function sendLoginKey(uid,path,callback){doRequest(loginUrls.request,{uid:uid,path:path},callback)}function verifyKey(uid,key,validFor,callback){doRequest(loginUrls.authenticateToken,{uid:uid,token:key,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function verifyPassword(uid,password,validFor,callback){doRequest(loginUrls.verifyPassword,{uid:uid,password:password,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function requestReset(uid,callback){doRequest(loginUrls.requestResetCode,{uid:uid},callback)}function resetPassword(uid,resetCode,password,callback){doRequest(loginUrls.resetPassword,{uid:uid,resetCode:resetCode,newPassword:password},callback)}function personaLogin(assertion,callback){doRequest(loginUrls.authenticate,{assertion:assertion,audience:audience,user:{referrer:refferals.refValue()}},callback)}function logout(callback){doRequest(loginUrls.logout,null,callback)}function verify(callback){doRequest(loginUrls.verify,null,callback)}options=options||{},options.paths=options.paths||{};var refferals=require("./referrals.js")(),loginUrls=require("./loginUrls.js")(options),withCredentials=options.withCredentials===!1?!1:!0,timeout=1e3*(options.timeout||10),headers={"X-CSRF-Token":options.csrfToken},audience=options.audience||window.location.protocol+"//"+window.location.host;return{uidExists:uidExists,checkUsername:checkUsername,createUser:createUser,sendLoginKey:sendLoginKey,verifyKey:verifyKey,verifyPassword:verifyPassword,requestReset:requestReset,resetPassword:resetPassword,personaLogin:personaLogin,logout:logout,verify:verify}}},{"./loginUrls.js":21,"./referrals.js":22,"browser-request":4}],21:[function(require,module){module.exports=function(options){var paths={},host=options.host||"";return paths=options.paths||{},paths.authenticate=options.paths.authenticate||"/authenticate",paths.legacyCreate=options.paths.legacyCreate||"/create",paths.verify=options.paths.verify||"/verify",paths.logout=options.paths.logout||"/logout",paths.checkUsername=options.paths.checkUsername||"/check-username",paths.request=options.paths.request||"/auth/v2/request",paths.uidExists=options.paths.uidExists||"/auth/v2/uid-exists",paths.createUser=options.paths.createUser||"/auth/v2/create",paths.authenticateToken=options.paths.authenticateToken||"/auth/v2/authenticateToken",paths.verifyPassword=options.paths.verifyPassword||"/auth/v2/verify-password",paths.requestResetCode=options.paths.requestResetCode||"/auth/v2/request-reset-code",paths.removePassword=options.paths.removePassword||"/auth/v2/remove-password",paths.enablePasswords=options.paths.enablePasswords||"/auth/v2/enable-passwords",paths.resetPassword=options.paths.resetPassword||"/auth/v2/reset-password",{request:host+paths.request,authenticateToken:host+paths.authenticateToken,authenticate:host+paths.authenticate,legacyCreate:host+paths.legacyCreate,createUser:host+paths.createUser,verify:host+paths.verify,logout:host+paths.logout,uidExists:host+paths.uidExists,checkUsername:host+paths.checkUsername,verifyPassword:host+paths.verifyPassword,requestResetCode:host+paths.requestResetCode,removePassword:host+paths.removePassword,enablePasswords:host+paths.enablePasswords,resetPassword:host+paths.resetPassword}}},{}],22:[function(require,module){var cookiejs=require("cookie-js");module.exports=function(){var referralCookieSettings={domain:location.hostname.split(".").slice(-2).join("."),path:"/",secure:"https:"===location.protocol,expires:new Date(Date.now()+6048e5)},refValue=/ref=((?:\w|-)+)/.exec(window.location.search),cookieRefValue=cookiejs.parse(document.cookie).webmakerReferral;return refValue&&(refValue=refValue[1],cookieRefValue!==refValue&&(document.cookie=cookiejs.serialize("webmakerReferral",refValue,referralCookieSettings),cookieRefValue=refValue)),{clearReferrerCookie:function(){referralCookieSettings.expires=new Date(Date.now()-1e4),document.cookie=cookiejs.serialize("webmakerReferral","expire",referralCookieSettings),referralCookieSettings.expires=new Date(Date.now()+6048e5)},refValue:function(){return cookieRefValue}}}},{"cookie-js":5}],23:[function(require,module){var EventEmitter=require("events").EventEmitter;module.exports=function(){var emitter=new EventEmitter;return{on:function(event,listener){emitter.addListener(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):void emitter.removeAllListeners(event)},emit:function(){emitter.emit.apply(emitter,arguments)}}}},{events:6}],24:[function(require,module){module.exports={JoinController:require("./join.js"),SignInController:require("./signin.js"),ResetController:require("./reset.js"),PersonaController:require("./persona.js"),LogoutController:require("./logout.js")}},{"./join.js":25,"./logout.js":26,"./persona.js":27,"./reset.js":28,"./signin.js":29}],25:[function(require,module){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi,showCTA){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(JOIN_EVENTS.sendingRequest,state,state?!1:!0)}function displayAlert(alertId,forceUpdate){emit(JOIN_EVENTS.displayAlert,alertId,forceUpdate)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alert){emit(JOIN_EVENTS.hideAlert,alert)})}function validateEmailCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.accountExists,!0):void 0}function usernameExistsCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.usernameTaken,!0):void emit(JOIN_EVENTS.displayUsernameInput)}var emitter=new Emitter,JOIN_ALERTS={agreeToTerms:"agreeToTerms",accountExists:"accountExists",invalidEmail:"invalidEmail",invalidUsername:"invalidUsername",usernameTaken:"usernameTaken",serverError:"serverError"},JOIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayUsernameInput:"displayUsernameInput",displayEmailInput:"displayEmailInput",displayWelcome:"displayWelcome"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):emitter.off(event)},start:function(){emit(JOIN_EVENTS.displayEmailInput)},validateEmail:function(email){clearAlerts([JOIN_ALERTS.invalidEmail,JOIN_ALERTS.accountExists,JOIN_ALERTS.serverError]);var valid=validation.isEmail(email);return valid?(setRequestState(!0),loginApi.uidExists(email,validateEmailCallback),!0):(displayAlert(JOIN_ALERTS.invalidEmail),!1)},submitEmail:function(agreeToTerms){return agreeToTerms?void emit(JOIN_EVENTS.displayUsernameInput):displayAlert(JOIN_ALERTS.agreeToTerms)},agreeToTermsChanged:function(agree){agree&&emit(JOIN_EVENTS.hideAlert,JOIN_ALERTS.agreeToTerms)},validateUsername:function(username){if(clearAlerts([JOIN_ALERTS.invalidUsername,JOIN_ALERTS.usernameTaken,JOIN_ALERTS.serverError]),username){var valid=validation.isUsername(username);if(!valid)return displayAlert(JOIN_ALERTS.invalidUsername);setRequestState(!0),loginApi.uidExists(username,usernameExistsCallback)}},submitUser:function(formData){clearAlerts([JOIN_ALERTS.agreeToTerms,JOIN_ALERTS.serverError]);var lang="en-US",html=document.querySelector("html");html.lang&&(lang=html.lang),setRequestState(!0),loginApi.createUser({email:formData.email,username:formData.username,mailingList:formData.subscribeToList,prefLocale:lang},function(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError):(analytics.event("Webmaker New User Created",{nonInteraction:!0}),analytics.conversionGoal("WebmakerNewUserCreated"),void emit(JOIN_EVENTS.displayWelcome,body.user,showCTA))})}}}},{"../validation":30,"./emitter.js":23,"webmaker-analytics":17}],26:[function(require,module){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginAPI){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter;return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},logout:function(){loginAPI.logout(function(err,resp){return err||200!==resp.status?emit("logoutFailed"):(analytics.event("Webmaker Logout Clicked"),void emit("loggedOut"))})}}}},{"./emitter.js":23,"webmaker-analytics":17}],27:[function(require,module){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter,PERSONA_EVENTS={signedIn:"signedIn",newUser:"newUser"},analyticsLabel={label:"persona"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},authenticate:function(){return window.navigator.id?(analytics.event("Persona Login Clicked"),void window.navigator.id.get(function(assertion){return assertion?void loginApi.personaLogin(assertion,function(err,resp,body){return err||200!==resp.status?void analytics.event("Webmaker Login Failed",analyticsLabel):(analytics.event("Webmaker Login Succeeded",analyticsLabel),void(body.user?emit(PERSONA_EVENTS.signedIn,body.user):body.email&&(analytics.event("Webmaker New User Started",analyticsLabel),emit(PERSONA_EVENTS.newUser,body.email))))}):void analytics.event("Webmaker Login Cancelled",analyticsLabel)})):console.error("No persona found. Did you load include.js?")}}}},{"./emitter.js":23,"webmaker-analytics":17}],28:[function(require,module){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(RESET_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(RESET_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(RESET_EVENTS.hideAlert,alertId)}var emitter=new Emitter,RESET_ALERTS={passwordsMustMatch:"passwordsMustMatch",weakPassword:"weakPassword",serverError:"serverError"},RESET_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",resetSucceeded:"resetSucceeded",passwordCheckResult:"passwordCheckResult",checkConfirmPassword:"checkConfirmPassword"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},passwordsMatch:function(password,confimValue,blur){validation.passwordsMatch(password,confimValue)?(hideAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!0)):(blur&&displayAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!1))},checkPasswordStrength:function(password,blur){emit(RESET_EVENTS.passwordCheckResult,validation.checkPasswordStrength(password),blur)},submitResetRequest:function(uid,resetCode,password){hideAlert(RESET_ALERTS.serverError),hideAlert(RESET_ALERTS.weakPassword),setRequestState(!0),loginApi.resetPassword(uid,resetCode,password,function(err,resp){return setRequestState(!1),err||200!==resp.status?displayAlert(400===resp.status?RESET_ALERTS.weakPassword:RESET_ALERTS.serverError):(analytics.event("Webmaker Password Reset Succeeded"),void emit(RESET_EVENTS.resetSucceeded))})}}}},{"../validation":30,"./emitter.js":23,"webmaker-analytics":17}],29:[function(require,module){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(SIGNIN_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(SIGNIN_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(SIGNIN_EVENTS.hideAlert,alertId)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alertId){hideAlert(alertId)})}var emitter=new Emitter,SIGNIN_ALERTS={paswordReset:"paswordReset",noAccount:"noAccount",invalidUid:"invalidUid",serverError:"serverError",invalidKey:"invalidKey",passwordSigninFailed:"passwordSigninFailed",resetRequestFailed:"resetRequestFailed"},SIGNIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayEnterUid:"displayEnterUid",displayEnterPassword:"displayEnterPassword",displayEnterKey:"displayEnterKey",displayCheckEmail:"displayCheckEmail",displayResetSent:"displayResetSent",signedIn:"signedIn"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},start:function(){emit(SIGNIN_EVENTS.displayEnterUid)},submitUid:function(uid,path){clearAlerts([SIGNIN_ALERTS.invalidUid,SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.noAccount]);var valid=validation.isEmail(uid)||validation.isUsername(uid);return valid?(setRequestState(!0),void loginApi.uidExists(uid,function(err,resp,body){if(setRequestState(!1),err||200!==resp.status)return displayAlert(SIGNIN_ALERTS.serverError);var isVerified=body.verified;return body.exists?body.usePasswordLogin?emit(SIGNIN_EVENTS.displayEnterPassword):void loginApi.sendLoginKey(uid,path,function(err){return err?displayAlert(SIGNIN_ALERTS.serverError):void(isVerified?emit(SIGNIN_EVENTS.displayEnterKey,!1):emit(SIGNIN_EVENTS.displayCheckEmail))}):displayAlert(SIGNIN_ALERTS.noAccount)})):displayAlert(SIGNIN_ALERTS.invalidUid)},displayEnterKey:function(){emit(SIGNIN_EVENTS.displayEnterKey,!0)},verifyKey:function(uid,key,rememberMe){clearAlerts([SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.invalidKey]),setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyKey(uid,key,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"key"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.invalidKey)})},verifyPassword:function(uid,password,rememberMe){setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyPassword(uid,password,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"password"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.passwordSigninFailed)})},requestReset:function(uid){setRequestState(!0),loginApi.requestReset(uid,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.status?(analytics.event("Webmaker Password Reset Requested"),void emit(SIGNIN_EVENTS.displayResetSent)):displayAlert(SIGNIN_ALERTS.resetRequestFailed)})},getUidType:function(uid){return validation.isEmail(uid)?"email":validation.isUsername(uid)?"username":null}}}},{"../validation":30,"./emitter.js":23,"webmaker-analytics":17}],30:[function(require,module){var usernameRegex=/^[a-zA-Z0-9\-]{1,20}$/,emailRegex=/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,containsBothCases=/^.*(?=.*[a-z])(?=.*[A-Z]).*$/,containsDigit=/\d/,MIN_PASSWORD_LEN=8; -module.exports={isEmail:function(email){return emailRegex.test(email)},isUsername:function(username){return usernameRegex.test(username)},passwordsMatch:function(password,confirmation){return password===confirmation},checkPasswordStrength:function(password){if(!password)return!1;var lengthValid=password.length>=MIN_PASSWORD_LEN,caseValid=!!password.match(containsBothCases),digitValid=!!password.match(containsDigit);return{lengthValid:lengthValid,caseValid:caseValid,digitValid:digitValid}}}},{}]},{},[18]); \ No newline at end of file +!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;oget help.',description:"Error message displayed if an error occurs on the server."},webmakerAuthCreateWelcome:{message:"Create An Account",description:"Header text for the join modal dialog"},webmakerAuthChooseUsername:{message:"Choose A Username",description:"Label text for the username selection input"},webmakerAuthTakenError:{message:' That username is taken. Try adding your favourite number at the end.',description:"Error message displayed when the entered username is not available for use."},webmakerAuthUsernameInvalid:{message:' Uh oh! All usernames must be between 1-20 characters, and only include "-" and alphanumeric symbols',description:"Error message displayed when the username entered contains symbols that are not allowed."},webmakerAuthMailingList:{message:"Send me email updates about and other projects",description:"Message about opting in for a Mozilla mailing list"},webmakerAuthAgreeToTerms:{message:"I agree to Terms and Privacy Policy",description:"I agree to terms and privacy policy."},webmakerAuthAgreeError:{message:' Oh snap! You must agree to our terms and conditions.',description:"Error message displayed if the terms and conditions checkbox isn't toggled on."},webmakerAuthCreateAccount:{message:"Create Account",description:"The button text for finishing the join process."},Back:{message:"Back",description:"Back text"},Cancel:{message:"Cancel",description:"Cancel button text"},Email:{message:"Enter Your Email",description:"Label text for the email input"},EmailOrUsername:{message:"Username (your email)",description:"Label text for the sign in input, asks for the email of the user's account."},NotAnEmail:{message:' Uh Oh! That doesn\'t look like an email address.',description:"Error message when the text entered in an email input is not an email address"},WebmakerAccountExists:{message:' Heads up! That email already has an account. Did you mean to sign in?',description:"That email already has an accout. Did you mean to sign in?"},ChooseUsername:{message:"Choose Username",description:" Label text for selecting a username"},"Language Preference":{message:"Language Preference",description:"Label text for selecting the preferred language for the user."},"Sign in to Webmaker":{message:"Sign In",description:"Header text for the sign in modal dialog"},"Sign in to VideoRemix":{message:"Sign In",description:"Header text for the sign in modal dialog"},"Sign in":{message:"Sign In",description:"Sign in Button text"},"Sign up":{message:"Join",description:"Join button text"},passLoginFailed:{message:' Authentication failed!',description:"Error message when a password login attempt fails"},resetMessage:{message:"Check your email for a password reset link.",description:"Directs the user to check their email for a password reset link"},resetRequestFailed:{message:' Uh oh! Something went wrong! Try requesting the password reset again. Or, get help.',description:"Error displayed if a password reset request fails."},Password:{message:"Password",description:"Label text for the password input"},"Forgot your password?":{message:"Forgot your password?",description:"button text for the password reset function"},"Reset your password?":{message:"Reset your password?",description:"link text for the password reset function"},"Click to Reset your password":{message:"Click to Reset your password",description:"Link text for the password reset function"},checkEmail:{message:"Check Your Email",description:"Message instructing the user to check their email"},tokenMessage:{message:"Please check your email to confirm your account.",description:"Message instructing the user to check their email for an account confirmation link"},"That does not look like an email address or username":{message:' Uh oh! That doesn\'t look like an email address or username.',description:"Error message displayed when the input doesn't match a username or email"},"No account found for your uid":{message:' We couldn\'t find your email address. Did you mean to create an account? Trouble? Get help.',description:"Error message displayed when the given username or email doesn't have an account and asks if they would like to sign up."},"problem sending token":{message:' There was a problem sending a login key to you, please try again. Get help.',description:"Error message displayed when the request for a login key fails for some reason."},incorrectToken:{message:' Uh oh! That key is not correct.',description:"Error message displayed when the token used to log in is rejected."},"Visit Email":{message:"Visit your email to retrieve your key",description:"Label text above the login key input field"},"Verified Visit Email":{message:"We emailed you a link & key to sign in",description:"Message instructing the user to check their email for an account confirmation link"},"Enter key":{message:'Enter key ',description:"Label to enter key that was sent to user's email"},"you can switch to webmaker login":{message:"You can switch back to our VideoRemix Login experience. We will send you login emails so you do not need a password.",description:"Message reminding users that they can switch back to the Login Key system instead of using a password."},Submit:{message:"Submit",description:"Label text for the submit new password button in the Reset Password Modal Dialog"},or:{message:"or",description:"Text beside the button that initiates a persona login"},"log in with Persona":{message:"log in with Persona",description:"Text for the button that initiates a persona login"},"trouble with email":{message:'Trouble with email? Check your spam or get help',description:"Text that allows users to get help"},aboutWebmaker:{message:"Make your own web pages, interactive videos, remixes and mobile apps.",description:"Short description"},"XRay-Goggles":{message:"X-Ray Goggles",description:"The X-Ray Goggles Tool"},AboutGoggles:{message:"X-Ray Goggles allow you to see and change the building blocks that make up websites on the Internet. Activate the goggles to play with the code behind any webpage.",description:"A short description of the X-Ray Goggles"},TryGoggles:{message:"Try Goggles now",description:"Text for the button that takes the user to the X-Ray Goggles homepage"},ExploreWebmaker:{message:"Explore the rest",description:"Text for the button which takes the user to explore"},Resources:{message:"Resources",description:"The Resources section"},AboutResources:{message:"Teach and learn digital skills and web literacy. Resources are full of fun things to discover, make and teach.",description:"A short description about the Resources section"},VisitResources:{message:"Visit Resources",description:"Text for the button that takes the user to the X-Ray Goggles homepage"},"passwords do not match":{message:' Uh oh! The passwords do not match!',description:"Error message displayed when the password input and password confirmation input do not match"},"error setting password":{message:' Uh oh! There was an error trying to set your password, please try again.',description:"Error displayed if there was a problem setting the new password"},"Confirm your password":{message:"Confirm Your Password",description:"Label text for the password confirmation input"},"Reset Password":{message:"Click to Reset Password",description:"Reset Password Modal title"},"Set a Password":{message:"Set A Password",description:"Label text for the password input box (reset password modal)"},"Password Reset Success":{message:' Success! You\'ve successfully reset your password, please sign in!',description:"Alert displayed after successfully resetting a password"},"Password too weak":{message:" Uh oh! The password you've entered is too weak. Make sure it doesn't contain any common words or patterns, and doesn't contain your email or username",description:"Error message displayed if the server determined the password entered is too weak."},"Minimum password requirements":{message:"Minimum password requirements",description:"Text above the list of minimum requirements that a password must satisfy"},"At least 8 characters":{message:"At least 8 characters",description:"A password must contain 8 or more characters"},"At least 1 upper and lower case character":{message:"At least 1 uppercase and lowercase character",description:"A password must contain at least 1 upper and lower case character"},"At least 1 number":{message:"At least 1 number",description:"a password must contain at least one number character"},resetRequestFailed:{message:' Uh oh! There was a problem processing your request, Please enter your Email & try again.',description:"Error message displayed if the reset request fails for some reason"},Next:{message:"Next",description:"Go to the next screen"},Cancel:{message:"Cancel",description:"Cancel sign up or sign in"},Done:{message:"Done",description:"Done, close the window."},"Remember me for one year":{message:"Remember me",description:"Message displayed next to the remember me checkbox"},"Lets Go!":{message:"Let's Go!",description:"Button text for closing the modal dialog after account creation"},"Expired Login Link":{message:"Uh Oh! Your login link expired. Request a new email to sign in.",description:"Error message displayed if a login link is expired"},"Contact Support":{message:"Contact Support",description:"Digital Zendesk Link"}}},{}],2:[function(require,module,exports){"use strict";function compile(src){var cached;if("string"!=typeof src)throw new TypeError("src must be a string, instead saw '"+typeof src+"'");return compile.cache?(cached=compile.cache[src],cached||(cached=compile.cache[src]=parser.parse(src)),cached):parser.parse(src)}function getFilter(name){return filters[name]}var parse=require("./parse.js"),filters={},Lexer=parse.Lexer,Parser=parse.Parser,lexer=new Lexer({}),parser=new Parser(lexer,getFilter);compile.cache={},exports.Lexer=Lexer,exports.Parser=Parser,exports.compile=compile,exports.filters=filters},{"./parse.js":3}],3:[function(require,module,exports){"use strict";function noop(){}function extend(dst,obj){var key;for(key in obj)obj.hasOwnProperty(key)&&(dst[key]=obj[key]);return dst}function isDefined(value){return"undefined"!=typeof value}function valueFn(value){return function(){return value}}function $parseMinErr(module,message,arg1,arg2,arg3){var args=arguments;throw message=message.replace(/{(\d)}/g,function(match){return args[2+parseInt(match[1])]}),new SyntaxError(message)}function lowercase(string){return"string"==typeof string?string.toLowerCase():string}function forEach(arr,iterator){arr.forEach(iterator)}function ensureSafeMemberName(name,fullExpression){if("constructor"===name)throw $parseMinErr("isecfld",'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',fullExpression);return name}function ensureSafeObject(obj,fullExpression){if(obj){if(obj.constructor===obj)throw $parseMinErr("isecfn","Referencing Function in Angular expressions is disallowed! Expression: {0}",fullExpression);if(obj.document&&obj.location&&obj.alert&&obj.setInterval)throw $parseMinErr("isecwindow","Referencing the Window in Angular expressions is disallowed! Expression: {0}",fullExpression);if(obj.children&&(obj.nodeName||obj.prop&&obj.attr&&obj.find))throw $parseMinErr("isecdom","Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}",fullExpression)}return obj}function setter(obj,path,setValue,fullExp){for(var key,element=path.split("."),i=0;element.length>1;i++){key=ensureSafeMemberName(element.shift(),fullExp);var propertyObj=obj[key];propertyObj||(propertyObj={},obj[key]=propertyObj),obj=propertyObj}return key=ensureSafeMemberName(element.shift(),fullExp),obj[key]=setValue,setValue}function cspSafeGetterFn(key0,key1,key2,key3,key4,fullExp){return ensureSafeMemberName(key0,fullExp),ensureSafeMemberName(key1,fullExp),ensureSafeMemberName(key2,fullExp),ensureSafeMemberName(key3,fullExp),ensureSafeMemberName(key4,fullExp),function(scope,locals){var pathVal=locals&&locals.hasOwnProperty(key0)?locals:scope;if(null==pathVal)return pathVal;if(pathVal=pathVal[key0],!key1)return pathVal;if(null!=pathVal){if(pathVal=pathVal[key1],!key2)return pathVal;if(null!=pathVal){if(pathVal=pathVal[key2],!key3)return pathVal;if(null!=pathVal){if(pathVal=pathVal[key3],!key4)return pathVal;if(null!=pathVal)return pathVal=pathVal[key4]}}}}}function simpleGetterFn1(key0,fullExp){return ensureSafeMemberName(key0,fullExp),function(scope,locals){return null!=scope?(locals&&locals.hasOwnProperty(key0)?locals:scope)[key0]:void 0}}function simpleGetterFn2(key0,key1,fullExp){return ensureSafeMemberName(key0,fullExp),ensureSafeMemberName(key1,fullExp),function(scope,locals){return null!=scope?(scope=(locals&&locals.hasOwnProperty(key0)?locals:scope)[key0],null==scope?void 0:scope[key1]):void 0}}function getterFn(path,options,fullExp){if(getterFnCache.hasOwnProperty(path))return getterFnCache[path];var fn,pathKeys=path.split("."),pathKeysLength=pathKeys.length;if(1===pathKeysLength)fn=simpleGetterFn1(pathKeys[0],fullExp);else if(2===pathKeysLength)fn=simpleGetterFn2(pathKeys[0],pathKeys[1],fullExp);else if(options.csp)fn=6>pathKeysLength?cspSafeGetterFn(pathKeys[0],pathKeys[1],pathKeys[2],pathKeys[3],pathKeys[4],fullExp,options):function(scope,locals){var val,i=0;do val=cspSafeGetterFn(pathKeys[i++],pathKeys[i++],pathKeys[i++],pathKeys[i++],pathKeys[i++],fullExp,options)(scope,locals),locals=void 0,scope=val;while(pathKeysLength>i);return val};else{var code="var p;\n";forEach(pathKeys,function(key,index){ensureSafeMemberName(key,fullExp),code+="if(s == null) return undefined;\ns="+(index?"s":'((k&&k.hasOwnProperty("'+key+'"))?k:s)')+'["'+key+'"];\n'}),code+="return s;";var evaledFnGetter=new Function("s","k","pw",code);evaledFnGetter.toString=valueFn(code),fn=evaledFnGetter}return"hasOwnProperty"!==path&&(getterFnCache[path]=fn),fn}var OPERATORS={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:noop,"+":function(self,locals,a,b){return a=a(self,locals),b=b(self,locals),isDefined(a)?isDefined(b)?a+b:a:isDefined(b)?b:void 0},"-":function(self,locals,a,b){return a=a(self,locals),b=b(self,locals),(isDefined(a)?a:0)-(isDefined(b)?b:0)},"*":function(self,locals,a,b){return a(self,locals)*b(self,locals)},"/":function(self,locals,a,b){return a(self,locals)/b(self,locals)},"%":function(self,locals,a,b){return a(self,locals)%b(self,locals)},"^":function(self,locals,a,b){return a(self,locals)^b(self,locals)},"=":noop,"===":function(self,locals,a,b){return a(self,locals)===b(self,locals)},"!==":function(self,locals,a,b){return a(self,locals)!==b(self,locals)},"==":function(self,locals,a,b){return a(self,locals)==b(self,locals)},"!=":function(self,locals,a,b){return a(self,locals)!=b(self,locals)},"<":function(self,locals,a,b){return a(self,locals)":function(self,locals,a,b){return a(self,locals)>b(self,locals)},"<=":function(self,locals,a,b){return a(self,locals)<=b(self,locals)},">=":function(self,locals,a,b){return a(self,locals)>=b(self,locals)},"&&":function(self,locals,a,b){return a(self,locals)&&b(self,locals)},"||":function(self,locals,a,b){return a(self,locals)||b(self,locals)},"&":function(self,locals,a,b){return a(self,locals)&b(self,locals)},"|":function(self,locals,a,b){return b(self,locals)(self,locals,a(self,locals))},"!":function(self,locals,a){return!a(self,locals)}},ESCAPE={n:"\n",f:"\f",r:"\r",t:" ",v:"\x0B","'":"'",'"':'"'},Lexer=function(options){this.options=options};Lexer.prototype={constructor:Lexer,lex:function(text){this.text=text,this.index=0,this.ch=void 0,this.lastCh=":",this.tokens=[];for(var token,json=[];this.index="0"&&"9">=ch},isWhitespace:function(ch){return" "===ch||"\r"===ch||" "===ch||"\n"===ch||"\x0B"===ch||" "===ch},isIdent:function(ch){return ch>="a"&&"z">=ch||ch>="A"&&"Z">=ch||"_"===ch||"$"===ch},isExpOperator:function(ch){return"-"===ch||"+"===ch||this.isNumber(ch)},throwError:function(error,start,end){end=end||this.index;var colStr=isDefined(start)?"s "+start+"-"+this.index+" ["+this.text.substring(start,end)+"]":" "+end;throw $parseMinErr("lexerr","Lexer Error: {0} at column{1} in expression [{2}].",error,colStr,this.text)},readNumber:function(){for(var number="",start=this.index;this.index0){var token=this.tokens[0],t=token.text;if(t===e1||t===e2||t===e3||t===e4||!e1&&!e2&&!e3&&!e4)return token}return!1},expect:function(e1,e2,e3,e4){var token=this.peek(e1,e2,e3,e4);return token?(this.tokens.shift(),token):!1},consume:function(e1){this.expect(e1)||this.throwError("is unexpected, expecting ["+e1+"]",this.peek())},unaryFn:function(fn,right){return extend(function(self,locals){return fn(self,locals,right)},{constant:right.constant})},ternaryFn:function(left,middle,right){return extend(function(self,locals){return left(self,locals)?middle(self,locals):right(self,locals)},{constant:left.constant&&middle.constant&&right.constant})},binaryFn:function(left,fn,right){return extend(function(self,locals){return fn(self,locals,left,right)},{constant:left.constant&&right.constant})},statements:function(){for(var statements=[];;)if(this.tokens.length>0&&!this.peek("}",")",";","]")&&statements.push(this.filterChain()),!this.expect(";"))return 1===statements.length?statements[0]:function(self,locals){for(var value,i=0;i","<=",">="))&&(left=this.binaryFn(left,token.fn,this.relational())),left},additive:function(){for(var token,left=this.multiplicative();token=this.expect("+","-");)left=this.binaryFn(left,token.fn,this.multiplicative());return left},multiplicative:function(){for(var token,left=this.unary();token=this.expect("*","/","%");)left=this.binaryFn(left,token.fn,this.unary());return left},unary:function(){var token;return this.expect("+")?this.primary():(token=this.expect("-"))?this.binaryFn(Parser.ZERO,token.fn,this.unary()):(token=this.expect("!"))?this.unaryFn(token.fn,this.unary()):this.primary()},fieldAccess:function(object){var parser=this,field=this.expect().text,getter=getterFn(field,this.options,this.text);return extend(function(scope,locals,self){return getter(self||object(scope,locals))},{assign:function(scope,value,locals){return setter(object(scope,locals),field,value,parser.text,parser.options)}})},objectIndex:function(obj){var parser=this,indexFn=this.expression();return this.consume("]"),extend(function(self,locals){var v,o=obj(self,locals),i=indexFn(self,locals);if(o)return v=ensureSafeObject(o[i],parser.text)},{assign:function(self,value,locals){var key=indexFn(self,locals),safe=ensureSafeObject(obj(self,locals),parser.text);return safe[key]=value}})},functionCall:function(fn,contextGetter){var argsFn=[];if(")"!==this.peekToken().text)do argsFn.push(this.expression());while(this.expect(","));this.consume(")");var parser=this;return function(scope,locals){for(var args=[],context=contextGetter?contextGetter(scope,locals):scope,i=0;i>18&63,h2=bits>>12&63,h3=bits>>6&63,h4=63&bits,tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4);while(i299)&&body.error){er=new Error("CouchDB error: "+(body.error.reason||body.error.error));for(var key in body)er[key]=body[key];return callback(er,resp,body)}return callback(er,resp,body)}"string"==typeof options&&(options={uri:options}),options.json=!0,options.body&&(options.json=options.body),delete options.body,callback=callback||noop;var xhr=request(options,couch_handler);return xhr},module.exports=request},{}],5:[function(require,module,exports){!function(){var cookiejs={serialize:function(name,val,opt){opt=opt||{};var enc=opt.encode||encode,pairs=[name+"="+enc(val)];if(null!=opt.maxAge){var maxAge=opt.maxAge-0;if(isNaN(maxAge))throw new Error("maxAge should be a Number");pairs.push("Max-Age="+maxAge)}return opt.domain&&pairs.push("Domain="+opt.domain),opt.path&&pairs.push("Path="+opt.path),opt.expires&&pairs.push("Expires="+opt.expires.toUTCString()),opt.httpOnly&&pairs.push("HttpOnly"),opt.secure&&pairs.push("Secure"),pairs.join("; ")},parse:function(str,opt){opt=opt||{};var obj={},pairs=str.split(/; */),dec=opt.decode||decode;return pairs.forEach(function(pair){var eq_idx=pair.indexOf("=");if(!(0>eq_idx)){var key=pair.substr(0,eq_idx).trim(),val=pair.substr(++eq_idx,pair.length).trim();if('"'==val[0]&&(val=val.slice(1,-1)),void 0==obj[key])try{obj[key]=dec(val)}catch(e){obj[key]=val}}}),obj}},encode=encodeURIComponent,decode=decodeURIComponent;"undefined"!=typeof module&&module.exports?module.exports=cookiejs:"function"==typeof define&&define.amd?define(function(){return cookiejs}):window.cookiejs=cookiejs}()},{}],6:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified "error" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],7:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],8:[function(require,module,exports){function noop(){}var process=module.exports={};process.nextTick=function(){var canSetImmediate="undefined"!=typeof window&&window.setImmediate,canPost="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(canSetImmediate)return function(f){return window.setImmediate(f)};if(canPost){var queue=[];return window.addEventListener("message",function(ev){var source=ev.source;if((source===window||null===source)&&"process-tick"===ev.data&&(ev.stopPropagation(),queue.length>0)){var fn=queue.shift();fn()}},!0),function(fn){queue.push(fn),window.postMessage("process-tick","*")}}return function(fn){setTimeout(fn,0)}}(),process.title="browser",process.browser=!0,process.env={},process.argv=[],process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],9:[function(require,module,exports){(function(global){!function(root){function error(type){throw RangeError(errors[type])}function map(array,fn){for(var length=array.length;length--;)array[length]=fn(array[length]);return array}function mapDomain(string,fn){return map(string.split(regexSeparators),fn).join(".")}function ucs2decode(string){for(var value,extra,output=[],counter=0,length=string.length;length>counter;)value=string.charCodeAt(counter++),value>=55296&&56319>=value&&length>counter?(extra=string.charCodeAt(counter++),56320==(64512&extra)?output.push(((1023&value)<<10)+(1023&extra)+65536):(output.push(value),counter--)):output.push(value);return output}function ucs2encode(array){return map(array,function(value){var output="";return value>65535&&(value-=65536,output+=stringFromCharCode(value>>>10&1023|55296),value=56320|1023&value),output+=stringFromCharCode(value)}).join("")}function basicToDigit(codePoint){return 10>codePoint-48?codePoint-22:26>codePoint-65?codePoint-65:26>codePoint-97?codePoint-97:base}function digitToBasic(digit,flag){return digit+22+75*(26>digit)-((0!=flag)<<5)}function adapt(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);delta>baseMinusTMin*tMax>>1;k+=base)delta=floor(delta/baseMinusTMin);return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var out,basic,j,index,oldi,w,k,digit,t,baseMinusT,output=[],inputLength=input.length,i=0,n=initialN,bias=initialBias;for(basic=input.lastIndexOf(delimiter),0>basic&&(basic=0),j=0;basic>j;++j)input.charCodeAt(j)>=128&&error("not-basic"),output.push(input.charCodeAt(j));for(index=basic>0?basic+1:0;inputLength>index;){for(oldi=i,w=1,k=base;index>=inputLength&&error("invalid-input"),digit=basicToDigit(input.charCodeAt(index++)),(digit>=base||digit>floor((maxInt-i)/w))&&error("overflow"),i+=digit*w,t=bias>=k?tMin:k>=bias+tMax?tMax:k-bias,!(t>digit);k+=base)baseMinusT=base-t,w>floor(maxInt/baseMinusT)&&error("overflow"),w*=baseMinusT;out=output.length+1,bias=adapt(i-oldi,out,0==oldi),floor(i/out)>maxInt-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,inputLength,handledCPCountPlusOne,baseMinusT,qMinusT,output=[];for(input=ucs2decode(input),inputLength=input.length,n=initialN,delta=0,bias=initialBias,j=0;inputLength>j;++j)currentValue=input[j],128>currentValue&&output.push(stringFromCharCode(currentValue));for(handledCPCount=basicLength=output.length,basicLength&&output.push(delimiter);inputLength>handledCPCount;){for(m=maxInt,j=0;inputLength>j;++j)currentValue=input[j],currentValue>=n&&m>currentValue&&(m=currentValue);for(handledCPCountPlusOne=handledCPCount+1,m-n>floor((maxInt-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m,j=0;inputLength>j;++j)if(currentValue=input[j],n>currentValue&&++delta>maxInt&&error("overflow"),currentValue==n){for(q=delta,k=base;t=bias>=k?tMin:k>=bias+tMax?tMax:k-bias,!(t>q);k+=base)qMinusT=q-t,baseMinusT=base-t,output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0))),q=floor(qMinusT/baseMinusT);output.push(stringFromCharCode(digitToBasic(q,0))),bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength),delta=0,++handledCPCount}++delta,++n}return output.join("")}function toUnicode(domain){return mapDomain(domain,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}function toASCII(domain){return mapDomain(domain,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})}var freeExports="object"==typeof exports&&exports,freeModule="object"==typeof module&&module&&module.exports==freeExports&&module,freeGlobal="object"==typeof global&&global;freeGlobal.global!==freeGlobal&&freeGlobal.window!==freeGlobal||(root=freeGlobal);var punycode,key,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^ -~]/,regexSeparators=/\x2E|\u3002|\uFF0E|\uFF61/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;if(punycode={version:"1.2.4",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return punycode});else if(freeExports&&!freeExports.nodeType)if(freeModule)freeModule.exports=punycode;else for(key in punycode)punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);else root.punycode=punycode}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],10:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;maxKeys>0&&len>maxKeys&&(len=maxKeys);for(var i=0;len>i;++i){var kstr,vstr,k,v,x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq);idx>=0?(kstr=x.substr(0,idx),vstr=x.substr(idx+1)):(kstr=x,vstr=""),k=decodeURIComponent(kstr),v=decodeURIComponent(vstr),hasOwnProperty(obj,k)?isArray(obj[k])?obj[k].push(v):obj[k]=[obj[k],v]:obj[k]=v}return obj};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)}},{}],11:[function(require,module,exports){"use strict";function map(xs,f){if(xs.map)return xs.map(f);for(var res=[],i=0;i",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var rest=url;rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);!slashes||proto&&hostlessProtocol[proto]||(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0;ihec)&&(hostEnd=hec)}var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0;ihec)&&(hostEnd=hec)}-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length;l>i;i++){var part=hostparts[i];if(part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;k>j;j++)newpart+=part.charCodeAt(j)>127?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}}if(this.hostname.length>hostnameMaxLen?this.hostname="":this.hostname=this.hostname.toLowerCase(),!ipv6Hostname){for(var domainArray=this.hostname.split("."),newOut=[],i=0;ii;i++){var ae=autoEscape[i],esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1!==qm?(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)):parseQueryString&&(this.search="",this.query={}),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&host!==!1?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):host||(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}var result=new Url;if(Object.keys(this).forEach(function(k){result[k]=this[k]},this),result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol)return Object.keys(relative).forEach(function(k){"protocol"!==k&&(result[k]=relative[k])}),slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result;if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol])return Object.keys(relative).forEach(function(k){result[k]=relative[k]}),result.href=result.format(),result;if(result.protocol=relative.protocol,relative.host||hostlessProtocol[relative.protocol])result.pathname=relative.pathname;else{for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),relPath.length<2&&relPath.unshift(""),result.pathname=relPath.join("/")}if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):!1;authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,isNull(result.pathname)&&isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.search?result.path="/"+result.search:result.path=null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;i>=0;i--)last=srcPath[i],"."==last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");!mustEndAbs||""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0)||srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):!1;authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),isNull(result.pathname)&&isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{punycode:9,querystring:12}],14:[function(require,module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],15:[function(require,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)), +isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;l>i;++i)hasOwnProperty(value,String(i))?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),str.indexOf("\n")>-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];len>i;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(process.noDeprecation===!0)return fn;var warned=!1;return deprecated};var debugEnviron,debugs={};exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":14,_process:8,inherits:7}],16:[function(require,module,exports){!function(){var modules={};!function(){function extend(cls,name,props){var F=function(){};F.prototype=cls.prototype;var prototype=new F,fnTest=/xyz/.test(function(){xyz})?/\bparent\b/:/.*/;props=props||{};for(var k in props){var src=props[k],parent=prototype[k];"function"==typeof parent&&"function"==typeof src&&fnTest.test(src)?prototype[k]=function(src,parent){return function(){var tmp=this.parent;this.parent=parent;var res=src.apply(this,arguments);return this.parent=tmp,res}}(src,parent):prototype[k]=src}prototype.typename=name;var new_cls=function(){prototype.init&&prototype.init.apply(this,arguments)};return new_cls.prototype=prototype,new_cls.prototype.constructor=new_cls,new_cls.extend=function(name,props){return"object"==typeof name&&(props=name,name="anonymous"),extend(new_cls,name,props)},new_cls}modules.object=extend(Object,"Object",{})}(),function(){var ArrayProto=Array.prototype,ObjProto=Object.prototype,escapeMap={"&":"&",'"':""","'":"'","<":"<",">":">"},escapeRegex=/[&"'<>]/g,lookupEscape=function(ch){return escapeMap[ch]},exports=modules.lib={};exports.withPrettyErrors=function(path,withInternals,func){try{return func()}catch(e){if(e.Update||(e=new exports.TemplateError(e)),e.Update(path),!withInternals){var old=e;e=new Error(old.message),e.name=old.name}throw e}},exports.TemplateError=function(message,lineno,colno){var err=this;return message instanceof Error?(err=message,message=message.name+": "+message.message):Error.captureStackTrace&&Error.captureStackTrace(err),err.name="Template render error",err.message=message,err.lineno=lineno,err.colno=colno,err.firstUpdate=!0,err.Update=function(path){var message="("+(path||"unknown path")+")";return this.firstUpdate&&(this.lineno&&this.colno?message+=" [Line "+this.lineno+", Column "+this.colno+"]":this.lineno&&(message+=" [Line "+this.lineno+"]")),message+="\n ",this.firstUpdate&&(message+=" "),this.message=message+(this.message||""),this.firstUpdate=!1,this},err},exports.TemplateError.prototype=Error.prototype,exports.escape=function(val){return val.replace(escapeRegex,lookupEscape)},exports.isFunction=function(obj){return"[object Function]"==ObjProto.toString.call(obj)},exports.isArray=Array.isArray||function(obj){return"[object Array]"==ObjProto.toString.call(obj)},exports.isString=function(obj){return"[object String]"==ObjProto.toString.call(obj)},exports.isObject=function(obj){return"[object Object]"==ObjProto.toString.call(obj)},exports.groupBy=function(obj,val){for(var result={},iterator=exports.isFunction(val)?val:function(obj){return obj[val]},i=0;ii;i++)str+=char_;return str},exports.each=function(obj,func,context){if(null!=obj)if(ArrayProto.each&&obj.each==ArrayProto.each)obj.forEach(func,context);else if(obj.length===+obj.length)for(var i=0,l=obj.length;l>i;i++)func.call(context,obj[i],i,obj)},exports.map=function(obj,func){var results=[];if(null==obj)return results;if(ArrayProto.map&&obj.map===ArrayProto.map)return obj.map(func);for(var i=0;ii?iter(k,obj[k],i,len,next):cb()}var keys=exports.keys(obj),len=keys.length,i=-1;next()},Array.prototype.indexOf||(Array.prototype.indexOf=function(array,searchElement){if(null==array)throw new TypeError;var t=Object(array),len=t.length>>>0;if(0===len)return-1;var n=0;if(arguments.length>2&&(n=Number(arguments[2]),n!=n?n=0:0!=n&&n!=1/0&&n!=-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=len)return-1;for(var k=n>=0?n:Math.max(len-Math.abs(n),0);len>k;k++)if(k in t&&t[k]===searchElement)return k;return-1}),Array.prototype.map||(Array.prototype.map=function(){throw new Error("map is unimplemented for this js engine")}),exports.keys=function(obj){if(Object.prototype.keys)return obj.keys();var keys=[];for(var k in obj)obj.hasOwnProperty(k)&&keys.push(k);return keys}}(),function(){function traverseAndCheck(obj,type,results){obj instanceof type&&results.push(obj),obj instanceof Node&&obj.findAll(type,results)}function printNodes(node,indent){function print(str,indent,inline){for(var lines=str.split("\n"),i=0;i0||!inline))for(var j=0;indent>j;j++)util.print(" ");i===lines.length-1?util.print(lines[i]):util.puts(lines[i])}}if(indent=indent||0,print(node.typename+": ",indent),node instanceof NodeList)print("\n"),lib.each(node.children,function(n){printNodes(n,indent+2)});else if(node instanceof CallExtension)print(node.extName+"."+node.prop),print("\n"),node.args&&printNodes(node.args,indent+2),node.contentArgs&&lib.each(node.contentArgs,function(n){printNodes(n,indent+2)});else{var nodes=null,props=null;if(node.iterFields(function(val,field){val instanceof Node?(nodes=nodes||{},nodes[field]=val):(props=props||{},props[field]=val)}),props?print(util.inspect(props,!0,null)+"\n",null,!0):print("\n"),nodes)for(var k in nodes)printNodes(nodes[k],indent+2)}}var util=modules.util,lib=modules.lib,Object=modules.object,Node=Object.extend("Node",{init:function(lineno,colno){this.lineno=lineno,this.colno=colno;for(var fields=this.fields,i=0,l=fields.length;l>i;i++){var field=fields[i],val=arguments[i+2];void 0===val&&(val=null),this[field]=val}},findAll:function(type,results){if(results=results||[],this instanceof NodeList)for(var children=this.children,i=0,l=children.length;l>i;i++)traverseAndCheck(children[i],type,results);else for(var fields=this.fields,i=0,l=fields.length;l>i;i++)traverseAndCheck(this[fields[i]],type,results);return results},iterFields:function(func){lib.each(this.fields,function(field){func(this[field],field)},this)}}),Value=Node.extend("Value",{fields:["value"]}),NodeList=Node.extend("NodeList",{fields:["children"],init:function(lineno,colno,nodes){this.parent(lineno,colno,nodes||[])},addChild:function(node){this.children.push(node)}}),Root=NodeList.extend("Root"),Literal=Value.extend("Literal"),Symbol=Value.extend("Symbol"),Group=NodeList.extend("Group"),Array=NodeList.extend("Array"),Pair=Node.extend("Pair",{fields:["key","value"]}),Dict=NodeList.extend("Dict"),LookupVal=Node.extend("LookupVal",{fields:["target","val"]}),If=Node.extend("If",{fields:["cond","body","else_"]}),IfAsync=If.extend("IfAsync"),InlineIf=Node.extend("InlineIf",{fields:["cond","body","else_"]}),For=Node.extend("For",{fields:["arr","name","body"]}),AsyncEach=For.extend("AsyncEach"),AsyncAll=For.extend("AsyncAll"),Macro=Node.extend("Macro",{fields:["name","args","body"]}),Import=Node.extend("Import",{fields:["template","target"]}),FromImport=Node.extend("FromImport",{fields:["template","names"],init:function(lineno,colno,template,names){this.parent(lineno,colno,template,names||new NodeList)}}),FunCall=Node.extend("FunCall",{fields:["name","args"]}),Filter=FunCall.extend("Filter"),FilterAsync=Filter.extend("FilterAsync",{fields:["name","args","symbol"]}),KeywordArgs=Dict.extend("KeywordArgs"),Block=Node.extend("Block",{fields:["name","body"]}),Super=Node.extend("Super",{fields:["blockName","symbol"]}),TemplateRef=Node.extend("TemplateRef",{fields:["template"]}),Extends=TemplateRef.extend("Extends"),Include=TemplateRef.extend("Include"),Set=Node.extend("Set",{fields:["targets","value"]}),Output=NodeList.extend("Output"),TemplateData=Literal.extend("TemplateData"),UnaryOp=Node.extend("UnaryOp",{fields:["target"]}),BinOp=Node.extend("BinOp",{fields:["left","right"]}),Or=BinOp.extend("Or"),And=BinOp.extend("And"),Not=UnaryOp.extend("Not"),Add=BinOp.extend("Add"),Sub=BinOp.extend("Sub"),Mul=BinOp.extend("Mul"),Div=BinOp.extend("Div"),FloorDiv=BinOp.extend("FloorDiv"),Mod=BinOp.extend("Mod"),Pow=BinOp.extend("Pow"),Neg=UnaryOp.extend("Neg"),Pos=UnaryOp.extend("Pos"),Compare=Node.extend("Compare",{fields:["expr","ops"]}),CompareOperand=Node.extend("CompareOperand",{fields:["expr","type"]}),CallExtension=(Node.extend("CustomTag",{init:function(lineno,colno,name){this.lineno=lineno,this.colno=colno,this.name=name}}),Node.extend("CallExtension",{fields:["extName","prop","args","contentArgs"],init:function(ext,prop,args,contentArgs){this.extName=ext._name||ext,this.prop=prop,this.args=args||new NodeList,this.contentArgs=contentArgs||[],this.autoescape=ext.autoescape}})),CallExtensionAsync=CallExtension.extend("CallExtensionAsync");modules.nodes={Node:Node,Root:Root,NodeList:NodeList,Value:Value,Literal:Literal,Symbol:Symbol,Group:Group,Array:Array,Pair:Pair,Dict:Dict,Output:Output,TemplateData:TemplateData,If:If,IfAsync:IfAsync,InlineIf:InlineIf,For:For,AsyncEach:AsyncEach,AsyncAll:AsyncAll,Macro:Macro,Import:Import,FromImport:FromImport,FunCall:FunCall,Filter:Filter,FilterAsync:FilterAsync,KeywordArgs:KeywordArgs,Block:Block,Super:Super,Extends:Extends,Include:Include,Set:Set,LookupVal:LookupVal,BinOp:BinOp,Or:Or,And:And,Not:Not,Add:Add,Sub:Sub,Mul:Mul,Div:Div,FloorDiv:FloorDiv,Mod:Mod,Pow:Pow,Neg:Neg,Pos:Pos,Compare:Compare,CompareOperand:CompareOperand,CallExtension:CallExtension,CallExtensionAsync:CallExtensionAsync,printNodes:printNodes}}(),function(){function makeMacro(argNames,kwargNames,func){return function(){var args,argCount=numArgs(arguments),kwargs=getKeywordArgs(arguments);if(argCount>argNames.length){args=Array.prototype.slice.call(arguments,0,argNames.length);for(var vals=Array.prototype.slice.call(arguments,args.length,argCount),i=0;i=","//","**"],curComplex=cur+this.current();switch(-1!==complexOps.indexOf(curComplex)&&(this.forward(),cur=curComplex),cur){case"(":type=TOKEN_LEFT_PAREN;break;case")":type=TOKEN_RIGHT_PAREN;break;case"[":type=TOKEN_LEFT_BRACKET;break;case"]":type=TOKEN_RIGHT_BRACKET;break;case"{":type=TOKEN_LEFT_CURLY;break;case"}":type=TOKEN_RIGHT_CURLY;break;case",":type=TOKEN_COMMA;break;case":":type=TOKEN_COLON;break;case"|":type=TOKEN_PIPE;break;default:type=TOKEN_OPERATOR}return token(type,cur,lineno,colno)}if(tok=this._extractUntil(whitespaceChars+delimChars),tok.match(/^[-+]?[0-9]+$/)){if("."==this.current()){this.forward();var dec=this._extract(intChars);return token(TOKEN_FLOAT,tok+"."+dec,lineno,colno)}return token(TOKEN_INT,tok,lineno,colno)}if(tok.match(/^(true|false)$/))return token(TOKEN_BOOLEAN,tok,lineno,colno);if(tok)return token(TOKEN_SYMBOL,tok,lineno,colno);throw new Error("Unexpected value while parsing: "+tok)}var tok,beginChars=BLOCK_START.charAt(0)+VARIABLE_START.charAt(0)+COMMENT_START.charAt(0)+COMMENT_END.charAt(0);if(this.is_finished())return null;if((tok=this._extractString(BLOCK_START+"-"))||(tok=this._extractString(BLOCK_START)))return this.in_code=!0,token(TOKEN_BLOCK_START,tok,lineno,colno);if(tok=this._extractString(VARIABLE_START))return this.in_code=!0,token(TOKEN_VARIABLE_START,tok,lineno,colno);tok="";var data,in_comment=!1;for(this._matches(COMMENT_START)&&(in_comment=!0,tok=this._extractString(COMMENT_START));null!==(data=this._extractUntil(beginChars))&&(tok+=data,!(this._matches(BLOCK_START)||this._matches(VARIABLE_START)||this._matches(COMMENT_START))||in_comment);){if(this._matches(COMMENT_END)){if(!in_comment)throw new Error("unexpected end of comment");tok+=this._extractString(COMMENT_END);break}tok+=this.current(),this.forward()}if(null===data&&in_comment)throw new Error("expected end of comment, got end of file");return token(in_comment?TOKEN_COMMENT:TOKEN_DATA,tok,lineno,colno)},Tokenizer.prototype.parseString=function(delimiter){this.forward();for(var str=(this.lineno,this.colno,"");!this.is_finished()&&this.current()!=delimiter;){var cur=this.current();if("\\"==cur){switch(this.forward(),this.current()){case"n":str+="\n";break;case"t":str+=" ";break;case"r":str+="\r";break;default:str+=this.current()}this.forward()}else str+=cur,this.forward()}return this.forward(),str},Tokenizer.prototype._matches=function(str){if(this.index+str.length>this.length)return null;var m=this.str.slice(this.index,this.index+str.length);return m==str},Tokenizer.prototype._extractString=function(str){return this._matches(str)?(this.index+=str.length,str):null},Tokenizer.prototype._extractUntil=function(charString){return this._extractMatching(!0,charString||"")},Tokenizer.prototype._extract=function(charString){return this._extractMatching(!1,charString)},Tokenizer.prototype._extractMatching=function(breakOnMatch,charString){if(this.is_finished())return null;var first=charString.indexOf(this.current());if(breakOnMatch&&-1==first||!breakOnMatch&&-1!=first){var t=this.current();this.forward();for(var idx=charString.indexOf(this.current());(breakOnMatch&&-1==idx||!breakOnMatch&&-1!=idx)&&!this.is_finished();)t+=this.current(),this.forward(),idx=charString.indexOf(this.current());return t}return""},Tokenizer.prototype.is_finished=function(){return this.index>=this.len},Tokenizer.prototype.forwardN=function(n){for(var i=0;n>i;i++)this.forward()},Tokenizer.prototype.forward=function(){this.index++,"\n"==this.previous()?(this.lineno++,this.colno=0):this.colno++},Tokenizer.prototype.back=function(){if(this.index--,"\n"==this.current()){this.lineno--;var idx=this.src.lastIndexOf("\n",this.index-1);-1==idx?this.colno=this.index:this.colno=this.index-idx}else this.colno--},Tokenizer.prototype.current=function(){return this.is_finished()?"":this.str.charAt(this.index)},Tokenizer.prototype.previous=function(){return this.str.charAt(this.index-1)},modules.lexer={lex:function(src){return new Tokenizer(src)},setTags:function(tags){BLOCK_START=tags.blockStart||BLOCK_START,BLOCK_END=tags.blockEnd||BLOCK_END,VARIABLE_START=tags.variableStart||VARIABLE_START,VARIABLE_END=tags.variableEnd||VARIABLE_END,COMMENT_START=tags.commentStart||COMMENT_START,COMMENT_END=tags.commentEnd||COMMENT_END},TOKEN_STRING:TOKEN_STRING,TOKEN_WHITESPACE:TOKEN_WHITESPACE,TOKEN_DATA:TOKEN_DATA,TOKEN_BLOCK_START:TOKEN_BLOCK_START,TOKEN_BLOCK_END:TOKEN_BLOCK_END,TOKEN_VARIABLE_START:TOKEN_VARIABLE_START,TOKEN_VARIABLE_END:TOKEN_VARIABLE_END,TOKEN_COMMENT:TOKEN_COMMENT,TOKEN_LEFT_PAREN:TOKEN_LEFT_PAREN,TOKEN_RIGHT_PAREN:TOKEN_RIGHT_PAREN,TOKEN_LEFT_BRACKET:TOKEN_LEFT_BRACKET,TOKEN_RIGHT_BRACKET:TOKEN_RIGHT_BRACKET,TOKEN_LEFT_CURLY:TOKEN_LEFT_CURLY,TOKEN_RIGHT_CURLY:TOKEN_RIGHT_CURLY,TOKEN_OPERATOR:TOKEN_OPERATOR,TOKEN_COMMA:TOKEN_COMMA,TOKEN_COLON:TOKEN_COLON,TOKEN_PIPE:TOKEN_PIPE,TOKEN_INT:TOKEN_INT,TOKEN_FLOAT:TOKEN_FLOAT,TOKEN_BOOLEAN:TOKEN_BOOLEAN,TOKEN_SYMBOL:TOKEN_SYMBOL,TOKEN_SPECIAL:TOKEN_SPECIAL}}(),function(){var lexer=modules.lexer,nodes=modules.nodes,Object=modules.object,lib=modules.lib,Parser=Object.extend({init:function(tokens){this.tokens=tokens,this.peeked=null,this.breakOnBlocks=null,this.dropLeadingWhitespace=!1,this.extensions=[]},nextToken:function(withWhitespace){var tok;if(this.peeked){if(withWhitespace||this.peeked.type!=lexer.TOKEN_WHITESPACE)return tok=this.peeked,this.peeked=null,tok;this.peeked=null}if(tok=this.tokens.nextToken(),!withWhitespace)for(;tok&&tok.type==lexer.TOKEN_WHITESPACE;)tok=this.tokens.nextToken();return tok},peekToken:function(){return this.peeked=this.peeked||this.nextToken(),this.peeked},pushToken:function(tok){if(this.peeked)throw new Error("pushToken: can only push one token on between reads");this.peeked=tok},fail:function(msg,lineno,colno){if((void 0===lineno||void 0===colno)&&this.peekToken()){var tok=this.peekToken();lineno=tok.lineno,colno=tok.colno}throw void 0!==lineno&&(lineno+=1),void 0!==colno&&(colno+=1),new lib.TemplateError(msg,lineno,colno)},skip:function(type){var tok=this.nextToken();return tok&&tok.type==type?!0:(this.pushToken(tok),!1)},expect:function(type){var tok=this.nextToken();return tok.type!==type&&this.fail("expected "+type+", got "+tok.type,tok.lineno,tok.colno),tok},skipValue:function(type,val){var tok=this.nextToken();return tok&&tok.type==type&&tok.value==val?!0:(this.pushToken(tok),!1)},skipWhitespace:function(){return this.skip(lexer.TOKEN_WHITESPACE)},skipSymbol:function(val){return this.skipValue(lexer.TOKEN_SYMBOL,val)},advanceAfterBlockEnd:function(name){if(!name){var tok=this.peekToken();tok||this.fail("unexpected end of file"),tok.type!=lexer.TOKEN_SYMBOL&&this.fail("advanceAfterBlockEnd: expected symbol token or explicit name to be passed"),name=this.nextToken().value}var tok=this.nextToken();tok&&tok.type==lexer.TOKEN_BLOCK_END?"-"===tok.value.charAt(0)&&(this.dropLeadingWhitespace=!0):this.fail("expected block end in "+name+" statement")},advanceAfterVariableEnd:function(){this.skip(lexer.TOKEN_VARIABLE_END)||this.fail("expected variable end")},parseFor:function(){var node,endBlock,forTok=this.peekToken();this.skipSymbol("for")?(node=new nodes.For(forTok.lineno,forTok.colno),endBlock="endfor"):this.skipSymbol("asyncEach")?(node=new nodes.AsyncEach(forTok.lineno,forTok.colno),endBlock="endeach"):this.skipSymbol("asyncAll")?(node=new nodes.AsyncAll(forTok.lineno,forTok.colno),endBlock="endall"):this.fail("parseFor: expected for{Async}",forTok.lineno,forTok.colno),node.name=this.parsePrimary(),node.name instanceof nodes.Symbol||this.fail("parseFor: variable name expected for loop");var type=this.peekToken().type;if(type==lexer.TOKEN_COMMA){var key=node.name;for(node.name=new nodes.Array(key.lineno,key.colno),node.name.addChild(key);this.skip(lexer.TOKEN_COMMA);){var prim=this.parsePrimary();node.name.addChild(prim)}}return this.skipSymbol("in")||this.fail('parseFor: expected "in" keyword for loop',forTok.lineno,forTok.colno),node.arr=this.parseExpression(),this.advanceAfterBlockEnd(forTok.value),node.body=this.parseUntilBlocks(endBlock),this.advanceAfterBlockEnd(),node},parseMacro:function(){var macroTok=this.peekToken();this.skipSymbol("macro")||this.fail("expected macro");var name=this.parsePrimary(!0),args=this.parseSignature(),node=new nodes.Macro(macroTok.lineno,macroTok.colno,name,args);return this.advanceAfterBlockEnd(macroTok.value),node.body=this.parseUntilBlocks("endmacro"), +this.advanceAfterBlockEnd(),node},parseImport:function(){var importTok=this.peekToken();this.skipSymbol("import")||this.fail("parseImport: expected import",importTok.lineno,importTok.colno);var template=this.parseExpression();this.skipSymbol("as")||this.fail('parseImport: expected "as" keyword',importTok.lineno,importTok.colno);var target=this.parsePrimary(),node=new nodes.Import(importTok.lineno,importTok.colno,template,target);return this.advanceAfterBlockEnd(importTok.value),node},parseFrom:function(){var fromTok=this.peekToken();this.skipSymbol("from")||this.fail("parseFrom: expected from");var template=this.parsePrimary(),node=new nodes.FromImport(fromTok.lineno,fromTok.colno,template,new nodes.NodeList);this.skipSymbol("import")||this.fail("parseFrom: expected import",fromTok.lineno,fromTok.colno);for(var names=node.names;;){var nextTok=this.peekToken();if(nextTok.type==lexer.TOKEN_BLOCK_END){names.children.length||this.fail("parseFrom: Expected at least one import name",fromTok.lineno,fromTok.colno),"-"==nextTok.value.charAt(0)&&(this.dropLeadingWhitespace=!0),this.nextToken();break}names.children.length>0&&!this.skip(lexer.TOKEN_COMMA)&&this.fail("parseFrom: expected comma",fromTok.lineno,fromTok.colno);var name=this.parsePrimary();if("_"==name.value.charAt(0)&&this.fail("parseFrom: names starting with an underscore cannot be imported",name.lineno,name.colno),this.skipSymbol("as")){var alias=this.parsePrimary();names.addChild(new nodes.Pair(name.lineno,name.colno,name,alias))}else names.addChild(name)}return node},parseBlock:function(){var tag=this.peekToken();this.skipSymbol("block")||this.fail("parseBlock: expected block",tag.lineno,tag.colno);var node=new nodes.Block(tag.lineno,tag.colno);return node.name=this.parsePrimary(),node.name instanceof nodes.Symbol||this.fail("parseBlock: variable name expected",tag.lineno,tag.colno),this.advanceAfterBlockEnd(tag.value),node.body=this.parseUntilBlocks("endblock"),this.peekToken()||this.fail("parseBlock: expected endblock, got end of file"),this.advanceAfterBlockEnd(),node},parseTemplateRef:function(tagName,nodeType){var tag=this.peekToken();this.skipSymbol(tagName)||this.fail("parseTemplateRef: expected "+tagName);var node=new nodeType(tag.lineno,tag.colno);return node.template=this.parseExpression(),this.advanceAfterBlockEnd(tag.value),node},parseExtends:function(){return this.parseTemplateRef("extends",nodes.Extends)},parseInclude:function(){return this.parseTemplateRef("include",nodes.Include)},parseIf:function(){var node,tag=this.peekToken();this.skipSymbol("if")||this.skipSymbol("elif")?node=new nodes.If(tag.lineno,tag.colno):this.skipSymbol("ifAsync")?node=new nodes.IfAsync(tag.lineno,tag.colno):this.fail("parseIf: expected if or elif",tag.lineno,tag.colno),node.cond=this.parseExpression(),this.advanceAfterBlockEnd(tag.value),node.body=this.parseUntilBlocks("elif","else","endif");var tok=this.peekToken();switch(tok&&tok.value){case"elif":node.else_=this.parseIf();break;case"else":this.advanceAfterBlockEnd(),node.else_=this.parseUntilBlocks("endif"),this.advanceAfterBlockEnd();break;case"endif":node.else_=null,this.advanceAfterBlockEnd();break;default:this.fail("parseIf: expected endif, else, or endif, got end of file")}return node},parseSet:function(){var tag=this.peekToken();this.skipSymbol("set")||this.fail("parseSet: expected set",tag.lineno,tag.colno);for(var target,node=new nodes.Set(tag.lineno,tag.colno,[]);(target=this.parsePrimary())&&(node.targets.push(target),this.skip(lexer.TOKEN_COMMA)););return this.skipValue(lexer.TOKEN_OPERATOR,"=")||this.fail("parseSet: expected = in set tag",tag.lineno,tag.colno),node.value=this.parseExpression(),this.advanceAfterBlockEnd(tag.value),node},parseStatement:function(){var node,tok=this.peekToken();if(tok.type!=lexer.TOKEN_SYMBOL&&this.fail("tag name expected",tok.lineno,tok.colno),this.breakOnBlocks&&-1!==this.breakOnBlocks.indexOf(tok.value))return null;switch(tok.value){case"raw":return this.parseRaw();case"if":case"ifAsync":return this.parseIf();case"for":case"asyncEach":case"asyncAll":return this.parseFor();case"block":return this.parseBlock();case"extends":return this.parseExtends();case"include":return this.parseInclude();case"set":return this.parseSet();case"macro":return this.parseMacro();case"import":return this.parseImport();case"from":return this.parseFrom();default:if(this.extensions.length)for(var i=0;i1&&this.fail("invalid index"),node=new nodes.LookupVal(tok.lineno,tok.colno,node,lookup.children[0])}else{if(tok.type!=lexer.TOKEN_OPERATOR||"."!=tok.value)break;this.nextToken();var val=this.nextToken();val.type!=lexer.TOKEN_SYMBOL&&this.fail("expected name as lookup value, got "+val.value,val.lineno,val.colno);var lookup=new nodes.Literal(val.lineno,val.colno,val.value);node=new nodes.LookupVal(tok.lineno,tok.colno,node,lookup)}tok=this.peekToken()}return node},parseExpression:function(){var node=this.parseInlineIf();return node},parseInlineIf:function(){var node=this.parseOr();if(this.skipSymbol("if")){var cond_node=this.parseOr(),body_node=node;node=new nodes.InlineIf(node.lineno,node.colno),node.body=body_node,node.cond=cond_node,this.skipSymbol("else")?node.else_=this.parseOr():node.else_=null}return node},parseOr:function(){for(var node=this.parseAnd();this.skipSymbol("or");){var node2=this.parseAnd();node=new nodes.Or(node.lineno,node.colno,node,node2)}return node},parseAnd:function(){for(var node=this.parseNot();this.skipSymbol("and");){var node2=this.parseNot();node=new nodes.And(node.lineno,node.colno,node,node2)}return node},parseNot:function(){var tok=this.peekToken();return this.skipSymbol("not")?new nodes.Not(tok.lineno,tok.colno,this.parseNot()):this.parseCompare()},parseCompare:function(){for(var compareOps=["==","!=","<",">","<=",">="],expr=this.parseAdd(),ops=[];;){var tok=this.nextToken();if(!tok)break;if(-1!==compareOps.indexOf(tok.value))ops.push(new nodes.CompareOperand(tok.lineno,tok.colno,this.parseAdd(),tok.value));else if(tok.type==lexer.TOKEN_SYMBOL&&"in"==tok.value)ops.push(new nodes.CompareOperand(tok.lineno,tok.colno,this.parseAdd(),"in"));else{if(tok.type!=lexer.TOKEN_SYMBOL||"not"!=tok.value||!this.skipSymbol("in")){this.pushToken(tok);break}ops.push(new nodes.CompareOperand(tok.lineno,tok.colno,this.parseAdd(),"notin"))}}return ops.length?new nodes.Compare(ops[0].lineno,ops[0].colno,expr,ops):expr},parseAdd:function(){for(var node=this.parseSub();this.skipValue(lexer.TOKEN_OPERATOR,"+");){var node2=this.parseSub();node=new nodes.Add(node.lineno,node.colno,node,node2)}return node},parseSub:function(){for(var node=this.parseMul();this.skipValue(lexer.TOKEN_OPERATOR,"-");){var node2=this.parseMul();node=new nodes.Sub(node.lineno,node.colno,node,node2)}return node},parseMul:function(){for(var node=this.parseDiv();this.skipValue(lexer.TOKEN_OPERATOR,"*");){var node2=this.parseDiv();node=new nodes.Mul(node.lineno,node.colno,node,node2)}return node},parseDiv:function(){for(var node=this.parseFloorDiv();this.skipValue(lexer.TOKEN_OPERATOR,"/");){var node2=this.parseFloorDiv();node=new nodes.Div(node.lineno,node.colno,node,node2)}return node},parseFloorDiv:function(){for(var node=this.parseMod();this.skipValue(lexer.TOKEN_OPERATOR,"//");){var node2=this.parseMod();node=new nodes.FloorDiv(node.lineno,node.colno,node,node2)}return node},parseMod:function(){for(var node=this.parsePow();this.skipValue(lexer.TOKEN_OPERATOR,"%");){var node2=this.parsePow();node=new nodes.Mod(node.lineno,node.colno,node,node2)}return node},parsePow:function(){for(var node=this.parseUnary();this.skipValue(lexer.TOKEN_OPERATOR,"**");){var node2=this.parseUnary();node=new nodes.Pow(node.lineno,node.colno,node,node2)}return node},parseUnary:function(noFilters){var node,tok=this.peekToken();return node=this.skipValue(lexer.TOKEN_OPERATOR,"-")?new nodes.Neg(tok.lineno,tok.colno,this.parseUnary(!0)):this.skipValue(lexer.TOKEN_OPERATOR,"+")?new nodes.Pos(tok.lineno,tok.colno,this.parseUnary(!0)):this.parsePrimary(),noFilters||(node=this.parseFilter(node)),node},parsePrimary:function(noPostfix){var tok=this.nextToken(),val=null,node=null;return tok?tok.type==lexer.TOKEN_STRING?val=tok.value:tok.type==lexer.TOKEN_INT?val=parseInt(tok.value,10):tok.type==lexer.TOKEN_FLOAT?val=parseFloat(tok.value):tok.type==lexer.TOKEN_BOOLEAN&&("true"==tok.value?val=!0:"false"==tok.value?val=!1:this.fail("invalid boolean: "+tok.val,tok.lineno,tok.colno)):this.fail("expected expression, got end of file"),null!==val?node=new nodes.Literal(tok.lineno,tok.colno,val):tok.type==lexer.TOKEN_SYMBOL?(node=new nodes.Symbol(tok.lineno,tok.colno,tok.value),noPostfix||(node=this.parsePostfix(node))):(this.pushToken(tok),node=this.parseAggregate()),node?node:void this.fail("unexpected token: "+tok.value,tok.lineno,tok.colno)},parseFilter:function(node){for(;this.skip(lexer.TOKEN_PIPE);){for(var tok=this.expect(lexer.TOKEN_SYMBOL),name=tok.value;this.skipValue(lexer.TOKEN_OPERATOR,".");)name+="."+this.expect(lexer.TOKEN_SYMBOL).value;if(node=new nodes.Filter(tok.lineno,tok.colno,new nodes.Symbol(tok.lineno,tok.colno,name),new nodes.NodeList(tok.lineno,tok.colno,[node])),this.peekToken().type==lexer.TOKEN_LEFT_PAREN){var call=this.parsePostfix(node);node.args.children=node.args.children.concat(call.args.children)}}return node},parseAggregate:function(){var node,tok=this.nextToken();switch(tok.type){case lexer.TOKEN_LEFT_PAREN:node=new nodes.Group(tok.lineno,tok.colno);break;case lexer.TOKEN_LEFT_BRACKET:node=new nodes.Array(tok.lineno,tok.colno);break;case lexer.TOKEN_LEFT_CURLY:node=new nodes.Dict(tok.lineno,tok.colno);break;default:return null}for(;;){var type=this.peekToken().type;if(type==lexer.TOKEN_RIGHT_PAREN||type==lexer.TOKEN_RIGHT_BRACKET||type==lexer.TOKEN_RIGHT_CURLY){this.nextToken();break}if(node.children.length>0&&(this.skip(lexer.TOKEN_COMMA)||this.fail("parseAggregate: expected comma after expression",tok.lineno,tok.colno)),node instanceof nodes.Dict){var key=this.parsePrimary();this.skip(lexer.TOKEN_COLON)||this.fail("parseAggregate: expected colon after dict key",tok.lineno,tok.colno);var value=this.parseExpression();node.addChild(new nodes.Pair(key.lineno,key.colno,key,value))}else{var expr=this.parseExpression();node.addChild(expr)}}return node},parseSignature:function(tolerant,noParens){var tok=this.peekToken();if(!noParens&&tok.type!=lexer.TOKEN_LEFT_PAREN){if(tolerant)return null;this.fail("expected arguments",tok.lineno,tok.colno)}tok.type==lexer.TOKEN_LEFT_PAREN&&(tok=this.nextToken());for(var args=new nodes.NodeList(tok.lineno,tok.colno),kwargs=new nodes.KeywordArgs(tok.lineno,tok.colno),checkComma=!1;;){if(tok=this.peekToken(),!noParens&&tok.type==lexer.TOKEN_RIGHT_PAREN){this.nextToken();break}if(noParens&&tok.type==lexer.TOKEN_BLOCK_END)break;if(checkComma&&!this.skip(lexer.TOKEN_COMMA))this.fail("parseSignature: expected comma after expression",tok.lineno,tok.colno);else{var arg=this.parseExpression();this.skipValue(lexer.TOKEN_OPERATOR,"=")?kwargs.addChild(new nodes.Pair(arg.lineno,arg.colno,arg,this.parseExpression())):args.addChild(arg)}checkComma=!0}return kwargs.children.length&&args.addChild(kwargs),args},parseUntilBlocks:function(){var prev=this.breakOnBlocks;this.breakOnBlocks=lib.toArray(arguments);var ret=this.parse();return this.breakOnBlocks=prev,ret},parseNodes:function(){for(var tok,buf=[];tok=this.nextToken();)if(tok.type==lexer.TOKEN_DATA){var data=tok.value,nextToken=this.peekToken(),nextVal=nextToken&&nextToken.value;this.dropLeadingWhitespace&&(data=data.replace(/^\s*/,""),this.dropLeadingWhitespace=!1),nextToken&&nextToken.type==lexer.TOKEN_BLOCK_START&&"-"==nextVal.charAt(nextVal.length-1)&&(data=data.replace(/\s*$/,"")),buf.push(new nodes.Output(tok.lineno,tok.colno,[new nodes.TemplateData(tok.lineno,tok.colno,data)]))}else if(tok.type==lexer.TOKEN_BLOCK_START){var n=this.parseStatement();if(!n)break;buf.push(n)}else if(tok.type==lexer.TOKEN_VARIABLE_START){var e=this.parseExpression();this.advanceAfterVariableEnd(),buf.push(new nodes.Output(tok.lineno,tok.colno,[e]))}else tok.type!=lexer.TOKEN_COMMENT&&this.fail("Unexpected token at top-level: "+tok.type,tok.lineno,tok.colno);return buf},parse:function(){return new nodes.NodeList(0,0,this.parseNodes())},parseAsRoot:function(){return new nodes.Root(0,0,this.parseNodes())}});modules.parser={parse:function(src,extensions){var p=new Parser(lexer.lex(src));return void 0!==extensions&&(p.extensions=extensions),p.parseAsRoot()}}}(),function(){function gensym(){return"hole_"+sym++}function mapCOW(arr,func){for(var res=null,i=0;i":">","<=":"<=",">=":">="},Compiler=Object.extend({init:function(){this.codebuf=[],this.lastId=0,this.buffer=null,this.bufferStack=[],this.isChild=!1,this.scopeClosers=""},fail:function(msg,lineno,colno){throw void 0!==lineno&&(lineno+=1),void 0!==colno&&(colno+=1),new lib.TemplateError(msg,lineno,colno)},pushBufferId:function(id){this.bufferStack.push(this.buffer),this.buffer=id,this.emit("var "+this.buffer+' = "";')},popBufferId:function(){this.buffer=this.bufferStack.pop()},emit:function(code){this.codebuf.push(code)},emitLine:function(code){this.emit(code+"\n")},emitLines:function(){lib.each(lib.toArray(arguments),function(line){this.emitLine(line)},this)},emitFuncBegin:function(name){this.buffer="output",this.scopeClosers="",this.emitLine("function "+name+"(env, context, frame, runtime, cb) {"),this.emitLine("var lineno = null;"),this.emitLine("var colno = null;"),this.emitLine("var "+this.buffer+' = "";'),this.emitLine("try {")},emitFuncEnd:function(noReturn){noReturn||this.emitLine("cb(null, "+this.buffer+");"),this.closeScopeLevels(),this.emitLine("} catch (e) {"),this.emitLine(" cb(runtime.handleError(e, lineno, colno));"),this.emitLine("}"),this.emitLine("}"),this.buffer=null},addScopeLevel:function(){this.scopeClosers+="})"},closeScopeLevels:function(){this.emitLine(this.scopeClosers+";"),this.scopeClosers=""},withScopedSyntax:function(func){var scopeClosers=this.scopeClosers;this.scopeClosers="",func.call(this),this.closeScopeLevels(),this.scopeClosers=scopeClosers},makeCallback:function(res){var err=this.tmpid();return"function("+err+(res?","+res:"")+") {\nif("+err+") { cb("+err+"); return; }"},tmpid:function(){return this.lastId++,"t_"+this.lastId},_bufferAppend:function(func){this.emit(this.buffer+" += runtime.suppressValue("),func.call(this),this.emit(", env.autoesc);\n")},_compileChildren:function(node,frame){for(var children=node.children,i=0,l=children.length;l>i;i++)this.compile(children[i],frame)},_compileAggregate:function(node,frame,startChar,endChar){startChar&&this.emit(startChar);for(var i=0;i0&&this.emit(","),this.compile(node.children[i],frame);endChar&&this.emit(endChar)},_compileExpression:function(node,frame){this.assertType(node,nodes.Literal,nodes.Symbol,nodes.Group,nodes.Array,nodes.Dict,nodes.FunCall,nodes.Filter,nodes.LookupVal,nodes.Compare,nodes.InlineIf,nodes.And,nodes.Or,nodes.Not,nodes.Add,nodes.Sub,nodes.Mul,nodes.Div,nodes.FloorDiv,nodes.Mod,nodes.Pow,nodes.Neg,nodes.Pos,nodes.Compare,nodes.NodeList),this.compile(node,frame)},assertType:function(node){for(var types=lib.toArray(arguments).slice(1),success=!1,i=0;i0&&this.emit(","),arg){var id=this.tmpid();this.emitLine("function(cb) {"),this.emitLine("if(!cb) { cb = function(err) { if(err) { throw err; }}}"),this.pushBufferId(id),this.withScopedSyntax(function(){this.compile(arg,frame),this.emitLine("cb(null, "+id+");")}),this.popBufferId(),this.emitLine("return "+id+";"),this.emitLine("}")}else this.emit("null")},this),async){var res=this.tmpid();this.emitLine(", "+this.makeCallback(res)),this.emitLine(this.buffer+" += runtime.suppressValue("+res+", "+autoescape+" && env.autoesc);"),this.addScopeLevel()}else this.emit(")"),this.emit(", "+autoescape+" && env.autoesc);\n")},compileCallExtensionAsync:function(node,frame){this.compileCallExtension(node,frame,!0)},compileNodeList:function(node,frame){this._compileChildren(node,frame)},compileLiteral:function(node,frame){if("string"==typeof node.value){var val=node.value.replace(/\\/g,"\\\\");val=val.replace(/"/g,'\\"'),val=val.replace(/\n/g,"\\n"),val=val.replace(/\r/g,"\\r"),val=val.replace(/\t/g,"\\t"),this.emit('"'+val+'"')}else this.emit(node.value.toString())},compileSymbol:function(node,frame){var v,name=node.value;(v=frame.lookup(name))?this.emit(v):this.emit('runtime.contextOrFrameLookup(context, frame, "'+name+'")')},compileGroup:function(node,frame){this._compileAggregate(node,frame,"(",")")},compileArray:function(node,frame){this._compileAggregate(node,frame,"[","]")},compileDict:function(node,frame){this._compileAggregate(node,frame,"{","}")},compilePair:function(node,frame){var key=node.key,val=node.value;key instanceof nodes.Symbol?key=new nodes.Literal(key.lineno,key.colno,key.value):key instanceof nodes.Literal&&"string"==typeof key.value||this.fail("compilePair: Dict keys must be strings or names",key.lineno,key.colno),this.compile(key,frame),this.emit(": "),this._compileExpression(val,frame)},compileInlineIf:function(node,frame){this.emit("("),this.compile(node.cond,frame),this.emit("?"),this.compile(node.body,frame),this.emit(":"),null!==node.else_?this.compile(node.else_,frame):this.emit('""'),this.emit(")")},compileOr:binOpEmitter(" || "),compileAnd:binOpEmitter(" && "),compileAdd:binOpEmitter(" + "),compileSub:binOpEmitter(" - "),compileMul:binOpEmitter(" * "),compileDiv:binOpEmitter(" / "),compileMod:binOpEmitter(" % "),compileNot:function(node,frame){this.emit("!"),this.compile(node.target,frame)},compileFloorDiv:function(node,frame){this.emit("Math.floor("),this.compile(node.left,frame),this.emit(" / "),this.compile(node.right,frame),this.emit(")")},compilePow:function(node,frame){this.emit("Math.pow("),this.compile(node.left,frame),this.emit(", "),this.compile(node.right,frame),this.emit(")")},compileNeg:function(node,frame){this.emit("-"),this.compile(node.target,frame)},compilePos:function(node,frame){this.emit("+"),this.compile(node.target,frame)},compileCompare:function(node,frame){this.compile(node.expr,frame);for(var i=0;ii;i++)tmp.push(fill_with);res.push(tmp)}return res},capitalize:function(str){var ret=str.toLowerCase();return r.copySafeness(str,ret.charAt(0).toUpperCase()+ret.slice(1))},center:function(str,width){if(width=width||80,str.length>=width)return str;var spaces=width-str.length,pre=lib.repeat(" ",spaces/2-spaces%2),post=lib.repeat(" ",spaces/2);return r.copySafeness(str,pre+str+post)},"default":function(val,def){return val?val:def},dictsort:function(val,case_sensitive,by){if(!lib.isObject(val))throw new lib.TemplateError("dictsort filter: val must be an object");var array=[];for(var k in val)array.push([k,val[k]]);var si;if(void 0===by||"key"===by)si=0;else{if("value"!==by)throw new lib.TemplateError("dictsort filter: You can only sort by either key or value");si=1}return array.sort(function(t1,t2){var a=t1[si],b=t2[si];return case_sensitive||(lib.isString(a)&&(a=a.toUpperCase()),lib.isString(b)&&(b=b.toUpperCase())),a>b?1:a==b?0:-1}),array},escape:function(str){return"string"==typeof str||str instanceof r.SafeString?lib.escape(str):str},safe:function(str){return r.markSafe(str)},first:function(arr){return arr[0]},groupby:function(arr,attr){return lib.groupBy(arr,attr)},indent:function(str,width,indentfirst){width=width||4;for(var res="",lines=str.split("\n"),sp=lib.repeat(" ",width),i=0;i=maxCount);)last=res,res=res.replace(old,new_),count++;return r.copySafeness(str,res)},reverse:function(val){var arr;return arr=lib.isString(val)?filters.list(val):lib.map(val,function(v){return v}),arr.reverse(),lib.isString(val)?r.copySafeness(val,arr.join("")):arr},round:function(val,precision,method){precision=precision||0;var rounder,factor=Math.pow(10,precision);return rounder="ceil"==method?Math.ceil:"floor"==method?Math.floor:Math.round,rounder(val*factor)/factor},slice:function(arr,slices,fillWith){for(var sliceLength=Math.floor(arr.length/slices),extra=arr.length%slices,offset=0,res=[],i=0;slices>i;i++){var start=offset+i*sliceLength;extra>i&&offset++;var end=offset+(i+1)*sliceLength,slice=arr.slice(start,end);fillWith&&i>=extra&&slice.push(fillWith),res.push(slice)}return res},sort:function(arr,reverse,caseSens,attr){return arr=lib.map(arr,function(v){return v}),arr.sort(function(a,b){var x,y;return attr?(x=a[attr],y=b[attr]):(x=a,y=b),!caseSens&&lib.isString(x)&&lib.isString(y)&&(x=x.toLowerCase(),y=y.toLowerCase()),y>x?reverse?1:-1:x>y?reverse?-1:1:0}),arr},string:function(obj){return r.copySafeness(obj,obj)},title:function(str){for(var words=str.split(" "),i=0;i"+possibleUrl.substr(0,length)+"":wwwRE.test(possibleUrl)?'"+possibleUrl.substr(0,length)+"":emailRE.test(possibleUrl)?''+possibleUrl+"":tldRE.test(possibleUrl)?'"+possibleUrl.substr(0,length)+"":possibleUrl});return words.join(" ")},wordcount:function(str){var words=str?str.match(/\w+/g):null;return words?words.length:null},"float":function(val,def){var res=parseFloat(val);return isNaN(res)?def:res},"int":function(val,def){var res=parseInt(val,10);return isNaN(res)?def:res}};filters.d=filters["default"],filters.e=filters.escape,modules.filters=filters}(),function(){function cycler(items){var index=-1,current=null;return{reset:function(){index=-1,current=null},next:function(){return index++,index>=items.length&&(index=0),current=items[index]}}}function joiner(sep){sep=sep||",";var first=!0;return function(){var val=first?"":sep;return first=!1,val}}var globals={range:function(start,stop,step){stop?step||(step=1):(stop=start,start=0,step=1);for(var arr=[],i=start;stop>i;i+=step)arr.push(i);return arr},cycler:function(){return cycler(Array.prototype.slice.call(arguments))},joiner:function(sep){return joiner(sep)}};modules.globals=globals}(),function(){var Obj=modules.object,lib=modules.lib,Loader=Obj.extend({on:function(name,func){this.listeners=this.listeners||{},this.listeners[name]=this.listeners[name]||[],this.listeners[name].push(func)},emit:function(name){var args=Array.prototype.slice.call(arguments,1);this.listeners&&this.listeners[name]&&lib.each(this.listeners[name],function(listener){listener.apply(null,args)})}});modules.loader=Loader}(),function(){var Loader=modules.loader,WebLoader=Loader.extend({init:function(baseURL,neverUpdate){this.precompiled=window.nunjucksPrecompiled||{},this.baseURL=baseURL||"",this.neverUpdate=neverUpdate},getSource:function(name){if(this.precompiled[name])return{src:{type:"code",obj:this.precompiled[name]},path:name};var src=this.fetch(this.baseURL+"/"+name);return src?{src:src,path:name,noCache:!this.neverUpdate}:null},fetch:function(url,callback){var ajax,src,loading=!0;return window.XMLHttpRequest?ajax=new XMLHttpRequest:window.ActiveXObject&&(ajax=new ActiveXObject("Microsoft.XMLHTTP")),ajax.onreadystatechange=function(){4!==ajax.readyState||0!==ajax.status&&200!==ajax.status||!loading||(loading=!1,src=ajax.responseText)},url+=(-1===url.indexOf("?")?"?":"&")+"s="+(new Date).getTime(),ajax.open("GET",url,!1),ajax.send(),src}});modules["web-loaders"]={WebLoader:WebLoader}}(),function(){"undefined"==typeof window||window!==this?modules.loaders=modules["node-loaders"]:modules.loaders=modules["web-loaders"]}(),function(){var path=modules.path,lib=modules.lib,Obj=modules.object,lexer=modules.lexer,compiler=modules.compiler,builtin_filters=modules.filters,builtin_loaders=modules.loaders,runtime=modules.runtime,globals=modules.globals,Frame=runtime.Frame,Environment=Obj.extend({init:function(loaders,opts){opts=opts||{},this.dev=!!opts.dev,this.autoesc=!!opts.autoescape,loaders?this.loaders=lib.isArray(loaders)?loaders:[loaders]:builtin_loaders.FileSystemLoader?this.loaders=[new builtin_loaders.FileSystemLoader("views")]:this.loaders=[new builtin_loaders.WebLoader("/views")],this.initCache(),this.filters={},this.asyncFilters=[],this.extensions={},this.extensionsList=[],opts.tags&&lexer.setTags(opts.tags);for(var name in builtin_filters)this.addFilter(name,builtin_filters[name])},initCache:function(){var cache={};lib.each(this.loaders,function(loader){"function"==typeof loader.on&&loader.on("update",function(template){cache[template]=null})}),this.cache=cache},addExtension:function(name,extension){extension._name=name,this.extensions[name]=extension,this.extensionsList.push(extension)},getExtension:function(name){return this.extensions[name]},addGlobal:function(name,value){globals[name]=value},addFilter:function(name,func,async){var wrapped=func;async&&this.asyncFilters.push(name),this.filters[name]=wrapped},getFilter:function(name){if(!this.filters[name])throw new Error("filter not found: "+name);return this.filters[name]},getTemplate:function(name,eagerCompile,cb){if(name&&name.raw&&(name=name.raw),lib.isFunction(eagerCompile)&&(cb=eagerCompile,eagerCompile=!1),"string"!=typeof name)throw new Error("template names must be a string: "+name);var tmpl=this.cache[name];if(!tmpl){var syncResult;return lib.asyncIter(this.loaders,function(loader,i,next,done){function handle(src){src?done(src):next()}loader.async?loader.getSource(name,function(err,src){if(err)throw err;handle(src)}):handle(loader.getSource(name))},function(info){if(info){var tmpl=new Template(info.src,this,info.path,eagerCompile);info.noCache||(this.cache[name]=tmpl),cb?cb(null,tmpl):syncResult=tmpl}else{var err=new Error("template not found: "+name);if(!cb)throw err;cb(err)}}.bind(this)),syncResult}return eagerCompile&&tmpl.compile(),cb?void cb(null,tmpl):tmpl},express:function(app){function NunjucksView(name,opts){if(this.name=name,this.path=name,this.defaultEngine=opts.defaultEngine,this.ext=path.extname(name),!this.ext&&!this.defaultEngine)throw new Error("No default engine was specified and no extension was provided.");this.ext||(this.name+=this.ext=("."!==this.defaultEngine[0]?".":"")+this.defaultEngine)}var env=this;NunjucksView.prototype.render=function(opts,cb){env.render(this.name,opts,cb)},app.set("view",NunjucksView)},render:function(name,ctx,cb){lib.isFunction(ctx)&&(cb=ctx,ctx=null);var syncResult=null;return this.getTemplate(name,function(err,tmpl){if(err&&cb)cb(err);else{if(err)throw err;tmpl.render(ctx,cb||function(err,res){if(err)throw err;syncResult=res})}}),syncResult},renderString:function(src,ctx,cb){var tmpl=new Template(src,this);return tmpl.render(ctx,cb)}}),Context=Obj.extend({init:function(ctx,blocks){this.ctx=ctx,this.blocks={},this.exported=[];for(var name in blocks)this.addBlock(name,blocks[name])},lookup:function(name){return name in globals&&!(name in this.ctx)?globals[name]:this.ctx[name]},setVariable:function(name,val){this.ctx[name]=val},getVariables:function(){return this.ctx},addBlock:function(name,block){this.blocks[name]=this.blocks[name]||[],this.blocks[name].push(block)},getBlock:function(name){if(!this.blocks[name])throw new Error('unknown block "'+name+'"');return this.blocks[name][0]},getSuper:function(env,name,block,frame,runtime,cb){var idx=(this.blocks[name]||[]).indexOf(block),blk=this.blocks[name][idx+1],context=this;if(-1==idx||!blk)throw new Error('no super block available for "'+name+'"');blk(env,context,frame,runtime,cb)},addExport:function(name){this.exported.push(name)},getExported:function(){for(var exported={},i=0;i0&&index+match.length!==title.length&&match.search(smallWords)>-1&&":"!==title.charAt(index-2)&&("-"!==title.charAt(index+match.length)||"-"===title.charAt(index-1))&&title.charAt(index-1).search(/[^\s-]/)<0?match.toLowerCase():match.substr(1).search(/[A-Z]|\../)>-1?match:match.charAt(0).toUpperCase()+match.substr(1)})}function trim(s){return s.replace(/^\s+|\s+$/g,"")}function mightBeEmail(s){return/[^@]+@[^@]+/.test(s)}function warn(msg){console.warn("[analytics] "+msg)}function _gaEvent(options){if("function"==typeof ga){var fieldObject={hitType:"event",eventCategory:_category,eventAction:options.action};options.label&&(fieldObject.eventLabel=options.label),(options.value||0===options.value)&&(fieldObject.eventValue=options.value),options.nonInteraction===!0&&(fieldObject.nonInteraction=1),ga("send",fieldObject)}var eventArgs=["_trackEvent",_category,options.action];options.label&&(eventArgs[3]=options.label),(options.value||0===options.value)&&(eventArgs[4]=options.value),options.nonInteraction===!0&&(eventArgs[5]=!0),_gaq.push(eventArgs)}function event(action,options){options=options||{};var eventOptions={},label=options.label,value=options.value,nonInteraction=options.noninteraction||options.nonInteraction;return action?(mightBeEmail(action)&&(warn("`action` arg looks like an email address, redacting."),action=_redacted),eventOptions.action=toTitleCase(action),label&&("string"!=typeof label?warn("Expected `label` arg to be a String."):(mightBeEmail(label)&&(warn("`label` arg looks like an email address, redacting."),label=_redacted),eventOptions.label=trim(label))),(value||0===value)&&("number"!=typeof value?warn("Expected `value` arg to be a Number."):eventOptions.value=0|value),nonInteraction&&("boolean"!=typeof nonInteraction?warn("Expected `noninteraction` arg to be a Boolean."):eventOptions.nonInteraction=nonInteraction===!0),void _gaEvent(eventOptions)):void warn("Expected `action` arg.")}function prefixVirtualPageview(s){return/^\/virtual\//.test(s)?s:(s=s.replace(/^[/]?/,"/"),"/virtual"+s)}function _gaVirtualPageView(options){if("function"==typeof ga){var fieldObject={hitType:"pageview",page:options.virtualPagePath};ga("send",fieldObject)}var eventArgs=["_trackPageview",options.virtualPagePath];_gaq.push(eventArgs)}function virtualPageview(virtualPagePath){if(!virtualPagePath)return void warn("Expected `virtualPagePath` arg.");virtualPagePath=trim(virtualPagePath);var eventOptions={};eventOptions.virtualPagePath=prefixVirtualPageview(virtualPagePath),_gaVirtualPageView(eventOptions)}function _optimizely(options){var eventArgs=["trackEvent",options.action];if(options.revenue){var args={revenue:options.revenue};eventArgs[2]=args}optimizely.push(eventArgs)}function conversionGoal(action,options){options=options||{};var eventOptions={},valueInCents=options.valueInCents;return action?(eventOptions.action=trim(action),valueInCents&&("number"==typeof valueInCents&&valueInCents%1===0?eventOptions.revenue=valueInCents:warn("Expected `valueInCents` arg to be an integer.")),void _optimizely(eventOptions)):void warn("Expected `action` arg.")}this._gaq||(this._gaq=[]),this.optimizely||(this.optimizely=[]);var _category=location.hostname,_redacted="REDACTED (Potential Email Address)";return{event:event,virtualPageview:virtualPageview,conversionGoal:conversionGoal}})},{}],18:[function(require,module,exports){function _each(baseEl,selector,cb){if(baseEl){var els=baseEl.querySelectorAll(selector);if(els)for(var i=0;i\n \n \n \n\n\n',template_options), +login:template.renderString('\n\n',template_options),reset:template.renderString('\n\n',template_options),wrapper:'\n\n'},_create_modal_fragment=function(template){var range=document.createRange();range.selectNode(document.body);var modal_fragment=range.createContextualFragment(ui.wrapper);return modal_fragment.querySelector(".modal-content").appendChild(range.createContextualFragment(template)),modal_fragment},_translate_ng_html_expressions=function(modal_fragment){var elements=modal_fragment.querySelectorAll("[ng-bind-html]"),i=0;for(i=0;i div.modal-backdrop")),document.body.removeChild(document.querySelector("body > div.modal"))},_attach_close=function(modal){_each(modal,"[ng-click='close()']",function(i,el){el.addEventListener("click",function(event){event.preventDefault(),_close_modal()},!1)})},WebmakerLogin=function(options){var wmLogin=this.wmLogin=new wmLoginCore(options);this.showCTA=!!options.showCTA,this.disablePersona=!!options.disablePersona,EventEmitter.call(this);var query=url.parse(window.location.href,!0).query;query.uid&&query.resetCode?this.request_password_reset(query.uid,query.resetCode):query.uid&&query.token&&(wmLogin.instantLogin(query.uid,query.token,query.validFor),wmLogin.on("signedIn",function(user){this.emit("login",user)}.bind(this)),wmLogin.on("signinFailed",function(uid){console.log("Instant signin failed for uid %s",uid),this.login(uid,{expired:!0})}.bind(this))),wmLogin.on("verified",function(user){this.emit("verified",user)}.bind(this)),wmLogin.on("error",function(err){this.emit("error",err)}.bind(this)),wmLogin.verify()};util.inherits(WebmakerLogin,EventEmitter),WebmakerLogin.prototype.create=function(email_hint,username_hint,agreeToTerms_hint){var controller=this.wmLogin.joinWebmaker(this.showCTA),scope={MODALSTATE:{inputEmail:0,inputUsername:1,welcome:2},currentState:-1,form:{user:{$error:{}}},user:{},sendingRequest:!1,welcomeModalIdx:-1},modal_fragment=_create_modal_fragment(ui.create);_translate_ng_html_expressions(modal_fragment);var usernameWithUrl=modal_fragment.querySelector(".username-with-url");email_hint&&(scope.user.email=email_hint,modal_fragment.querySelector('input[name="email"]').value=email_hint),username_hint&&(scope.user.username=username_hint,modal_fragment.querySelector('input[name="username"]').value=username_hint,usernameWithUrl.textContent=scope.user.username),scope.user.agree=agreeToTerms_hint,controller.on("sendingRequest",function(state){scope.sendingRequest=state,_run_expressions(modal,scope)}),controller.on("displayEmailInput",function(){scope.currentState=scope.MODALSTATE.inputEmail,_run_expressions(modal,scope),modal.querySelector('input[focus-on="create-user-email"]').focus(),void 0!==scope.user.email&&controller.validateEmail(scope.user.email)&&void 0!==scope.user.agree&&(controller.submitEmail(scope.user.agree),scope.user.agree&&(scope.skippedEmail="true",controller.validateUsername(scope.user.username)))}),controller.on("displayUsernameInput",function(){scope.currentState=scope.MODALSTATE.inputUsername,_run_expressions(modal,scope),modal.querySelector('input[focus-on="create-user-username"]').focus()}),controller.on("displayWelcome",function(user,showCTA){this.emit("login",user),showCTA?scope.welcomeModalIdx=0:scope.simpleCTA=!0,scope.currentState=scope.MODALSTATE.welcome,_run_expressions(modal,scope)}.bind(this)),controller.on("displayAlert",function(alertId){scope.form.user.$error[alertId]=!0,_run_expressions(modal,scope)}),controller.on("hideAlert",function(alertId){scope.form.user.$error[alertId]=!1,_run_expressions(modal,scope)}),modal_fragment.querySelector('a[ng-click="switchToSignin();"]').addEventListener("click",function(event){event.preventDefault(),_close_modal(),setTimeout(function(){this.login(scope.user.email)}.bind(this),0)}.bind(this)),modal_fragment.querySelector('input[name="email"]').addEventListener("keyup",function(e){scope.user.email=e.target.value,e.target.value&&controller.validateEmail(scope.user.email)}),modal_fragment.querySelector('input[name="agree"]').addEventListener("change",function(e){scope.user.agree=e.target.checked,controller.agreeToTermsChanged(scope.user.agree),_run_expressions(modal,scope)}),modal_fragment.querySelector('input[name="subscribeToList"]').addEventListener("change",function(e){scope.user.subscribeToList=e.target.checked}),_each(modal_fragment,'button[ng-click="submitEmail()"]',function(i,el){el.addEventListener("click",function(e){controller.submitEmail(scope.user.agree)})}),modal_fragment.querySelector('input[name="username"]').addEventListener("input",function(e){scope.user.username=e.target.value,controller.validateUsername(scope.user.username),usernameWithUrl.textContent=scope.user.username}),_each(modal_fragment,'button[ng-click="submitUser()"]',function(i,el){el.addEventListener("click",function(){controller.submitUser(scope.user)})}),_run_expressions(modal_fragment,scope),_open_modal(modal_fragment);var modal=document.querySelector("body > div.modal");_attach_close(modal),document.querySelector("body > div.modal > .modal-dialog").addEventListener("click",function(e){e.stopPropagation()}),document.querySelector("body > div.modal").addEventListener("click",function(){_close_modal()}),controller.start()},WebmakerLogin.prototype.login=function(uid_hint,options){options=options||{};var controller=this.wmLogin.signIn(),scope={MODALSTATE:{enterUid:0,checkEmail:1,enterKey:2,enterPassword:3,resetRequestSent:4,enterEmail:5},currentState:0,form:{user:{$error:{}}},user:{},passwordWasReset:!!options.password_was_reset,expiredLoginLink:!!options.expired,sendingRequest:!1,disablePersona:this.disablePersona},modal_fragment=_create_modal_fragment(ui.login);_translate_ng_html_expressions(modal_fragment),uid_hint&&(scope.user.uid=uid_hint,modal_fragment.querySelector('input[name="uid"]').value=uid_hint),controller.on("sendingRequest",function(state){scope.sendingRequest=state,_run_expressions(modal,scope)}),controller.on("displayEnterUid",function(){scope.currentState=scope.MODALSTATE.enterUid,_run_expressions(modal,scope),modal.querySelector('input[focus-on="login-uid"]').focus()}),controller.on("displayEnterEmail",function(){scope.currentState=scope.MODALSTATE.enterEmail,_run_expressions(modal,scope),modal.querySelector('input[focus-on="login-uid"]').focus()}),controller.on("displayEnterPassword",function(){scope.currentState=scope.MODALSTATE.enterPassword,_run_expressions(modal,scope),modal.querySelector('input[focus-on="enter-password"]').focus()}),controller.on("displayEnterKey",function(verified){scope.verified=verified,scope.currentState=scope.MODALSTATE.enterKey,_run_expressions(modal,scope),modal.querySelector('input[focus-on="enter-key"]').focus()}),controller.on("displayCheckEmail",function(){scope.currentState=scope.MODALSTATE.checkEmail,_run_expressions(modal,scope)}),controller.on("displayResetSent",function(){scope.currentState=scope.MODALSTATE.resetRequestSent,_run_expressions(modal,scope)}),controller.on("displayAlert",function(alertId){scope.form.user.$error[alertId]=!0,_run_expressions(modal,scope)}),controller.on("hideAlert",function(alertId){scope.form.user.$error[alertId]=!1,_run_expressions(modal,scope)}),controller.on("signedIn",function(user){this.emit("login",user),_close_modal()}.bind(this)),modal_fragment.querySelector('input[name="uid"]').addEventListener("input",function(e){scope.user.uid=e.target.value,_run_expressions(modal,scope)}),modal_fragment.querySelector('input[name="myuid"]').addEventListener("input",function(e){scope.user.uid=e.target.value,_run_expressions(modal,scope)}),_each(modal_fragment,'input[name="rememberMe"]',function(i,el){el.addEventListener("change",function(e){scope.user.rememberMe=e.target.checked,_run_expressions(modal,scope)})}),_each(modal_fragment,'button[ng-click="submitUid()"]',function(i,el){el.addEventListener("click",function(){controller.submitUid(scope.user.uid,window.location.pathname)})}),_each(modal_fragment,'input[name="key"]',function(i,el){el.addEventListener("input",function(e){scope.user.key=e.target.value,_run_expressions(modal,scope)})}),_each(modal_fragment,'a[ng-click="enterKey()"]',function(i,el){el.addEventListener("click",function(event){event.preventDefault(),controller.displayEnterKey()})}),_each(modal_fragment,'button[ng-click="user.key && submitKey()"]',function(i,el){el.addEventListener("click",function(){controller.verifyKey(scope.user.uid,scope.user.key,scope.user.rememberMe)})}),modal_fragment.querySelector('input[name="password"]').addEventListener("input",function(e){scope.user.password=e.target.value,_run_expressions(modal,scope)}),_each(modal_fragment,'button[ng-click="user.password && submitPassword()"]',function(i,el){el.addEventListener("click",function(){controller.verifyPassword(scope.user.uid,scope.user.password,scope.user.rememberMe)})}),modal_fragment.querySelector('a[ng-click="requestReset()"]').addEventListener("click",function(event){event.preventDefault(),controller.requestReset(scope.user.uid)}),modal_fragment.querySelector('a[ng-click="requestEmail()"]').addEventListener("click",function(event){event.preventDefault(),controller.requestEmail(scope.user.uid)}),modal_fragment.querySelector('a[ng-click="switchToSignup();"]').addEventListener("click",function(event){event.preventDefault(),_close_modal(),setTimeout(function(){var uid=scope.user.uid,type=controller.getUidType(uid),email="email"===type?uid:"",username="username"===type?uid:"";this.create(email,username)}.bind(this),0)}.bind(this)),modal_fragment.querySelector('button[ng-click="usePersona();"]').addEventListener("click",function(event){event.preventDefault(),_close_modal(),setTimeout(function(){this._persona_login()}.bind(this),0)}.bind(this)),modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && !sendingRequest && submitUid()"]').addEventListener("keyup",function(event){13!==event.keyCode||scope.sendingRequest||controller.submitUid(scope.user.uid,window.location.pathname)}.bind(this)),modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && user.key && !sendingRequest && submitKey()"]').addEventListener("keyup",function(event){13===event.keyCode&&scope.user.key&&!scope.sendingRequest&&controller.verifyKey(scope.user.uid,scope.user.key,scope.user.rememberMe)}.bind(this)),modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && user.password && !sendingRequest && submitPassword()"]').addEventListener("keyup",function(event){13!==event.keyCode||scope.sendingRequest||controller.verifyPassword(scope.user.uid,scope.user.password,scope.user.rememberMe)}.bind(this)),_run_expressions(modal_fragment,scope),_open_modal(modal_fragment);var modal=document.querySelector("body > div.modal");_attach_close(modal),document.querySelector("body > div.modal > .modal-dialog").addEventListener("click",function(e){e.stopPropagation()}),controller.start()},WebmakerLogin.prototype._persona_login=function(){var controller=this.wmLogin.personaLogin();controller.on("signedIn",function(user){this.emit("login",user)}.bind(this)),controller.on("newUser",function(email){this.create(email)}.bind(this)),controller.authenticate()},WebmakerLogin.prototype.request_password_reset=function(uid,token){var controller=this.wmLogin.resetPassword(),scope={form:{password:{$error:{}}},password:{},sendingRequest:!1},modal_fragment=_create_modal_fragment(ui.reset);_translate_ng_html_expressions(modal_fragment),controller.on("sendingRequest",function(state){scope.sendingRequest=state,_run_expressions(modal,scope)}),controller.on("displayAlert",function(alertId){scope.form.password.$error[alertId]=!0,_run_expressions(modal,scope); +}),controller.on("hideAlert",function(alertId){scope.form.password.$error[alertId]=!1,_run_expressions(modal,scope)}),controller.on("checkConfirmPassword",function(status){scope.passwordsMatch=status,_run_expressions(modal,scope)}),controller.on("passwordCheckResult",function(result,blur){return result?(scope.eightCharsState=result.lengthValid?blur?"valid":"":"invalid",scope.oneEachCaseState=result.caseValid?blur?"valid":"":"invalid",scope.oneNumberState=result.digitValid?blur?"valid":"":"invalid",scope.isValidPassword=result.lengthValid&&result.caseValid&&result.digitValid,void _run_expressions(modal,scope)):(scope.eightCharsState=scope.oneEachCaseState=scope.oneNumberState="default",void(scope.isValidPassword=!1))}),controller.on("resetSucceeded",function(){_close_modal(),setTimeout(function(){this.login(uid,{password_was_reset:!0})}.bind(this),0)}.bind(this)),modal_fragment.querySelector('input[name="value"]').addEventListener("input",function(e){scope.password.value=e.target.value,controller.checkPasswordStrength(scope.password.value,!1)}),modal_fragment.querySelector('input[name="value"]').addEventListener("blur",function(e){scope.password.value=e.target.value,controller.checkPasswordStrength(scope.password.value,!0)}),modal_fragment.querySelector('input[name="confirmValue"]').addEventListener("input",function(e){scope.password.confirmValue=e.target.value,controller.passwordsMatch(scope.password.value,scope.password.confirmValue,!1)}),modal_fragment.querySelector('input[name="confirmValue"]').addEventListener("blur",function(e){scope.password.confirmValue=e.target.value,controller.passwordsMatch(scope.password.value,scope.password.confirmValue,!0)}),modal_fragment.querySelector('button[ng-click="submitResetRequest()"]').addEventListener("click",function(e){controller.submitResetRequest(uid,token,scope.password.value)}),_run_expressions(modal_fragment,scope),_open_modal(modal_fragment);var modal=document.querySelector("body > div.modal");_attach_close(modal),document.querySelector("body > div.modal > .modal-dialog > .modal-content > .modal-body > form.form > div > div.cta-links > button.reset-password").addEventListener("click",function(e){e.target.disabled===!1?controller.submitResetRequest(uid,token,scope.password.value):e.stopPropagation()})},WebmakerLogin.prototype.logout=function(){var controller=this.wmLogin.logout();controller.on("loggedOut",function(){this.emit("logout")}.bind(this)),controller.logout()},window.WebmakerLogin=WebmakerLogin,module.exports=WebmakerLogin},{"../../locale/en_US/webmaker-login.json":1,"../core":19,"angular-expressions":2,events:6,nunjucks:16,url:13,util:15}],19:[function(require,module,exports){var state=require("./state"),LoginAPI=require("./loginAPI"),Emitter=require("./state/emitter");module.exports=function(options){function verify(){loginAPI.verify(function(err,resp,body){if(err)return emitter.emit("error",err);try{body=JSON.parse(body)}catch(ex){return emitter.emit("error","could not parse json from verify route")}emitter.emit("verified",body.user)})}var loginAPI=new LoginAPI(options),emitter=new Emitter;return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},joinWebmaker:function(showCTA){return new state.JoinController(loginAPI,!!showCTA)},signIn:function(){return new state.SignInController(loginAPI)},resetPassword:function(){return new state.ResetController(loginAPI)},personaLogin:function(){return new state.PersonaController(loginAPI)},logout:function(){return new state.LogoutController(loginAPI)},instantLogin:function(uid,password,validFor){loginAPI.verifyKey(uid,password,validFor,function(err,resp,body){return err||200!==resp.status||!body.user?emitter.emit("signinFailed",uid):void emitter.emit("signedIn",body.user)})},verify:verify}}},{"./loginAPI":20,"./state":24,"./state/emitter":23}],20:[function(require,module,exports){var request=require("browser-request");module.exports=function(options){function doRequest(uri,payload,callback){request({method:"post",uri:uri,timeout:timeout,withCredentials:withCredentials,headers:headers,json:payload},callback)}function uidExists(uid,callback){doRequest(loginUrls.uidExists,{uid:uid},callback)}function checkUsername(username,callback){doRequest(loginUrls.checkUsername,{username:username},callback)}function createUser(user,callback){user.referrer=refferals.refValue(),doRequest(loginUrls.createUser,{user:user,audience:audience},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function sendLoginKey(uid,path,callback){doRequest(loginUrls.request,{uid:uid,path:path},callback)}function verifyKey(uid,key,validFor,callback){doRequest(loginUrls.authenticateToken,{uid:uid,token:key,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function verifyPassword(uid,password,validFor,callback){doRequest(loginUrls.verifyPassword,{uid:uid,password:password,validFor:validFor,user:{referrer:refferals.refValue()}},function(){refferals.clearReferrerCookie(),callback.apply(null,arguments)})}function requestReset(uid,callback){doRequest(loginUrls.requestResetCode,{uid:uid},callback)}function requestEmail(uid,callback){doRequest(loginUrls.requestResetCode,{uid:uid},callback)}function resetPassword(uid,resetCode,password,callback){doRequest(loginUrls.resetPassword,{uid:uid,resetCode:resetCode,newPassword:password},callback)}function personaLogin(assertion,callback){doRequest(loginUrls.authenticate,{assertion:assertion,audience:audience,user:{referrer:refferals.refValue()}},callback)}function logout(callback){doRequest(loginUrls.logout,null,callback)}function verify(callback){doRequest(loginUrls.verify,null,callback)}options=options||{},options.paths=options.paths||{};var refferals=require("./referrals.js")(),loginUrls=require("./loginUrls.js")(options),withCredentials=options.withCredentials!==!1,timeout=1e3*(options.timeout||10),headers={"X-CSRF-Token":options.csrfToken},audience=options.audience||window.location.protocol+"//"+window.location.host;return{uidExists:uidExists,checkUsername:checkUsername,createUser:createUser,sendLoginKey:sendLoginKey,verifyKey:verifyKey,verifyPassword:verifyPassword,requestReset:requestReset,requestEmail:requestEmail,resetPassword:resetPassword,personaLogin:personaLogin,logout:logout,verify:verify}}},{"./loginUrls.js":21,"./referrals.js":22,"browser-request":4}],21:[function(require,module,exports){module.exports=function(options){var paths={},host=options.host||"";return paths=options.paths||{},paths.authenticate=options.paths.authenticate||"/authenticate",paths.legacyCreate=options.paths.legacyCreate||"/create",paths.verify=options.paths.verify||"/verify",paths.logout=options.paths.logout||"/logout",paths.checkUsername=options.paths.checkUsername||"/check-username",paths.request=options.paths.request||"/auth/v2/request",paths.uidExists=options.paths.uidExists||"/auth/v2/uid-exists",paths.createUser=options.paths.createUser||"/auth/v2/create",paths.authenticateToken=options.paths.authenticateToken||"/auth/v2/authenticateToken",paths.verifyPassword=options.paths.verifyPassword||"/auth/v2/verify-password",paths.requestResetCode=options.paths.requestResetCode||"/auth/v2/request-reset-code",paths.removePassword=options.paths.removePassword||"/auth/v2/remove-password",paths.enablePasswords=options.paths.enablePasswords||"/auth/v2/enable-passwords",paths.resetPassword=options.paths.resetPassword||"/auth/v2/reset-password",{request:host+paths.request,authenticateToken:host+paths.authenticateToken,authenticate:host+paths.authenticate,legacyCreate:host+paths.legacyCreate,createUser:host+paths.createUser,verify:host+paths.verify,logout:host+paths.logout,uidExists:host+paths.uidExists,checkUsername:host+paths.checkUsername,verifyPassword:host+paths.verifyPassword,requestResetCode:host+paths.requestResetCode,removePassword:host+paths.removePassword,enablePasswords:host+paths.enablePasswords,resetPassword:host+paths.resetPassword}}},{}],22:[function(require,module,exports){var cookiejs=require("cookie-js");module.exports=function(){var referralCookieSettings={domain:location.hostname.split(".").slice(-2).join("."),path:"/",secure:"https:"===location.protocol,expires:new Date(Date.now()+6048e5)},refValue=/ref=((?:\w|-)+)/.exec(window.location.search),cookieRefValue=cookiejs.parse(document.cookie).webmakerReferral;return refValue&&(refValue=refValue[1],cookieRefValue!==refValue&&(document.cookie=cookiejs.serialize("webmakerReferral",refValue,referralCookieSettings),cookieRefValue=refValue)),{clearReferrerCookie:function(){referralCookieSettings.expires=new Date(Date.now()-1e4),document.cookie=cookiejs.serialize("webmakerReferral","expire",referralCookieSettings),referralCookieSettings.expires=new Date(Date.now()+6048e5)},refValue:function(){return cookieRefValue}}}},{"cookie-js":5}],23:[function(require,module,exports){var EventEmitter=require("events").EventEmitter;module.exports=function(){var emitter=new EventEmitter;return{on:function(event,listener){emitter.addListener(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):void emitter.removeAllListeners(event)},emit:function(){emitter.emit.apply(emitter,arguments)}}}},{events:6}],24:[function(require,module,exports){module.exports={JoinController:require("./join.js"),SignInController:require("./signin.js"),ResetController:require("./reset.js"),PersonaController:require("./persona.js"),LogoutController:require("./logout.js")}},{"./join.js":25,"./logout.js":26,"./persona.js":27,"./reset.js":28,"./signin.js":29}],25:[function(require,module,exports){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi,showCTA){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(JOIN_EVENTS.sendingRequest,state,!state)}function displayAlert(alertId,forceUpdate){emit(JOIN_EVENTS.displayAlert,alertId,forceUpdate)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alert){emit(JOIN_EVENTS.hideAlert,alert)})}function validateEmailCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.accountExists,!0):void 0}function usernameExistsCallback(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError,!0):body.exists?displayAlert(JOIN_ALERTS.usernameTaken,!0):void emit(JOIN_EVENTS.displayUsernameInput)}var emitter=new Emitter,JOIN_ALERTS={agreeToTerms:"agreeToTerms",accountExists:"accountExists",invalidEmail:"invalidEmail",invalidUsername:"invalidUsername",usernameTaken:"usernameTaken",serverError:"serverError"},JOIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayUsernameInput:"displayUsernameInput",displayEmailInput:"displayEmailInput",displayWelcome:"displayWelcome"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){return listener?void emitter.removeListener(event,listener):emitter.off(event)},start:function(){emit(JOIN_EVENTS.displayEmailInput)},validateEmail:function(email){clearAlerts([JOIN_ALERTS.invalidEmail,JOIN_ALERTS.accountExists,JOIN_ALERTS.serverError]);var valid=validation.isEmail(email);return valid?(setRequestState(!0),loginApi.uidExists(email,validateEmailCallback),!0):(displayAlert(JOIN_ALERTS.invalidEmail),!1)},submitEmail:function(agreeToTerms){return agreeToTerms?void emit(JOIN_EVENTS.displayUsernameInput):displayAlert(JOIN_ALERTS.agreeToTerms)},agreeToTermsChanged:function(agree){agree&&emit(JOIN_EVENTS.hideAlert,JOIN_ALERTS.agreeToTerms)},validateUsername:function(username){if(clearAlerts([JOIN_ALERTS.invalidUsername,JOIN_ALERTS.usernameTaken,JOIN_ALERTS.serverError]),username){var valid=validation.isUsername(username);if(!valid)return displayAlert(JOIN_ALERTS.invalidUsername);setRequestState(!0),loginApi.uidExists(username,usernameExistsCallback)}},submitUser:function(formData){clearAlerts([JOIN_ALERTS.agreeToTerms,JOIN_ALERTS.serverError]);var lang="en-US",html=document.querySelector("html");html.lang&&(lang=html.lang),setRequestState(!0),loginApi.createUser({email:formData.email,username:formData.username,mailingList:formData.subscribeToList,prefLocale:lang},function(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(JOIN_ALERTS.serverError):(analytics.event("Webmaker New User Created",{nonInteraction:!0}),analytics.conversionGoal("WebmakerNewUserCreated"),void emit(JOIN_EVENTS.displayWelcome,body.user,showCTA))})}}}},{"../validation":30,"./emitter.js":23,"webmaker-analytics":17}],26:[function(require,module,exports){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginAPI){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter;return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},logout:function(){loginAPI.logout(function(err,resp,body){return err||200!==resp.status?emit("logoutFailed"):(analytics.event("Webmaker Logout Clicked"),void emit("loggedOut"))})}}}},{"./emitter.js":23,"webmaker-analytics":17}],27:[function(require,module,exports){var Emitter=require("./emitter.js"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}var emitter=new Emitter,PERSONA_EVENTS={signedIn:"signedIn",newUser:"newUser"},analyticsLabel={label:"persona"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},authenticate:function(){return window.navigator.id?(analytics.event("Persona Login Clicked"),void window.navigator.id.get(function(assertion){return assertion?void loginApi.personaLogin(assertion,function(err,resp,body){return err||200!==resp.status?void analytics.event("Webmaker Login Failed",analyticsLabel):(analytics.event("Webmaker Login Succeeded",analyticsLabel),void(body.user?emit(PERSONA_EVENTS.signedIn,body.user):body.email&&(analytics.event("Webmaker New User Started",analyticsLabel),emit(PERSONA_EVENTS.newUser,body.email))))}):void analytics.event("Webmaker Login Cancelled",analyticsLabel)})):console.error("No persona found. Did you load include.js?")}}}},{"./emitter.js":23,"webmaker-analytics":17}],28:[function(require,module,exports){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(RESET_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(RESET_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(RESET_EVENTS.hideAlert,alertId)}var emitter=new Emitter,RESET_ALERTS={passwordsMustMatch:"passwordsMustMatch",weakPassword:"weakPassword",serverError:"serverError"},RESET_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",resetSucceeded:"resetSucceeded",passwordCheckResult:"passwordCheckResult",checkConfirmPassword:"checkConfirmPassword"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},passwordsMatch:function(password,confimValue,blur){validation.passwordsMatch(password,confimValue)?(hideAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!0)):(blur&&displayAlert(RESET_ALERTS.passwordsMustMatch),emit(RESET_EVENTS.checkConfirmPassword,!1))},checkPasswordStrength:function(password,blur){emit(RESET_EVENTS.passwordCheckResult,validation.checkPasswordStrength(password),blur)},submitResetRequest:function(uid,resetCode,password){hideAlert(RESET_ALERTS.serverError),hideAlert(RESET_ALERTS.weakPassword),setRequestState(!0),loginApi.resetPassword(uid,resetCode,password,function(err,resp,body){return setRequestState(!1),err||200!==resp.status?displayAlert(400===resp.status?RESET_ALERTS.weakPassword:RESET_ALERTS.serverError):(analytics.event("Webmaker Password Reset Succeeded"),void(window.location="/"))})}}}},{"../validation":30,"./emitter.js":23,"webmaker-analytics":17}],29:[function(require,module,exports){var Emitter=require("./emitter.js"),validation=require("../validation"),analytics=require("webmaker-analytics");module.exports=function(loginApi){function emit(){emitter.emit.apply(emitter,arguments)}function setRequestState(state){emit(SIGNIN_EVENTS.sendingRequest,state)}function displayAlert(alertId){emit(SIGNIN_EVENTS.displayAlert,alertId)}function hideAlert(alertId){emit(SIGNIN_EVENTS.hideAlert,alertId)}function clearAlerts(alerts){alerts=Array.isArray(alerts)?alerts:[alerts],alerts.forEach(function(alertId){hideAlert(alertId)})}var emitter=new Emitter,SIGNIN_ALERTS={paswordReset:"paswordReset",noAccount:"noAccount",invalidUid:"invalidUid",serverError:"serverError",invalidKey:"invalidKey",passwordSigninFailed:"passwordSigninFailed",resetRequestFailed:"resetRequestFailed"},SIGNIN_EVENTS={sendingRequest:"sendingRequest",displayAlert:"displayAlert",hideAlert:"hideAlert",displayEnterUid:"displayEnterUid",displayEnterPassword:"displayEnterPassword",displayEnterKey:"displayEnterKey",displayCheckEmail:"displayCheckEmail",displayResetSent:"displayResetSent",signedIn:"signedIn",displayEnterEmail:"displayEnterEmail"};return{on:function(event,listener){emitter.on(event,listener)},off:function(event,listener){emitter.off(event,listener)},start:function(){emit(SIGNIN_EVENTS.displayEnterUid)},submitUid:function(uid,path){clearAlerts([SIGNIN_ALERTS.invalidUid,SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.noAccount]);var valid=validation.isEmail(uid)||validation.isUsername(uid);return valid?(setRequestState(!0),void loginApi.uidExists(uid,function(err,resp,body){if(setRequestState(!1),err||200!==resp.status)return displayAlert(SIGNIN_ALERTS.serverError);var isVerified=body.verified;return body.exists?body.usePasswordLogin?!1:void loginApi.sendLoginKey(uid,path,function(err,resp,body){return err?displayAlert(SIGNIN_ALERTS.serverError):void(isVerified?emit(SIGNIN_EVENTS.displayEnterKey,!1):emit(SIGNIN_EVENTS.displayCheckEmail))}):displayAlert(SIGNIN_ALERTS.noAccount)})):displayAlert(SIGNIN_ALERTS.invalidUid)},displayEnterKey:function(){emit(SIGNIN_EVENTS.displayEnterKey,!0)},verifyKey:function(uid,key,rememberMe){clearAlerts([SIGNIN_ALERTS.serverError,SIGNIN_ALERTS.invalidKey]),setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyKey(uid,key,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"key"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.invalidKey)})},verifyPassword:function(uid,password,rememberMe){setRequestState(!0);var validFor=rememberMe?"one-year":"";loginApi.verifyPassword(uid,password,validFor,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):body.user?(analytics.event("Webmaker Login Succeeded",{label:"password"}),void emit(SIGNIN_EVENTS.signedIn,body.user)):displayAlert(SIGNIN_ALERTS.passwordSigninFailed)})},requestEmail:function(uid){setRequestState(!1),emit(SIGNIN_EVENTS.displayEnterEmail)},requestReset:function(uid){setRequestState(!0),loginApi.requestReset(uid,function(err,resp,body){return setRequestState(!1),err?displayAlert(SIGNIN_ALERTS.serverError):(hideAlert(SIGNIN_ALERTS.serverError),body.status?(hideAlert(SIGNIN_ALERTS.resetRequestFailed),analytics.event("Webmaker Password Reset Requested"),void emit(SIGNIN_EVENTS.displayResetSent)):displayAlert(SIGNIN_ALERTS.resetRequestFailed))})},getUidType:function(uid){return validation.isEmail(uid)?"email":validation.isUsername(uid)?"username":null}}}},{"../validation":30,"./emitter.js":23,"webmaker-analytics":17}],30:[function(require,module,exports){var usernameRegex=/^[a-zA-Z0-9\-]{1,20}$/,emailRegex=/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,containsBothCases=/^.*(?=.*[a-z])(?=.*[A-Z]).*$/,containsDigit=/\d/,MIN_PASSWORD_LEN=8;module.exports={isEmail:function(email){return emailRegex.test(email)},isUsername:function(username){return usernameRegex.test(username)},passwordsMatch:function(password,confirmation){return password===confirmation},checkPasswordStrength:function(password){if(!password)return!1;var lengthValid=password.length>=MIN_PASSWORD_LEN,caseValid=!!password.match(containsBothCases),digitValid=!!password.match(containsDigit);return{lengthValid:lengthValid,caseValid:caseValid,digitValid:digitValid}}}},{}]},{},[18]); \ No newline at end of file diff --git a/dist/ngWebmakerLogin.js b/dist/ngWebmakerLogin.js index a4d7a06..3547fe2 100644 --- a/dist/ngWebmakerLogin.js +++ b/dist/ngWebmakerLogin.js @@ -1415,11 +1415,13 @@ ngModule.directive('wmSignin', [ checkEmail: 1, enterKey: 2, enterPassword: 3, - resetRequestSent: 4 + resetRequestSent: 4, + enterEmail: 5 }; $scope.MODALSTATE = MODALSTATE; $scope.currentState = MODALSTATE.enterUid; + $scope.enterEmail = enterEmail; $scope.passwordWasReset = passwordWasReset; $scope.sendingRequest = false; $scope.disablePersona = disablePersona; @@ -1446,6 +1448,13 @@ ngModule.directive('wmSignin', [ }, 0); }); + signinController.on('displayEnterEmail', function () { + $timeout(function () { + $scope.currentState = MODALSTATE.enterEmail; + focus('input[focus-on="login-uid2"]'); + }, 0); + }); + signinController.on('displayEnterPassword', function () { $timeout(function () { $scope.currentState = MODALSTATE.enterPassword; @@ -1499,6 +1508,10 @@ ngModule.directive('wmSignin', [ signinController.displayEnterKey(); }; + $scope.enterEmail = function(){ + signinController.displayEnterEmail(); + }; + $scope.submitKey = function () { signinController.verifyKey($scope.user.uid, $scope.user.key, $scope.user.rememberMe); }; @@ -1518,6 +1531,7 @@ ngModule.directive('wmSignin', [ $scope.switchToSignup = function () { var uid = $scope.user.uid, + myid = $scope.user.id, type = signinController.getUidType(uid), email = type === 'email' ? uid : '', username = type === 'username' ? uid : ''; @@ -1552,7 +1566,9 @@ ngModule.directive('wmSignin', [ disablePersona: function () { return $scope.disablePersona; } - } + }, + backdrop: 'static', /* this prevent user interaction with the background */ + keyboard: false }); }; } @@ -1655,6 +1671,7 @@ ngModule.directive('wmPasswordReset', [ }; $scope.submitResetRequest = function () { + var uid = $scope.user.uid; resetController.submitResetRequest(uid, resetCode, $scope.password.value); }; @@ -1768,7 +1785,7 @@ module.exports = function WebmakerLoginCore(options) { }); } - window.addEventListener('focus', verify); + //window.addEventListener('focus', verify); return { on: function (event, listener) { @@ -1897,6 +1914,12 @@ module.exports = function LoginAPI(options) { }, callback); } + function requestEmail(uid,callback) { + doRequest(loginUrls.requestResetCode, { + uid: uid + }, callback); + } + function resetPassword(uid, resetCode, password, callback) { doRequest(loginUrls.resetPassword, { uid: uid, @@ -1931,6 +1954,7 @@ module.exports = function LoginAPI(options) { verifyKey: verifyKey, verifyPassword: verifyPassword, requestReset: requestReset, + requestEmail: requestEmail, resetPassword: resetPassword, personaLogin: personaLogin, logout: logout, @@ -2381,8 +2405,8 @@ module.exports = function ResetController(loginApi) { } analytics.event('Webmaker Password Reset Succeeded'); - - emit(RESET_EVENTS.resetSucceeded); + window.location = '/'; + //emit(RESET_EVENTS.resetSucceeded); }); } }; @@ -2416,7 +2440,8 @@ module.exports = function SignInController(loginApi) { displayEnterKey: 'displayEnterKey', displayCheckEmail: 'displayCheckEmail', displayResetSent: 'displayResetSent', - signedIn: 'signedIn' + signedIn: 'signedIn', + displayEnterEmail: 'displayEnterEmail' }; function emit() { @@ -2480,7 +2505,7 @@ module.exports = function SignInController(loginApi) { } if (body.usePasswordLogin) { - return emit(SIGNIN_EVENTS.displayEnterPassword); + return false; //emit(SIGNIN_EVENTS.displayEnterPassword); } loginApi.sendLoginKey(uid, path, function sendLoginKeyCallback(err, resp, body) { @@ -2545,16 +2570,24 @@ module.exports = function SignInController(loginApi) { emit(SIGNIN_EVENTS.signedIn, body.user); }); }, + requestEmail: function(uid) { + setRequestState(false); + emit(SIGNIN_EVENTS.displayEnterEmail); + }, requestReset: function (uid) { setRequestState(true); loginApi.requestReset(uid, function requestResetCallback(err, resp, body) { setRequestState(false); if (err) { return displayAlert(SIGNIN_ALERTS.serverError); + } else { + hideAlert(SIGNIN_ALERTS.serverError); } if (!body.status) { return displayAlert(SIGNIN_ALERTS.resetRequestFailed); + } else { + hideAlert(SIGNIN_ALERTS.resetRequestFailed); } analytics.event('Webmaker Password Reset Requested'); diff --git a/dist/templates/ngWebmakerLogin.templates.js b/dist/templates/ngWebmakerLogin.templates.js index cb46532..ee7636b 100644 --- a/dist/templates/ngWebmakerLogin.templates.js +++ b/dist/templates/ngWebmakerLogin.templates.js @@ -175,10 +175,10 @@ angular.module("reset-modal.html", []).run(["$templateCache", function($template angular.module("signin-modal.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("signin-modal.html", "
\n" + - " \n" + + " \n" + "

\n" + " \n" + - " {{ 'Sign in to Webmaker' | i18n }}\n" + + " {{ 'Sign in' | i18n }}\n" + " \n" + "

\n" + + "

\n" + + " Reset Password\n" + + "

\n" + "

\n" + " {{ 'Cancel' | i18n }}\n" + " {{ 'checkEmail' | i18n }}\n" + @@ -218,19 +221,50 @@ angular.module("signin-modal.html", []).run(["$templateCache", function($templat "
\n" + " \n" + " \n" + + " \n" + + " \n" + "
\n" + "
\n" + + "
\n" + "
\n" + + "
\n" + + " \n" + + " \n" + + "
\n" + " \n" + " \n" + "\n" + + " \n" + + "
\n" + + "\n" + + "
\n" + + " \n" + + " \n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "
\n" + + " \n" + + "
\n" + + " \n" + + "\n" + " \n" + "
\n" + "
\n" + @@ -274,7 +308,7 @@ angular.module("signin-modal.html", []).run(["$templateCache", function($templat " \n" + " \n" + " \n" + - " \n" + + " \n" + " \n" + " \n" + " \n" + @@ -293,7 +327,7 @@ angular.module("signin-modal.html", []).run(["$templateCache", function($templat "
\n" + "
\n" + " \n" + - "
\n" + "\n" + @@ -343,7 +377,7 @@ angular.module("signin-modal.html", []).run(["$templateCache", function($templat " \n" + " \n" + " \n" + - " \n" + + " \n" + " \n" + " \n" + " \n" + @@ -353,10 +387,6 @@ angular.module("signin-modal.html", []).run(["$templateCache", function($templat " \n" + "

{{ 'resetMessage' | i18n }}

\n" + "
\n" + - "
\n" + - "
\n" + - "

{{ 'you can switch to webmaker login' | i18n }}

\n" + - "
\n" + "
\n" + " \n" + "

\n" + diff --git a/dist/webmakerLogin.js b/dist/webmakerLogin.js index 8301b13..6a21dfe 100644 --- a/dist/webmakerLogin.js +++ b/dist/webmakerLogin.js @@ -1,16 +1,16 @@ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;oget help.", + "message": "An unknown error occurred on the server. Try your request again. If the problem persists, get help.", "description": "Error message displayed if an error occurs on the server." }, "webmakerAuthCreateWelcome": { - "message": "Create a Webmaker account", - "description": "Header text for the join webmaker modal dialog" + "message": "Create An Account", + "description": "Header text for the join modal dialog" }, "webmakerAuthChooseUsername": { "message": "Choose A Username", @@ -25,12 +25,12 @@ module.exports={ "description": "Error message displayed when the username entered contains symbols that are not allowed." }, "webmakerAuthMailingList": { - "message": "Send me email updates about Webmaker and other Mozilla projects", + "message": "Send me email updates about and other projects", "description": "Message about opting in for a Mozilla mailing list" }, "webmakerAuthAgreeToTerms": { - "message": "I agree to Mozilla Webmaker's Terms and Privacy Policy", - "description": "I agree to Mozilla Webmaker's terms and privacy policy." + "message": "I agree to Terms and Privacy Policy", + "description": "I agree to terms and privacy policy." }, "webmakerAuthAgreeError": { "message": " Oh snap! You must agree to our terms and conditions.", @@ -38,7 +38,11 @@ module.exports={ }, "webmakerAuthCreateAccount": { "message": "Create Account", - "description": "The button text for finishing the join Webmaker process." + "description": "The button text for finishing the join process." + }, + "Back": { + "message": "Back", + "description": "Back text" }, "Cancel": { "message": "Cancel", @@ -49,8 +53,8 @@ module.exports={ "description": "Label text for the email input" }, "EmailOrUsername": { - "message": "Email or Username", - "description": "Label text for the sign in input, asks for the username or email of the user's account." + "message": "Username (your email)", + "description": "Label text for the sign in input, asks for the email of the user's account." }, "NotAnEmail": { "message": " Uh Oh! That doesn't look like an email address.", @@ -69,7 +73,11 @@ module.exports={ "description": "Label text for selecting the preferred language for the user." }, "Sign in to Webmaker": { - "message": "Sign In To Webmaker", + "message": "Sign In", + "description": "Header text for the sign in modal dialog" + }, + "Sign in to VideoRemix": { + "message": "Sign In", "description": "Header text for the sign in modal dialog" }, "Sign in": { @@ -89,7 +97,7 @@ module.exports={ "description": "Directs the user to check their email for a password reset link" }, "resetRequestFailed": { - "message": " Uh oh! Something went wrong! Try requesting the password reset again. Or, get help.", + "message": " Uh oh! Something went wrong! Try requesting the password reset again. Or, get help.", "description": "Error displayed if a password reset request fails." }, "Password": { @@ -100,6 +108,14 @@ module.exports={ "message": "Forgot your password?", "description": "button text for the password reset function" }, + "Reset your password?": { + "message": "Reset your password?", + "description": "link text for the password reset function" + }, + "Click to Reset your password": { + "message": "Click to Reset your password", + "description": "Link text for the password reset function" + }, "checkEmail": { "message": "Check Your Email", "description": "Message instructing the user to check their email" @@ -113,11 +129,11 @@ module.exports={ "description": "Error message displayed when the input doesn't match a username or email" }, "No account found for your uid": { - "message": " We couldn't find your username or email address. Did you mean to create an account? Trouble? Get help.", - "description": "Error message displayed when the given username or email doesn't have a Webmaker account and asks if they would like to sign up." + "message": " We couldn't find your email address. Did you mean to create an account? Trouble? Get help.", + "description": "Error message displayed when the given username or email doesn't have an account and asks if they would like to sign up." }, "problem sending token": { - "message": " There was a problem sending a login key to you, please try again. Get help.", + "message": " There was a problem sending a login key to you, please try again. Get help.", "description": "Error message displayed when the request for a login key fails for some reason." }, "incorrectToken": { @@ -137,8 +153,8 @@ module.exports={ "description": "Label to enter key that was sent to user's email" }, "you can switch to webmaker login": { - "message": "You can switch back to our Webmaker Login experience. We will send you login emails so you do not need a password.", - "description": "Message reminding users that they can switch back to the Webmaker Login Key system instead of using a password." + "message": "You can switch back to our VideoRemix Login experience. We will send you login emails so you do not need a password.", + "description": "Message reminding users that they can switch back to the Login Key system instead of using a password." }, "Submit": { "message": "Submit", @@ -153,12 +169,12 @@ module.exports={ "description": "Text for the button that initiates a persona login" }, "trouble with email": { - "message": "Trouble with email? Check your spam or get help", + "message": "Trouble with email? Check your spam or get help", "description": "Text that allows users to get help" }, "aboutWebmaker": { "message": "Make your own web pages, interactive videos, remixes and mobile apps.", - "description": "Short description of Webmaker" + "description": "Short description" }, "XRay-Goggles": { "message": "X-Ray Goggles", @@ -173,15 +189,15 @@ module.exports={ "description": "Text for the button that takes the user to the X-Ray Goggles homepage" }, "ExploreWebmaker": { - "message": "Explore the rest of Webmaker", - "description": "Text for the button which takes the user to webmaker.org/explore" + "message": "Explore the rest", + "description": "Text for the button which takes the user to explore" }, "Resources": { "message": "Resources", - "description": "The Resources section of Webmaker" + "description": "The Resources section" }, "AboutResources": { - "message": "Teach and learn digital skills and web literacy. Webmaker Resources are full of fun things to discover, make and teach.", + "message": "Teach and learn digital skills and web literacy. Resources are full of fun things to discover, make and teach.", "description": "A short description about the Resources section" }, "VisitResources": { @@ -201,7 +217,7 @@ module.exports={ "description": "Label text for the password confirmation input" }, "Reset Password": { - "message": "Reset Password", + "message": "Click to Reset Password", "description": "Reset Password Modal title" }, "Set a Password": { @@ -233,7 +249,7 @@ module.exports={ "description": "a password must contain at least one number character" }, "resetRequestFailed": { - "message": " Uh oh! There was a problem processing your request, please try again.", + "message": " Uh oh! There was a problem processing your request, Please enter your Email & try again.", "description": "Error message displayed if the reset request fails for some reason" }, "Next": { @@ -259,6 +275,10 @@ module.exports={ "Expired Login Link": { "message": "Uh Oh! Your login link expired. Request a new email to sign in.", "description": "Error message displayed if a login link is expired" + }, + "Contact Support": { + "message": "Contact Support", + "description": "Digital Zendesk Link" } } @@ -9556,7 +9576,7 @@ expressions.filters.i18n = function (key) { var ui = { create: template.renderString("
\n \n

\n {{ 'Cancel' | i18n }}\n {{ 'webmakerAuthCreateWelcome' | i18n }}\n {{ 'Next' | i18n }}\n {{ 'Sign up' | i18n }}\n

\n

\n {{ 'Cancel' | i18n }}\n {{ 'webmakerAuthWelcome' | i18n }}\n {{ 'Done' | i18n }}\n

\n
\n
\n
\n
\n
\n \n \n
\n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n \n
\n\n
\n
\n \n \n \n
webmaker.org/user/{{user.username}}
\n
\n
\n
\n
\n
\n \n \n
\n \n
\n\n
\n

{{ 'aboutWebmaker' | i18n }}

\n\n \n
\n
\n \n \n Goggles\n XRay Goggles.\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n

{{ 'XRay-Goggles' | i18n }}

\n

{{ 'AboutGoggles' | i18n }}

\n \n
\n\n \n
\n
\n \n {{ 'ExploreWebmaker' | i18n }}\n
\n
\n
\n
\n
\n", template_options), - login: template.renderString("
\n \n

\n \n {{ 'Sign in to Webmaker' | i18n }}\n \n \n

\n

\n {{ 'Cancel' | i18n }}\n {{ 'checkEmail' | i18n }}\n {{ 'Next' | i18n }}\n {{ 'Next' | i18n }}\n {{ 'Done' | i18n }}\n

\n
\n
\n
\n
\n
\n
\n\n \n
\n
\n \n \n
\n
\n
\n \n
\n \n\n \n
\n
\n \n \n Mail Icon\n \n \n \n \n \n \n \n \n \n \n \n \n \n

{{ 'tokenMessage' | i18n }}

\n
\n
\n \n
\n
\n
\n

\n
\n
\n \n\n \n
\n
\n
\n \n \n Mail Icon\n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n
\n
\n \n \n \n
\n
\n
\n
\n \n \n
\n \n
\n
\n
\n
\n

\n
\n
\n \n\n
\n
\n
\n \n \n
\n
\n
\n \n \n
\n \n
\n
\n
\n

{{ 'you can switch to webmaker login' | i18n }}

\n
\n
\n\n
\n
\n \n \n Mail Icon\n \n \n \n \n \n \n \n \n \n \n \n \n \n

{{ 'resetMessage' | i18n }}

\n
\n
\n
\n

{{ 'you can switch to webmaker login' | i18n }}

\n
\n
\n
\n
\n", template_options), + login: template.renderString("
\n \n

\n \n {{ 'Sign in' | i18n }}\n \n \n

\n

\n Reset Password\n

\n

\n {{ 'Cancel' | i18n }}\n {{ 'checkEmail' | i18n }}\n {{ 'Next' | i18n }}\n {{ 'Next' | i18n }}\n {{ 'Done' | i18n }}\n

\n
\n
\n
\n
\n
\n
\n\n \n
\n
\n \n \n \n \n
\n
\n
\n
\n
\n \n \n
\n \n
\n \n\n \n
\n\n
\n \n \n\n
\n
\n
\n
\n \n
\n \n\n \n
\n
\n \n \n Mail Icon\n \n \n \n \n \n \n \n \n \n \n \n \n \n

{{ 'tokenMessage' | i18n }}

\n
\n
\n \n
\n
\n
\n

\n
\n
\n \n\n \n
\n
\n
\n \n \n Mail Icon\n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n
\n
\n \n \n \n
\n
\n
\n
\n \n \n
\n \n
\n
\n
\n
\n

\n
\n
\n \n\n
\n
\n
\n \n \n
\n
\n
\n \n \n
\n \n
\n
\n
\n \n
\n
\n\n
\n
\n \n \n Mail Icon\n \n \n \n \n \n \n \n \n \n \n \n \n \n

{{ 'resetMessage' | i18n }}

\n
\n
\n
\n
\n", template_options), reset: template.renderString("
\n \n

\n {{ 'Cancel' | i18n }}\n {{ 'Reset Password' | i18n }}\n \n

\n
\n
\n
\n\n
\n
\n
\n\n
\n
\n

{{ 'Minimum password requirements' | i18n }}

\n
    \n
  • {{ 'At least 8 characters' | i18n }}
  • \n
  • {{ 'At least 1 upper and lower case character' | i18n }}
  • \n
  • {{ 'At least 1 number' | i18n }}
  • \n
\n
\n
\n \n \n
\n
\n \n \n
\n \n
\n
\n
\n", template_options), wrapper: "
\n
\n
\n
\n
\n
\n" }; @@ -9829,7 +9849,8 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { checkEmail: 1, enterKey: 2, enterPassword: 3, - resetRequestSent: 4 + resetRequestSent: 4, + enterEmail: 5, }, currentState: 0, form: { @@ -9863,6 +9884,12 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { modal.querySelector('input[focus-on="login-uid"]').focus(); }); + controller.on('displayEnterEmail', function () { + scope.currentState = scope.MODALSTATE.enterEmail; + _run_expressions(modal, scope); + modal.querySelector('input[focus-on="login-uid"]').focus(); + }); + controller.on('displayEnterPassword', function () { scope.currentState = scope.MODALSTATE.enterPassword; _run_expressions(modal, scope); @@ -9906,6 +9933,11 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { _run_expressions(modal, scope); }); + modal_fragment.querySelector('input[name="myuid"]').addEventListener('input', function (e) { + scope.user.uid = e.target.value; + _run_expressions(modal, scope); + }); + _each(modal_fragment, 'input[name="rememberMe"]', function (i, el) { el.addEventListener('change', function (e) { scope.user.rememberMe = e.target.checked; @@ -9953,6 +9985,11 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { controller.requestReset(scope.user.uid); }); + modal_fragment.querySelector('a[ng-click="requestEmail()"]').addEventListener('click', function (event) { + event.preventDefault(); + controller.requestEmail(scope.user.uid); + }); + modal_fragment.querySelector('a[ng-click="switchToSignup();"]').addEventListener('click', function (event) { event.preventDefault(); _close_modal(); @@ -9987,7 +10024,7 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { }.bind(this)); modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && user.password && !sendingRequest && submitPassword()"]').addEventListener('keyup', function (event) { - if (event.keyCode === 13 && scope.user.password && !scope.sendingRequest) { + if (event.keyCode === 13 && !scope.sendingRequest) { controller.verifyPassword(scope.user.uid, scope.user.password, scope.user.rememberMe); } }.bind(this)); @@ -9999,9 +10036,10 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { document.querySelector('body > div.modal > .modal-dialog').addEventListener("click", function (e) { e.stopPropagation(); }); + /* Prevent click modal to close document.querySelector('body > div.modal').addEventListener("click", function () { _close_modal(); - }); + }); */ controller.start(); }; @@ -10107,12 +10145,17 @@ WebmakerLogin.prototype.request_password_reset = function (uid, token) { _open_modal(modal_fragment); var modal = document.querySelector('body > div.modal'); _attach_close(modal); - document.querySelector('body > div.modal > .modal-dialog').addEventListener("click", function (e) { - e.stopPropagation(); + document.querySelector('body > div.modal > .modal-dialog > .modal-content > .modal-body > form.form > div > div.cta-links > button.reset-password').addEventListener("click", function (e) { + if (e.target.disabled === false) { + controller.submitResetRequest(uid, token, scope.password.value); + } else { + e.stopPropagation(); + } }); + /* document.querySelector('body > div.modal').addEventListener("click", function () { _close_modal(); - }); + }); */ }; WebmakerLogin.prototype.logout = function () { @@ -10153,7 +10196,7 @@ module.exports = function WebmakerLoginCore(options) { }); } - window.addEventListener('focus', verify); + //window.addEventListener('focus', verify); return { on: function (event, listener) { @@ -10282,6 +10325,12 @@ module.exports = function LoginAPI(options) { }, callback); } + function requestEmail(uid,callback) { + doRequest(loginUrls.requestResetCode, { + uid: uid + }, callback); + } + function resetPassword(uid, resetCode, password, callback) { doRequest(loginUrls.resetPassword, { uid: uid, @@ -10316,6 +10365,7 @@ module.exports = function LoginAPI(options) { verifyKey: verifyKey, verifyPassword: verifyPassword, requestReset: requestReset, + requestEmail: requestEmail, resetPassword: resetPassword, personaLogin: personaLogin, logout: logout, @@ -10766,8 +10816,8 @@ module.exports = function ResetController(loginApi) { } analytics.event('Webmaker Password Reset Succeeded'); - - emit(RESET_EVENTS.resetSucceeded); + window.location = '/'; + //emit(RESET_EVENTS.resetSucceeded); }); } }; @@ -10801,7 +10851,8 @@ module.exports = function SignInController(loginApi) { displayEnterKey: 'displayEnterKey', displayCheckEmail: 'displayCheckEmail', displayResetSent: 'displayResetSent', - signedIn: 'signedIn' + signedIn: 'signedIn', + displayEnterEmail: 'displayEnterEmail' }; function emit() { @@ -10865,7 +10916,7 @@ module.exports = function SignInController(loginApi) { } if (body.usePasswordLogin) { - return emit(SIGNIN_EVENTS.displayEnterPassword); + return false; //emit(SIGNIN_EVENTS.displayEnterPassword); } loginApi.sendLoginKey(uid, path, function sendLoginKeyCallback(err, resp, body) { @@ -10930,16 +10981,24 @@ module.exports = function SignInController(loginApi) { emit(SIGNIN_EVENTS.signedIn, body.user); }); }, + requestEmail: function(uid) { + setRequestState(false); + emit(SIGNIN_EVENTS.displayEnterEmail); + }, requestReset: function (uid) { setRequestState(true); loginApi.requestReset(uid, function requestResetCallback(err, resp, body) { setRequestState(false); if (err) { return displayAlert(SIGNIN_ALERTS.serverError); + } else { + hideAlert(SIGNIN_ALERTS.serverError); } if (!body.status) { return displayAlert(SIGNIN_ALERTS.resetRequestFailed); + } else { + hideAlert(SIGNIN_ALERTS.resetRequestFailed); } analytics.event('Webmaker Password Reset Requested'); diff --git a/locale/en_US/webmaker-login.json b/locale/en_US/webmaker-login.json index 12dfaef..e296a56 100644 --- a/locale/en_US/webmaker-login.json +++ b/locale/en_US/webmaker-login.json @@ -1,15 +1,15 @@ { "webmakerAuthWelcome": { - "message": "Welcome to Webmaker!", - "description": "Welcome message for the join Webmaker modal dialog. Displayed after successfully creating a new Webmaker account" + "message": "Welcome!", + "description": "Welcome message for the join modal dialog. Displayed after successfully creating a new account" }, "webmakerAuthServerError": { - "message": "An unknown error occurred on the server. Try your request again. If the problem persists, get help.", + "message": "An unknown error occurred on the server. Try your request again. If the problem persists, get help.", "description": "Error message displayed if an error occurs on the server." }, "webmakerAuthCreateWelcome": { - "message": "Create a Webmaker account", - "description": "Header text for the join webmaker modal dialog" + "message": "Create An Account", + "description": "Header text for the join modal dialog" }, "webmakerAuthChooseUsername": { "message": "Choose A Username", @@ -24,12 +24,12 @@ "description": "Error message displayed when the username entered contains symbols that are not allowed." }, "webmakerAuthMailingList": { - "message": "Send me email updates about Webmaker and other Mozilla projects", + "message": "Send me email updates about and other projects", "description": "Message about opting in for a Mozilla mailing list" }, "webmakerAuthAgreeToTerms": { - "message": "I agree to Mozilla Webmaker's Terms and Privacy Policy", - "description": "I agree to Mozilla Webmaker's terms and privacy policy." + "message": "I agree to Terms and Privacy Policy", + "description": "I agree to terms and privacy policy." }, "webmakerAuthAgreeError": { "message": " Oh snap! You must agree to our terms and conditions.", @@ -37,7 +37,11 @@ }, "webmakerAuthCreateAccount": { "message": "Create Account", - "description": "The button text for finishing the join Webmaker process." + "description": "The button text for finishing the join process." + }, + "Back": { + "message": "Back", + "description": "Back text" }, "Cancel": { "message": "Cancel", @@ -48,8 +52,8 @@ "description": "Label text for the email input" }, "EmailOrUsername": { - "message": "Email or Username", - "description": "Label text for the sign in input, asks for the username or email of the user's account." + "message": "Username (your email)", + "description": "Label text for the sign in input, asks for the email of the user's account." }, "NotAnEmail": { "message": " Uh Oh! That doesn't look like an email address.", @@ -68,7 +72,11 @@ "description": "Label text for selecting the preferred language for the user." }, "Sign in to Webmaker": { - "message": "Sign In To Webmaker", + "message": "Sign In", + "description": "Header text for the sign in modal dialog" + }, + "Sign in to VideoRemix": { + "message": "Sign In", "description": "Header text for the sign in modal dialog" }, "Sign in": { @@ -88,7 +96,7 @@ "description": "Directs the user to check their email for a password reset link" }, "resetRequestFailed": { - "message": " Uh oh! Something went wrong! Try requesting the password reset again. Or, get help.", + "message": " Uh oh! Something went wrong! Try requesting the password reset again. Or, get help.", "description": "Error displayed if a password reset request fails." }, "Password": { @@ -99,6 +107,14 @@ "message": "Forgot your password?", "description": "button text for the password reset function" }, + "Reset your password?": { + "message": "Reset your password?", + "description": "link text for the password reset function" + }, + "Click to Reset your password": { + "message": "Click to Reset your password", + "description": "Link text for the password reset function" + }, "checkEmail": { "message": "Check Your Email", "description": "Message instructing the user to check their email" @@ -112,11 +128,11 @@ "description": "Error message displayed when the input doesn't match a username or email" }, "No account found for your uid": { - "message": " We couldn't find your username or email address. Did you mean to create an account? Trouble? Get help.", - "description": "Error message displayed when the given username or email doesn't have a Webmaker account and asks if they would like to sign up." + "message": " We couldn't find your email address. Did you mean to create an account? Trouble? Get help.", + "description": "Error message displayed when the given username or email doesn't have an account and asks if they would like to sign up." }, "problem sending token": { - "message": " There was a problem sending a login key to you, please try again. Get help.", + "message": " There was a problem sending a login key to you, please try again. Get help.", "description": "Error message displayed when the request for a login key fails for some reason." }, "incorrectToken": { @@ -136,8 +152,8 @@ "description": "Label to enter key that was sent to user's email" }, "you can switch to webmaker login": { - "message": "You can switch back to our Webmaker Login experience. We will send you login emails so you do not need a password.", - "description": "Message reminding users that they can switch back to the Webmaker Login Key system instead of using a password." + "message": "You can switch back to our VideoRemix Login experience. We will send you login emails so you do not need a password.", + "description": "Message reminding users that they can switch back to the Login Key system instead of using a password." }, "Submit": { "message": "Submit", @@ -152,12 +168,12 @@ "description": "Text for the button that initiates a persona login" }, "trouble with email": { - "message": "Trouble with email? Check your spam or get help", + "message": "Trouble with email? Check your spam or get help", "description": "Text that allows users to get help" }, "aboutWebmaker": { "message": "Make your own web pages, interactive videos, remixes and mobile apps.", - "description": "Short description of Webmaker" + "description": "Short description" }, "XRay-Goggles": { "message": "X-Ray Goggles", @@ -172,15 +188,15 @@ "description": "Text for the button that takes the user to the X-Ray Goggles homepage" }, "ExploreWebmaker": { - "message": "Explore the rest of Webmaker", - "description": "Text for the button which takes the user to webmaker.org/explore" + "message": "Explore the rest", + "description": "Text for the button which takes the user to explore" }, "Resources": { "message": "Resources", - "description": "The Resources section of Webmaker" + "description": "The Resources section" }, "AboutResources": { - "message": "Teach and learn digital skills and web literacy. Webmaker Resources are full of fun things to discover, make and teach.", + "message": "Teach and learn digital skills and web literacy. Resources are full of fun things to discover, make and teach.", "description": "A short description about the Resources section" }, "VisitResources": { @@ -200,7 +216,7 @@ "description": "Label text for the password confirmation input" }, "Reset Password": { - "message": "Reset Password", + "message": "Click to Reset Password", "description": "Reset Password Modal title" }, "Set a Password": { @@ -232,7 +248,7 @@ "description": "a password must contain at least one number character" }, "resetRequestFailed": { - "message": " Uh oh! There was a problem processing your request, please try again.", + "message": " Uh oh! There was a problem processing your request, Please enter your Email & try again.", "description": "Error message displayed if the reset request fails for some reason" }, "Next": { @@ -258,5 +274,9 @@ "Expired Login Link": { "message": "Uh Oh! Your login link expired. Request a new email to sign in.", "description": "Error message displayed if a login link is expired" + }, + "Contact Support": { + "message": "Contact Support", + "description": "Digital Zendesk Link" } } diff --git a/src/adapters/angular.js b/src/adapters/angular.js index b2781e9..662ba8a 100644 --- a/src/adapters/angular.js +++ b/src/adapters/angular.js @@ -288,11 +288,13 @@ ngModule.directive('wmSignin', [ checkEmail: 1, enterKey: 2, enterPassword: 3, - resetRequestSent: 4 + resetRequestSent: 4, + enterEmail: 5 }; $scope.MODALSTATE = MODALSTATE; $scope.currentState = MODALSTATE.enterUid; + $scope.enterEmail = enterEmail; $scope.passwordWasReset = passwordWasReset; $scope.sendingRequest = false; $scope.disablePersona = disablePersona; @@ -319,6 +321,13 @@ ngModule.directive('wmSignin', [ }, 0); }); + signinController.on('displayEnterEmail', function () { + $timeout(function () { + $scope.currentState = MODALSTATE.enterEmail; + focus('input[focus-on="login-uid2"]'); + }, 0); + }); + signinController.on('displayEnterPassword', function () { $timeout(function () { $scope.currentState = MODALSTATE.enterPassword; @@ -372,6 +381,10 @@ ngModule.directive('wmSignin', [ signinController.displayEnterKey(); }; + $scope.enterEmail = function(){ + signinController.displayEnterEmail(); + }; + $scope.submitKey = function () { signinController.verifyKey($scope.user.uid, $scope.user.key, $scope.user.rememberMe); }; @@ -391,6 +404,7 @@ ngModule.directive('wmSignin', [ $scope.switchToSignup = function () { var uid = $scope.user.uid, + myid = $scope.user.id, type = signinController.getUidType(uid), email = type === 'email' ? uid : '', username = type === 'username' ? uid : ''; @@ -425,7 +439,9 @@ ngModule.directive('wmSignin', [ disablePersona: function () { return $scope.disablePersona; } - } + }, + backdrop: 'static', /* this prevent user interaction with the background */ + keyboard: false }); }; } @@ -528,6 +544,7 @@ ngModule.directive('wmPasswordReset', [ }; $scope.submitResetRequest = function () { + var uid = $scope.user.uid; resetController.submitResetRequest(uid, resetCode, $scope.password.value); }; diff --git a/src/adapters/plain.js b/src/adapters/plain.js index d1d4b83..55eeae7 100644 --- a/src/adapters/plain.js +++ b/src/adapters/plain.js @@ -317,7 +317,8 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { checkEmail: 1, enterKey: 2, enterPassword: 3, - resetRequestSent: 4 + resetRequestSent: 4, + enterEmail: 5, }, currentState: 0, form: { @@ -351,6 +352,12 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { modal.querySelector('input[focus-on="login-uid"]').focus(); }); + controller.on('displayEnterEmail', function () { + scope.currentState = scope.MODALSTATE.enterEmail; + _run_expressions(modal, scope); + modal.querySelector('input[focus-on="login-uid"]').focus(); + }); + controller.on('displayEnterPassword', function () { scope.currentState = scope.MODALSTATE.enterPassword; _run_expressions(modal, scope); @@ -394,6 +401,11 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { _run_expressions(modal, scope); }); + modal_fragment.querySelector('input[name="myuid"]').addEventListener('input', function (e) { + scope.user.uid = e.target.value; + _run_expressions(modal, scope); + }); + _each(modal_fragment, 'input[name="rememberMe"]', function (i, el) { el.addEventListener('change', function (e) { scope.user.rememberMe = e.target.checked; @@ -441,6 +453,11 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { controller.requestReset(scope.user.uid); }); + modal_fragment.querySelector('a[ng-click="requestEmail()"]').addEventListener('click', function (event) { + event.preventDefault(); + controller.requestEmail(scope.user.uid); + }); + modal_fragment.querySelector('a[ng-click="switchToSignup();"]').addEventListener('click', function (event) { event.preventDefault(); _close_modal(); @@ -475,7 +492,7 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { }.bind(this)); modal_fragment.querySelector('input[ng-keyup="$event.keyCode === 13 && user.password && !sendingRequest && submitPassword()"]').addEventListener('keyup', function (event) { - if (event.keyCode === 13 && scope.user.password && !scope.sendingRequest) { + if (event.keyCode === 13 && !scope.sendingRequest) { controller.verifyPassword(scope.user.uid, scope.user.password, scope.user.rememberMe); } }.bind(this)); @@ -487,9 +504,10 @@ WebmakerLogin.prototype.login = function (uid_hint, options) { document.querySelector('body > div.modal > .modal-dialog').addEventListener("click", function (e) { e.stopPropagation(); }); + /* Prevent click modal to close document.querySelector('body > div.modal').addEventListener("click", function () { _close_modal(); - }); + }); */ controller.start(); }; @@ -595,12 +613,17 @@ WebmakerLogin.prototype.request_password_reset = function (uid, token) { _open_modal(modal_fragment); var modal = document.querySelector('body > div.modal'); _attach_close(modal); - document.querySelector('body > div.modal > .modal-dialog').addEventListener("click", function (e) { - e.stopPropagation(); + document.querySelector('body > div.modal > .modal-dialog > .modal-content > .modal-body > form.form > div > div.cta-links > button.reset-password').addEventListener("click", function (e) { + if (e.target.disabled === false) { + controller.submitResetRequest(uid, token, scope.password.value); + } else { + e.stopPropagation(); + } }); + /* document.querySelector('body > div.modal').addEventListener("click", function () { _close_modal(); - }); + }); */ }; WebmakerLogin.prototype.logout = function () { diff --git a/src/core/index.js b/src/core/index.js index 133eb60..d95119d 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -22,7 +22,7 @@ module.exports = function WebmakerLoginCore(options) { }); } - window.addEventListener('focus', verify); + //window.addEventListener('focus', verify); return { on: function (event, listener) { diff --git a/src/core/loginAPI/index.js b/src/core/loginAPI/index.js index 7feac03..18abf7f 100644 --- a/src/core/loginAPI/index.js +++ b/src/core/loginAPI/index.js @@ -89,6 +89,12 @@ module.exports = function LoginAPI(options) { }, callback); } + function requestEmail(uid,callback) { + doRequest(loginUrls.requestResetCode, { + uid: uid + }, callback); + } + function resetPassword(uid, resetCode, password, callback) { doRequest(loginUrls.resetPassword, { uid: uid, @@ -123,6 +129,7 @@ module.exports = function LoginAPI(options) { verifyKey: verifyKey, verifyPassword: verifyPassword, requestReset: requestReset, + requestEmail: requestEmail, resetPassword: resetPassword, personaLogin: personaLogin, logout: logout, diff --git a/src/core/state/reset.js b/src/core/state/reset.js index 71e5098..7d4cc09 100644 --- a/src/core/state/reset.js +++ b/src/core/state/reset.js @@ -71,8 +71,8 @@ module.exports = function ResetController(loginApi) { } analytics.event('Webmaker Password Reset Succeeded'); - - emit(RESET_EVENTS.resetSucceeded); + window.location = '/'; + //emit(RESET_EVENTS.resetSucceeded); }); } }; diff --git a/src/core/state/signin.js b/src/core/state/signin.js index 7b5b076..c9395db 100644 --- a/src/core/state/signin.js +++ b/src/core/state/signin.js @@ -25,7 +25,8 @@ module.exports = function SignInController(loginApi) { displayEnterKey: 'displayEnterKey', displayCheckEmail: 'displayCheckEmail', displayResetSent: 'displayResetSent', - signedIn: 'signedIn' + signedIn: 'signedIn', + displayEnterEmail: 'displayEnterEmail' }; function emit() { @@ -89,7 +90,7 @@ module.exports = function SignInController(loginApi) { } if (body.usePasswordLogin) { - return emit(SIGNIN_EVENTS.displayEnterPassword); + return false; //emit(SIGNIN_EVENTS.displayEnterPassword); } loginApi.sendLoginKey(uid, path, function sendLoginKeyCallback(err, resp, body) { @@ -154,16 +155,24 @@ module.exports = function SignInController(loginApi) { emit(SIGNIN_EVENTS.signedIn, body.user); }); }, + requestEmail: function(uid) { + setRequestState(false); + emit(SIGNIN_EVENTS.displayEnterEmail); + }, requestReset: function (uid) { setRequestState(true); loginApi.requestReset(uid, function requestResetCallback(err, resp, body) { setRequestState(false); if (err) { return displayAlert(SIGNIN_ALERTS.serverError); + } else { + hideAlert(SIGNIN_ALERTS.serverError); } if (!body.status) { return displayAlert(SIGNIN_ALERTS.resetRequestFailed); + } else { + hideAlert(SIGNIN_ALERTS.resetRequestFailed); } analytics.event('Webmaker Password Reset Requested'); diff --git a/templates/signin-modal.html b/templates/signin-modal.html index 6165269..fc8d53d 100644 --- a/templates/signin-modal.html +++ b/templates/signin-modal.html @@ -1,8 +1,8 @@
+
+
+ + +
+ +
+ +
+ + + +
+
+
+
+ +
+ +
@@ -98,7 +132,7 @@
-
-
@@ -167,7 +201,7 @@