<commit_before>'use strict';

	// Providers
	var GithubEventsProvider = function (){
		var username = '';
		var loader = 'Loading Github Events...';
		var error = [
			'
GithubEvents: Something went wrong, please review your configuration.
',
			'
',
				'Message: {{error.message | roIgnoreAllAfterFirstNewLine}}',
				'
',
					'
Make sure the profile you are trying to access is currently active
',
					'
Make sure the privacy settings are allowing public events to be accessible
',
					'
Make sure your Internet connection is active
',
					'
If the issue persists you can ask for some advice in the forum or submit an issue
',
				'

',
				'You can customize this error message during the configuration phase of your application by using:
 githubEventsProvider.error(\"You custom message\")

 See the GithubEvents project page for further reading.',
			'
'
		].join('\n');

		this.username = function (value) {
			username = value;
			return this;
		}

		this.template = function (template, section, value) {
			if(templates[template]) {
				if(angular.isObject(section)){
					angular.forEach(section, function (value, key){
						templates[template][key] = value;
					});
				} else {
					templates[template][section] = value;
				}
			}
			return this;
		}

		this.loader = function (value){
			loader = 'loader'.replace('loader', value);
			return this;
		}

		this.error = function (value){
			error = value;
			return this;
		}

		var sections = ['icon', 'date', 'heading', 'avatar', 'body'];

		var templatesNameSpace = 'templates/github-events';

		var defaultTpl = {
			icon: '',
			date: '{{event.created_at | timeAgo}}',
			heading: [
				'
',
					'{{event.actor.login}}',
					'{{event.payload.action}}',
					'{{event.repo.full_name}}',
				'
'
			].join('\n'),
			avatar: [
				'',
					'',
				''
			].join('\n'),
			body: '
{{event.type}}
',
			empty: '',
		}

		var templates = {
			'default': defaultTpl,
			CommitCommentEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'commented on commit {{event.repo.name}}@{{event.payload.comment.commit_id | limitTo:10}}',
					'
',
				].join('\n'),
				body: '
{{event.payload.comment.body | roIgnoreAllAfterFirstNewLine | roIgnoreAllAfterFirstDot}}
',
			},
			CreateEvent: {
				heading: [
					'',
						'{{event.actor.login}} created {{event.payload.ref_type}} ',
						'',
							'',
								'{{event.payload.ref | roMakeRef}}',
							'  at',
						'',
						' {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			/*CreateEvent: {
				heading: [
					'',
						'{{event.actor.login}} created {{event.payload.ref_type}} ',
						'',
							'{{event.payload.ref | roMakeRef}}',
						' ',
						'at {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},*/
			DeleteEvent: {
				heading: [
					'',
						'{{event.actor.login}} deleted {{event.payload.ref_type}} ',
						'{{event.payload.ref}}',
						'at {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			DeploymentEvent: defaultTpl,
			DeploymentStatusEvent: defaultTpl,
			DownloadEvent: defaultTpl,
			FollowEvent: defaultTpl,
			ForkEvent: {
				heading: [
					'',
						'{{event.actor.login}} forked ',
						'{{event.repo.name}} ',
						'at {{event.payload.forkee.full_name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			ForkApplyEvent: defaultTpl,
			GistEvent: defaultTpl,
			GollumEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'{{event.payload.pages[0].action}} the {{event.repo.name}} wiki',
					'
',
				].join('\n'),
				body: '
{{page.action}} {{page.title}}.
',
			},
			IssueCommentEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'commented on issue {{event.repo.name}}#{{event.payload.issue.number}}',
					'
',
				].join('\n'),
				body: '
{{event.payload.comment.body | roIgnoreAllAfterFirstNewLine }}
',
			},
			IssuesEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'{{event.payload.action}} issue ',
						'{{ event.repo.name }}#{{event.payload.issue.number}} ',
					'
',
				].join('\n'),
				body: [
					'
{{event.payload.issue.title}}
'
				].join('\n'),
			},
			MemberEvent: {
				heading: [
					'',
						'{{event.actor.login}} added ',
						'{{event.payload.user.login}} ',
						'to {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			MembershipEvent: defaultTpl,
			PageBuildEvent: defaultTpl,
			PublicEvent: {
				heading: [
					'',
						'{{event.actor.login}} has made ',
						'{{event.repo.name}} public',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			PullRequestEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'{{event.payload.action}} pull request ',
						'{{ event.repo.name }}#{{event.payload.pull_request.number}} ',
					'
',
				].join('\n'),
				body: [
					'
',
						'{{event.payload.pull_request.title}}
',
					'
',
					'
',
						'',
							'{{event.payload.pull_request.commits | number}} {{  {true:\'commit\', false:\'commits\'}[event.payload.pull_request.commits==1]  }} with',
							'{{event.payload.pull_request.additions | number}} {{  {true:\'addition\', false:\'additions\'}[event.payload.pull_request.additions==1]  }} and',
							'{{event.payload.pull_request.deletions | number}} {{  {true:\'deletions\', false:\'deletions\'}[event.payload.pull_request.deletions==1]  }}',
						'',
					'
',
				].join('\n'),
			},
			PullRequestReviewCommentEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'commented on a pull request ',
						'{{ event.repo.name }}#{{event.payload.pull_request.number}} ',
					'
',
				].join('\n'),
				body: [
					'
{{event.payload.comment.body | roIgnoreAllAfterFirstDot}}
'
				].join('\n'),
			},
			PushEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'pushed to {{  event.payload.ref | roMakeRef }} ',
						'at {{event.repo.name}}',
					'
',
				].join('\n'),
				body: [
					'
',
						' ',
						'{{commit.sha | limitTo:7}} {{commit.message | roIgnoreAllAfterFirstNewLine }}',
					'
',
					'',
						'{{event.payload.commits.length - 2}} more commits »',
					'',
					'',
						'View comparison for these 2 commits »',
					''
				].join('\n'),
			},
			ReleaseEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'released {{  event.payload.release.name }} ',
						'at {{event.repo.name}}',
					'
',
				].join('\n'),
				body: [
					'
',
						'Source code (zip)',
					'
',
				].join('\n'),
			},
			RepositoryEvent: defaultTpl,
			StatusEvent: defaultTpl,
			TeamAddEvent: defaultTpl,
			WatchEvent: {
				heading: [
					'',
						'{{event.actor.login}} starred ',
						'{{event.repo.name}}',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
		}

		this.$get = function ($resource, $templateCache){
			var Events = $resource('https://api.github.com/users/:username/events/public', null, {cache:true});

			angular.forEach(templates, function (tplValue, tplKey) {
				angular.forEach(tplValue, function (sectionValue, sectionKey){
					var path, url;

					path = templatesNameSpace+'/type-section.html';
					url = path
						.replace('type', tplKey)
						.replace('section', sectionKey);

					$templateCache.put(url, sectionValue);
				});
			});

			return {
				// Github API Services
				events: function (username){
					return 	Events.query({username:username});
				},

				// Gets
				getUser: function (){
					return username;
				},
				getTemplate: function (type, section){
					if(!templates[type] || templates[type] && !templates[type][section]) {
						type = 'default';
						if(!templates[type][section])
							section = 'empty';
					}

					var path = templatesNameSpace+'/type-section.html';
					var url = path
						.replace('type', type)
						.replace('section', section);

					return url;
				},
				getLoader: function (){
					return loader;
				},
				getError: function (){
					return error;
				}
			}

		}
	}
	/**
        * @ngdoc overview
        * @name githubEvents.provider:githubEventsProvider
        * @requires chem.components.button
        * @description
        * The chem.components module is a collection of AngularJS directives for
        * rapidly generate the DOM structure for Bootstrap Components.
        * This module makes use of {@link http://angular-ui.github.io/bootstrap ui.bootstrap}.
        *
        *
        * ##External Dependencies
        * {@link http://angular-ui.github.io/bootstrap ui.bootstrap}
        *
        * ##Installation
        * There are may ways to install chem.components in your project.
        * ###Installing using Bower
        * You can use {@link http://bower.io Bower} to load chem.components into your project dependencies:
        * >`bower install chem.components --save`
        *
        * ###Installing using Npm
        * You can use {@link http://bower.io Npm} to load chem.components into your project dependencies:
        * >`npm install chem.components --save`
    **/
	angular.module('githubEvents.providers', [])
		.provider('githubEvents', GithubEventsProvider);
<commit_msg>Updated githubEvents.providers<commit_after>'use strict';

	// Providers
	var GithubEventsProvider = function (){
		var username = '';
		var loader = 'Loading Github Events...';
		var error = [
			'
GithubEvents: Something went wrong, please review your configuration.
',
			'
',
				'Message: {{error.message | roIgnoreAllAfterFirstNewLine}}',
				'
',
					'
Make sure the profile you are trying to access is currently active
',
					'
Make sure the privacy settings are allowing public events to be accessible
',
					'
Make sure your Internet connection is active
',
					'
If the issue persists you can ask for some advice in the forum or submit an issue
',
				'

',
				'You can customize this error message during the configuration phase of your application by using:
 githubEventsProvider.error(\"You custom message\")

 See the GithubEvents project page for further reading.',
			'
'
		].join('\n');

		this.username = function (value) {
			username = value;
			return this;
		}

		this.template = function (template, section, value) {
			if(templates[template]) {
				if(angular.isObject(section)){
					angular.forEach(section, function (value, key){
						templates[template][key] = value;
					});
				} else {
					templates[template][section] = value;
				}
			}
			return this;
		}

		this.loader = function (value){
			loader = 'loader'.replace('loader', value);
			return this;
		}

		this.error = function (value){
			error = value;
			return this;
		}

		var sections = ['icon', 'date', 'heading', 'avatar', 'body'];

		var templatesNameSpace = 'templates/github-events';

		var defaultTpl = {
			icon: '',
			date: '{{event.created_at | timeAgo}}',
			heading: [
				'
',
					'{{event.actor.login}}',
					'{{event.payload.action}}',
					'{{event.repo.full_name}}',
				'
'
			].join('\n'),
			avatar: [
				'',
					'',
				''
			].join('\n'),
			body: '
{{event.type}}
',
			empty: '',
		}

		var templates = {
			'default': defaultTpl,
			CommitCommentEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'commented on commit {{event.repo.name}}@{{event.payload.comment.commit_id | limitTo:10}}',
					'
',
				].join('\n'),
				body: '
{{event.payload.comment.body | roIgnoreAllAfterFirstNewLine | roIgnoreAllAfterFirstDot}}
',
			},
			CreateEvent: {
				heading: [
					'',
						'{{event.actor.login}} created {{event.payload.ref_type}} ',
						'',
							'',
								'{{event.payload.ref | roMakeRef}}',
							'  at',
						'',
						' {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			/*CreateEvent: {
				heading: [
					'',
						'{{event.actor.login}} created {{event.payload.ref_type}} ',
						'',
							'{{event.payload.ref | roMakeRef}}',
						' ',
						'at {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},*/
			DeleteEvent: {
				heading: [
					'',
						'{{event.actor.login}} deleted {{event.payload.ref_type}} ',
						'{{event.payload.ref}}',
						'at {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			DeploymentEvent: defaultTpl,
			DeploymentStatusEvent: defaultTpl,
			DownloadEvent: defaultTpl,
			FollowEvent: defaultTpl,
			ForkEvent: {
				heading: [
					'',
						'{{event.actor.login}} forked ',
						'{{event.repo.name}} ',
						'at {{event.payload.forkee.full_name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			ForkApplyEvent: defaultTpl,
			GistEvent: defaultTpl,
			GollumEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'{{event.payload.pages[0].action}} the {{event.repo.name}} wiki',
					'
',
				].join('\n'),
				body: '
{{page.action}} {{page.title}}.
',
			},
			IssueCommentEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'commented on issue {{event.repo.name}}#{{event.payload.issue.number}}',
					'
',
				].join('\n'),
				body: '
{{event.payload.comment.body | roIgnoreAllAfterFirstNewLine }}
',
			},
			IssuesEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'{{event.payload.action}} issue ',
						'{{ event.repo.name }}#{{event.payload.issue.number}} ',
					'
',
				].join('\n'),
				body: [
					'
{{event.payload.issue.title}}
'
				].join('\n'),
			},
			MemberEvent: {
				heading: [
					'',
						'{{event.actor.login}} added ',
						'{{event.payload.user.login}} ',
						'to {{event.repo.name}} ',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			MembershipEvent: defaultTpl,
			PageBuildEvent: defaultTpl,
			PublicEvent: {
				heading: [
					'',
						'{{event.actor.login}} has made ',
						'{{event.repo.name}} public',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
			PullRequestEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'{{event.payload.action}} pull request ',
						'{{ event.repo.name }}#{{event.payload.pull_request.number}} ',
					'
',
				].join('\n'),
				body: [
					'
',
						'{{event.payload.pull_request.title}}
',
					'
',
					'
',
						'',
							'{{event.payload.pull_request.commits | number}} {{  {true:\'commit\', false:\'commits\'}[event.payload.pull_request.commits==1]  }} with',
							'{{event.payload.pull_request.additions | number}} {{  {true:\'addition\', false:\'additions\'}[event.payload.pull_request.additions==1]  }} and',
							'{{event.payload.pull_request.deletions | number}} {{  {true:\'deletions\', false:\'deletions\'}[event.payload.pull_request.deletions==1]  }}',
						'',
					'
',
				].join('\n'),
			},
			PullRequestReviewCommentEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'commented on a pull request ',
						'{{ event.repo.name }}#{{event.payload.pull_request.number}} ',
					'
',
				].join('\n'),
				body: [
					'
{{event.payload.comment.body | roIgnoreAllAfterFirstDot}}
'
				].join('\n'),
			},
			PushEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'pushed to {{  event.payload.ref | roMakeRef }} ',
						'at {{event.repo.name}}',
					'
',
				].join('\n'),
				body: [
					'
',
						' ',
						'{{commit.sha | limitTo:7}} {{commit.message | roIgnoreAllAfterFirstNewLine }}',
					'
',
					'',
						'{{event.payload.commits.length - 2}} more commits »',
					'',
					'',
						'View comparison for these 2 commits »',
					''
				].join('\n'),
			},
			ReleaseEvent: {
				heading: [
					'
',
						'{{event.actor.login}} ',
						'released {{  event.payload.release.name }} ',
						'at {{event.repo.name}}',
					'
',
				].join('\n'),
				body: [
					'
',
						'Source code (zip)',
					'
',
				].join('\n'),
			},
			RepositoryEvent: defaultTpl,
			StatusEvent: defaultTpl,
			TeamAddEvent: defaultTpl,
			WatchEvent: {
				heading: [
					'',
						'{{event.actor.login}} starred ',
						'{{event.repo.name}}',
						'{{event.created_at | timeAgo}}',
					''
				].join('\n'),
				date: ' ',
				body: ' ',
				avatar: ' ',
			},
		}

		this.$get = function ($resource, $templateCache){
			var Events = $resource('https://api.github.com/users/:username/events/public', null, {cache:true});

			angular.forEach(templates, function (tplValue, tplKey) {
				angular.forEach(tplValue, function (sectionValue, sectionKey){
					var path, url;

					path = templatesNameSpace+'/type-section.html';
					url = path
						.replace('type', tplKey)
						.replace('section', sectionKey);

					$templateCache.put(url, sectionValue);
				});
			});

			return {
				// Github API Services
				events: function (username){
					return 	Events.query({username:username});
				},

				// Gets
				getUser: function (){
					return username;
				},
				getTemplate: function (type, section){
					if(!templates[type] || templates[type] && !templates[type][section]) {
						type = 'default';
						if(!templates[type][section])
							section = 'empty';
					}

					var path = templatesNameSpace+'/type-section.html';
					var url = path
						.replace('type', type)
						.replace('section', section);

					return url;
				},
				getLoader: function (){
					return loader;
				},
				getError: function (){
					return error;
				}
			}

		}
	}

	angular.module('githubEvents.providers', [])
		.provider('githubEvents', GithubEventsProvider);
<|endoftext|>


<commit_before>'use strict';

/**
 * This is where we store the current version number
 * of the client, it's used so nodes can detect when
 * newer versions are available so they can refresh
 */
function FrontendVersionService() {

    var CURRENT_VERSION = 26;

    return {
        getVersion: function() {
            return CURRENT_VERSION;
        }
    };
}

module.exports = FrontendVersionService;<commit_msg>Increment frontend version<commit_after>'use strict';

/**
 * This is where we store the current version number
 * of the client, it's used so nodes can detect when
 * newer versions are available so they can refresh
 */
function FrontendVersionService() {

    var CURRENT_VERSION = 27;

    return {
        getVersion: function() {
            return CURRENT_VERSION;
        }
    };
}

module.exports = FrontendVersionService;<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import axios from 'axios';
import qs from 'qs';
import CONSTS from 'AppData/Constants';
import Configurations from 'Config';
import Utils from './Utils';
import User from './User';
import APIClient from './APIClient';
import APIClientFactory from './APIClientFactory';

/**
 * Class managing authentication
 */
class AuthManager {
    constructor() {
        this.isLogged = false;
        this.username = null;
    }

    /**
     * Refresh the access token and set new access token to the intercepted request
     * @param {Request} request
     * @param {Object} environment
     */
    static refreshTokenOnExpire(request, environment = Utils.getCurrentEnvironment()) {
        const refreshPeriod = 60;
        const user = AuthManager.getUser(environment.label);
        const timeToExpire = Utils.timeDifference(user.getExpiryTime());
        if (timeToExpire >= refreshPeriod) {
            return request;
        }
        if (user.getExpiryTime() < 0) {
            return request;
        }
        const loginPromise = AuthManager.refresh(environment);
        loginPromise.then((response) => {
            const loggedInUser = AuthManager.loginUserMapper(response, environment.label);
            AuthManager.setUser(loggedInUser, environment.label);
        });
        loginPromise.catch((error) => {
            const errorData = JSON.parse(error.responseText);
            const message = 'Error while refreshing token You will be redirect to the login page ...';
            console.error(errorData);
            console.error(message);
        });
        return loginPromise;
    }

    /**
     * Static method to handle unauthorized user action error catch, It will look for response status
     *  code and skip !401 errors
     * @param {object} errorResponse
     */
    static unauthorizedErrorHandler(errorResponse) {
        if (errorResponse.status !== 401) {
            /* Skip unrelated response code to handle in unauthorizedErrorHandler */
            throw errorResponse;
            /* re throwing the error since we don't handle it here and propagate to downstream error
             handlers in catch chain */
        }
        const message = 'The session has expired.
 You will be redirect to the login page ...';

        throw new Error(errorResponse + message);
    }

    /**
     * An user object is return in present of logged in user info in browser local storage, at the same
     *  time checks for partialToken in the cookie as well.
     * This may give a partial indication(passive check not actually check the token validity via an API) of
     *  whether the user has logged in or not, The actual API call may get denied
     * if the cookie stored access token is invalid/expired
     * @param {string} environmentName - label of the environment, the user to be retrieved from
     * @returns {User | null} Is any user has logged in or not
     */
    static getUser(environmentName = Utils.getCurrentEnvironment().label) {
        const userData = localStorage.getItem(`${User.CONST.LOCAL_STORAGE_USER}_${environmentName}`);
        const partialToken = Utils.getCookie(User.CONST.WSO2_AM_TOKEN_1, environmentName);
        const refreshToken = Utils.getCookie(User.CONST.WSO2_AM_REFRESH_TOKEN_1, environmentName);
        if (!(userData && (partialToken || refreshToken))) {
            return null;
        }
        return User.fromJson(JSON.parse(userData), environmentName);
    }

    /**
     * Do token introspection and Get the currently logged in user's details
     * When user authentication happens via redirection flow, This method might get used to
     * retrieve the user information
     * after setting the access token parts in cookies, Because access token parts are stored in /publisher path ,
     * just making an external request in same path will submit both cookies, allowing the service to build the
     * complete access token and do the introspection.
     * Return a promise resolving to user object iff introspect calls return active user else null
     * @static
     * @returns {Promise} fetch response promise resolving to introspect response JSON or null otherwise
     * @memberof AuthManager
     */
    static getUserFromToken() {
        const partialToken = Utils.getCookie(User.CONST.WSO2_AM_TOKEN_1);
        if (!partialToken) {
            return new Promise((resolve, reject) => reject(new Error(CONSTS.errorCodes.NO_TOKEN_FOUND)));
        }
        const introspectUrl = Configurations.app.context + Utils.CONST.INTROSPECT;
        const promisedResponse = fetch(introspectUrl, { credentials: 'same-origin' });
        return promisedResponse
            .then(response => response.json())
            .then((data) => {
                let user = null;
                if (data.active) {
                    const currentEnv = Utils.getCurrentEnvironment();
                    user = new User(currentEnv.label, data.username);
                    const scopes = data.scope.split(' ');
                    if (this.hasBasicLoginPermission(scopes)) {
                        user.scopes = scopes;
                        AuthManager.setUser(user, currentEnv.label);
                    } else {
                        console.warn('The user with ' + partialToken + ' doesn\'t enough have permission!');
                        throw new Error(CONSTS.errorCodes.INSUFFICIENT_PREVILEGES);
                    }
                } else {
                    console.warn('The user with ' + partialToken + ' is not active!');
                    throw new Error(CONSTS.errorCodes.INVALID_TOKEN);
                }
                return user;
            });
    }

    /**
     * Persist an user in browser local storage and in-memory, Since only one use can be
     * logged into the application at a time,
     * This method will override any previously persist user data.
     * @param {User} user - An instance of the {User} class
     * @param {string} environmentName - label of the environment to be set the user
     */
    static setUser(user, environmentName = Utils.getCurrentEnvironment().label) {
        if (!(user instanceof User)) {
            throw new Error('Invalid user object');
        }
        if (user) {
            localStorage.setItem(`${User.CONST.LOCAL_STORAGE_USER}_${environmentName}`, JSON.stringify(user.toJson()));
        }
    }

    /**
     *
     * @param {String} environmentName - Name of the environment the user to be removed
     */
    static dismissUser(environmentName) {
        localStorage.removeItem(`${User.CONST.LOCAL_STORAGE_USER}_${environmentName}`);
        User.destroyInMemoryUser(environmentName);
    }

    /**
     *
     * Get scope for resources
     * @static
     * @param {String} resourcePath
     * @param {String} resourceMethod
     * @returns Boolean
     * @memberof AuthManager
     */
    static hasScopes(resourcePath, resourceMethod) {
        const userscopes = AuthManager.getUser().scopes;
        const validScope = APIClient.getScopeForResource(resourcePath, resourceMethod);
        return validScope.then((scope) => {
            return userscopes.includes(scope);
        });
    }

    static isNotCreator() {
        return !AuthManager.getUser().scopes.includes('apim:api_create');
    }

    static isNotPublisher() {
        return !AuthManager.getUser().scopes.includes('apim:api_publish');
    }

    static isRestricted(scopesAllowedToEdit, api) {
        // determines whether the user is a publisher or creator (based on what is passed from the element)
        // if (scopesAllowedToEdit.filter(element => AuthManager.getUser().scopes.includes(element)).length > 0) {
        if (scopesAllowedToEdit.find(element => AuthManager.getUser().scopes.includes(element))) {
            // if the user has publisher role, no need to consider the api LifeCycleStatus
            if (AuthManager.getUser().scopes.includes('apim:api_publish')) {
                return false;
            } else if (
                // if the user has creator role, but not the publisher role
                api.lifeCycleStatus === 'CREATED') {
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    static hasBasicLoginPermission(scopes) {
        return scopes.includes('apim:api_view');
    }

    /**
     * @deprecated Was used when Basic login facility provided from SPA app
     * By given username and password Authenticate the user, Since this REST API has no swagger definition,
     * Can't use swaggerjs to generate client.Hence using Axios to make AJAX calls
     * @param {String} username - Username of the user
     * @param {String} password - Plain text password
     * @param {Object} environment - environment object
     * @returns {AxiosPromise} - Promise object with the login request made
     */
    authenticateUser(username, password, environment) {
        const headers = {
            Accept: 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
        };
        const data = {
            username,
            password,
            application: 'publisher',
            remember_me: true, // By default always remember user session
        };
        // Set the environment that user tried to authenticate
        const previousEnvironment = Utils.getCurrentEnvironment();
        Utils.setEnvironment(environment);

        const promisedResponse = this.postAuthenticationRequest(headers, data, environment);
        promisedResponse.catch(() => {
            Utils.setEnvironment(previousEnvironment);
        });

        return promisedResponse;
    }

    /**
     * Return an user object given the login request response object
     * @param {Object} response - Response object received from either Axios or Fetch libraries
     * @param {String} environmentName - Name of the environment
     * @returns {User} Instance of an user who is currently logged in (for the selected environment)
     */
    static loginUserMapper(response, environmentName) {
        const { data } = response;
        const { AM_ACC_TOKEN_DEFAULT_P1, expires_in: expiresIn } = data;
        const user = new User(environmentName, data.authUser);
        user.setPartialToken(AM_ACC_TOKEN_DEFAULT_P1, expiresIn, Configurations.app.context);
        user.setExpiryTime(expiresIn);
        user.scopes = data.scopes.split(' ');
        return user;
    }

    /**
     * Revoke the issued OAuth access token for currently logged in user and clear both cookie and local-storage data.
     * @param {String} environmentName - Name of the environment to be logged out. Default current environment.
     * @returns {AxiosPromise}
     */
    logout(environmentName = Utils.getCurrentEnvironment().label) {
        const authHeader = 'Bearer ' + AuthManager.getUser(environmentName).getPartialToken();
        // TODO Will have to change the logout end point url to contain the app context(i.e. publisher/store, etc.)
        const url = Utils.getAppLogoutURL();
        const headers = {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: authHeader,
        };
        const promisedLogout = axios.post(url, null, {
            headers,
        });
        promisedLogout
            .then(() => {
                Utils.deleteCookie(User.CONST.WSO2_AM_TOKEN_1, Configurations.app.context, environmentName);
                AuthManager.dismissUser(environmentName);
                new APIClientFactory().destroyAPIClient(environmentName);
                // Single client should be re initialize after log out
                console.log(`Successfully logout from environment: ${environmentName}`);
            })
            .catch((error) => {
                console.error(`Failed to logout from environment: ${environmentName}`, error);
            });

        return promisedLogout;
    }

    /**
     * Logout current user from all specified environments
     * @param {array} environments - Array of environments
     * @returns {Promise} Promised Logout object of current environment
     */
    logoutFromEnvironments(environments) {
        const currentEnvironmentName = Utils.getCurrentEnvironment().label;
        const currentUser = AuthManager.getUser(currentEnvironmentName).name;

        environments.forEach((environment) => {
            const user = AuthManager.getUser(environment.label);
            if (user && currentUser === user.name && currentEnvironmentName !== environment.label) {
                this.logout(environment.label);
            }
        });

        return this.logout(currentEnvironmentName);
    }

    setupAutoRefresh(environmentName) {
        const user = AuthManager.getUser(environmentName);
        const bufferTime = 1000 * 10; // Give 10 sec buffer time before token expire,
        // considering the network delays and ect.
        const triggerIn = Utils.timeDifference(user.getExpiryTime() - bufferTime);
        if (user) {
            setTimeout(AuthManager.refreshTokenOnExpire, triggerIn * 1000);
        } else {
            throw new Error('No user exist for current session! Needs to login before setting up refresh');
        }
    }

    /**
     * Call Token API with refresh token grant type
     * @param {Object} environment - Name of the environment
     * @return {AxiosPromise}
     */
    static refresh(environment) {
        const params = {
            refresh_token: AuthManager.getUser(environment.label).getRefreshPartialToken(),
            validity_period: -1,
            scopes: AuthManager.CONST.USER_SCOPES,
        };
        const referrer = document.referrer.indexOf('https') !== -1 ? document.referrer : null;
        const url = Configurations.app.context + environment.refreshTokenPath;
        const headers = {
            Accept: 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Alt-Referer': referrer,
        };
        return fetch(url, {
            method: 'POST',
            body: qs.stringify(params),
            headers,
        });
    }

    /**
     * @deprecated Was used when Basic login facility provided from SPA app
     * Send the POST request to the using Axios
     * @param {Object} headers - Header object
     * @param {Object} data - Data object with credentials
     * @param {Object} environment - environment object
     * @returns {Promise} Axios Promise object with the login request made
     */
    postAuthenticationRequest(headers, data, environment) {
        const promisedResponse = axios('/publisher/services/auth/basic', {
            method: 'POST',
            data: qs.stringify(data),
            headers,
            withCredentials: true,
        });

        promisedResponse
            .then((response) => {
                const user = AuthManager.loginUserMapper(response, environment.label);
                AuthManager.setUser(user, environment.label);
                this.setupAutoRefresh(environment.label);
                // remove the swaggerjs api client which could contain old access token if
                // user login back without page reload
                new APIClientFactory().destroyAPIClient(environment.label);
                console.log(`Authentication Success in '${environment.label}' environment.`);
            })
            .catch((error) => {
                console.error(`Authentication Error in '${environment.label}' environment :\n`, error);
            });

        return promisedResponse;
    }
}

// TODO: derive this from swagger definitions ~tmkb
AuthManager.CONST = {
    USER_SCOPES: 'apim:api_view apim:api_create apim:api_publish apim:tier_view apim:tier_manage '
        + 'apim:subscription_view apim:subscription_block apim:subscribe apim:external_services_discover',
};
const { isRestricted } = AuthManager;

export { isRestricted };

export default AuthManager;
<commit_msg>Fix creator edit prototype info issue<commit_after>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import axios from 'axios';
import qs from 'qs';
import CONSTS from 'AppData/Constants';
import Configurations from 'Config';
import Utils from './Utils';
import User from './User';
import APIClient from './APIClient';
import APIClientFactory from './APIClientFactory';

/**
 * Class managing authentication
 */
class AuthManager {
    constructor() {
        this.isLogged = false;
        this.username = null;
    }

    /**
     * Refresh the access token and set new access token to the intercepted request
     * @param {Request} request
     * @param {Object} environment
     */
    static refreshTokenOnExpire(request, environment = Utils.getCurrentEnvironment()) {
        const refreshPeriod = 60;
        const user = AuthManager.getUser(environment.label);
        const timeToExpire = Utils.timeDifference(user.getExpiryTime());
        if (timeToExpire >= refreshPeriod) {
            return request;
        }
        if (user.getExpiryTime() < 0) {
            return request;
        }
        const loginPromise = AuthManager.refresh(environment);
        loginPromise.then((response) => {
            const loggedInUser = AuthManager.loginUserMapper(response, environment.label);
            AuthManager.setUser(loggedInUser, environment.label);
        });
        loginPromise.catch((error) => {
            const errorData = JSON.parse(error.responseText);
            const message = 'Error while refreshing token You will be redirect to the login page ...';
            console.error(errorData);
            console.error(message);
        });
        return loginPromise;
    }

    /**
     * Static method to handle unauthorized user action error catch, It will look for response status
     *  code and skip !401 errors
     * @param {object} errorResponse
     */
    static unauthorizedErrorHandler(errorResponse) {
        if (errorResponse.status !== 401) {
            /* Skip unrelated response code to handle in unauthorizedErrorHandler */
            throw errorResponse;
            /* re throwing the error since we don't handle it here and propagate to downstream error
             handlers in catch chain */
        }
        const message = 'The session has expired.
 You will be redirect to the login page ...';

        throw new Error(errorResponse + message);
    }

    /**
     * An user object is return in present of logged in user info in browser local storage, at the same
     *  time checks for partialToken in the cookie as well.
     * This may give a partial indication(passive check not actually check the token validity via an API) of
     *  whether the user has logged in or not, The actual API call may get denied
     * if the cookie stored access token is invalid/expired
     * @param {string} environmentName - label of the environment, the user to be retrieved from
     * @returns {User | null} Is any user has logged in or not
     */
    static getUser(environmentName = Utils.getCurrentEnvironment().label) {
        const userData = localStorage.getItem(`${User.CONST.LOCAL_STORAGE_USER}_${environmentName}`);
        const partialToken = Utils.getCookie(User.CONST.WSO2_AM_TOKEN_1, environmentName);
        const refreshToken = Utils.getCookie(User.CONST.WSO2_AM_REFRESH_TOKEN_1, environmentName);
        if (!(userData && (partialToken || refreshToken))) {
            return null;
        }
        return User.fromJson(JSON.parse(userData), environmentName);
    }

    /**
     * Do token introspection and Get the currently logged in user's details
     * When user authentication happens via redirection flow, This method might get used to
     * retrieve the user information
     * after setting the access token parts in cookies, Because access token parts are stored in /publisher path ,
     * just making an external request in same path will submit both cookies, allowing the service to build the
     * complete access token and do the introspection.
     * Return a promise resolving to user object iff introspect calls return active user else null
     * @static
     * @returns {Promise} fetch response promise resolving to introspect response JSON or null otherwise
     * @memberof AuthManager
     */
    static getUserFromToken() {
        const partialToken = Utils.getCookie(User.CONST.WSO2_AM_TOKEN_1);
        if (!partialToken) {
            return new Promise((resolve, reject) => reject(new Error(CONSTS.errorCodes.NO_TOKEN_FOUND)));
        }
        const introspectUrl = Configurations.app.context + Utils.CONST.INTROSPECT;
        const promisedResponse = fetch(introspectUrl, { credentials: 'same-origin' });
        return promisedResponse
            .then(response => response.json())
            .then((data) => {
                let user = null;
                if (data.active) {
                    const currentEnv = Utils.getCurrentEnvironment();
                    user = new User(currentEnv.label, data.username);
                    const scopes = data.scope.split(' ');
                    if (this.hasBasicLoginPermission(scopes)) {
                        user.scopes = scopes;
                        AuthManager.setUser(user, currentEnv.label);
                    } else {
                        console.warn('The user with ' + partialToken + ' doesn\'t enough have permission!');
                        throw new Error(CONSTS.errorCodes.INSUFFICIENT_PREVILEGES);
                    }
                } else {
                    console.warn('The user with ' + partialToken + ' is not active!');
                    throw new Error(CONSTS.errorCodes.INVALID_TOKEN);
                }
                return user;
            });
    }

    /**
     * Persist an user in browser local storage and in-memory, Since only one use can be
     * logged into the application at a time,
     * This method will override any previously persist user data.
     * @param {User} user - An instance of the {User} class
     * @param {string} environmentName - label of the environment to be set the user
     */
    static setUser(user, environmentName = Utils.getCurrentEnvironment().label) {
        if (!(user instanceof User)) {
            throw new Error('Invalid user object');
        }
        if (user) {
            localStorage.setItem(`${User.CONST.LOCAL_STORAGE_USER}_${environmentName}`, JSON.stringify(user.toJson()));
        }
    }

    /**
     *
     * @param {String} environmentName - Name of the environment the user to be removed
     */
    static dismissUser(environmentName) {
        localStorage.removeItem(`${User.CONST.LOCAL_STORAGE_USER}_${environmentName}`);
        User.destroyInMemoryUser(environmentName);
    }

    /**
     *
     * Get scope for resources
     * @static
     * @param {String} resourcePath
     * @param {String} resourceMethod
     * @returns Boolean
     * @memberof AuthManager
     */
    static hasScopes(resourcePath, resourceMethod) {
        const userscopes = AuthManager.getUser().scopes;
        const validScope = APIClient.getScopeForResource(resourcePath, resourceMethod);
        return validScope.then((scope) => {
            return userscopes.includes(scope);
        });
    }

    static isNotCreator() {
        return !AuthManager.getUser().scopes.includes('apim:api_create');
    }

    static isNotPublisher() {
        return !AuthManager.getUser().scopes.includes('apim:api_publish');
    }

    static isRestricted(scopesAllowedToEdit, api) {
        // determines whether the user is a publisher or creator (based on what is passed from the element)
        // if (scopesAllowedToEdit.filter(element => AuthManager.getUser().scopes.includes(element)).length > 0) {
        if (scopesAllowedToEdit.find(element => AuthManager.getUser().scopes.includes(element))) {
            // if the user has publisher role, no need to consider the api LifeCycleStatus
            if (AuthManager.getUser().scopes.includes('apim:api_publish')) {
                return false;
            } else if (
                // if the user has creator role, but not the publisher role
                api.lifeCycleStatus === 'CREATED' || api.lifeCycleStatus === 'PROTOTYPED') {
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    static hasBasicLoginPermission(scopes) {
        return scopes.includes('apim:api_view');
    }

    /**
     * @deprecated Was used when Basic login facility provided from SPA app
     * By given username and password Authenticate the user, Since this REST API has no swagger definition,
     * Can't use swaggerjs to generate client.Hence using Axios to make AJAX calls
     * @param {String} username - Username of the user
     * @param {String} password - Plain text password
     * @param {Object} environment - environment object
     * @returns {AxiosPromise} - Promise object with the login request made
     */
    authenticateUser(username, password, environment) {
        const headers = {
            Accept: 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
        };
        const data = {
            username,
            password,
            application: 'publisher',
            remember_me: true, // By default always remember user session
        };
        // Set the environment that user tried to authenticate
        const previousEnvironment = Utils.getCurrentEnvironment();
        Utils.setEnvironment(environment);

        const promisedResponse = this.postAuthenticationRequest(headers, data, environment);
        promisedResponse.catch(() => {
            Utils.setEnvironment(previousEnvironment);
        });

        return promisedResponse;
    }

    /**
     * Return an user object given the login request response object
     * @param {Object} response - Response object received from either Axios or Fetch libraries
     * @param {String} environmentName - Name of the environment
     * @returns {User} Instance of an user who is currently logged in (for the selected environment)
     */
    static loginUserMapper(response, environmentName) {
        const { data } = response;
        const { AM_ACC_TOKEN_DEFAULT_P1, expires_in: expiresIn } = data;
        const user = new User(environmentName, data.authUser);
        user.setPartialToken(AM_ACC_TOKEN_DEFAULT_P1, expiresIn, Configurations.app.context);
        user.setExpiryTime(expiresIn);
        user.scopes = data.scopes.split(' ');
        return user;
    }

    /**
     * Revoke the issued OAuth access token for currently logged in user and clear both cookie and local-storage data.
     * @param {String} environmentName - Name of the environment to be logged out. Default current environment.
     * @returns {AxiosPromise}
     */
    logout(environmentName = Utils.getCurrentEnvironment().label) {
        const authHeader = 'Bearer ' + AuthManager.getUser(environmentName).getPartialToken();
        // TODO Will have to change the logout end point url to contain the app context(i.e. publisher/store, etc.)
        const url = Utils.getAppLogoutURL();
        const headers = {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: authHeader,
        };
        const promisedLogout = axios.post(url, null, {
            headers,
        });
        promisedLogout
            .then(() => {
                Utils.deleteCookie(User.CONST.WSO2_AM_TOKEN_1, Configurations.app.context, environmentName);
                AuthManager.dismissUser(environmentName);
                new APIClientFactory().destroyAPIClient(environmentName);
                // Single client should be re initialize after log out
                console.log(`Successfully logout from environment: ${environmentName}`);
            })
            .catch((error) => {
                console.error(`Failed to logout from environment: ${environmentName}`, error);
            });

        return promisedLogout;
    }

    /**
     * Logout current user from all specified environments
     * @param {array} environments - Array of environments
     * @returns {Promise} Promised Logout object of current environment
     */
    logoutFromEnvironments(environments) {
        const currentEnvironmentName = Utils.getCurrentEnvironment().label;
        const currentUser = AuthManager.getUser(currentEnvironmentName).name;

        environments.forEach((environment) => {
            const user = AuthManager.getUser(environment.label);
            if (user && currentUser === user.name && currentEnvironmentName !== environment.label) {
                this.logout(environment.label);
            }
        });

        return this.logout(currentEnvironmentName);
    }

    setupAutoRefresh(environmentName) {
        const user = AuthManager.getUser(environmentName);
        const bufferTime = 1000 * 10; // Give 10 sec buffer time before token expire,
        // considering the network delays and ect.
        const triggerIn = Utils.timeDifference(user.getExpiryTime() - bufferTime);
        if (user) {
            setTimeout(AuthManager.refreshTokenOnExpire, triggerIn * 1000);
        } else {
            throw new Error('No user exist for current session! Needs to login before setting up refresh');
        }
    }

    /**
     * Call Token API with refresh token grant type
     * @param {Object} environment - Name of the environment
     * @return {AxiosPromise}
     */
    static refresh(environment) {
        const params = {
            refresh_token: AuthManager.getUser(environment.label).getRefreshPartialToken(),
            validity_period: -1,
            scopes: AuthManager.CONST.USER_SCOPES,
        };
        const referrer = document.referrer.indexOf('https') !== -1 ? document.referrer : null;
        const url = Configurations.app.context + environment.refreshTokenPath;
        const headers = {
            Accept: 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Alt-Referer': referrer,
        };
        return fetch(url, {
            method: 'POST',
            body: qs.stringify(params),
            headers,
        });
    }

    /**
     * @deprecated Was used when Basic login facility provided from SPA app
     * Send the POST request to the using Axios
     * @param {Object} headers - Header object
     * @param {Object} data - Data object with credentials
     * @param {Object} environment - environment object
     * @returns {Promise} Axios Promise object with the login request made
     */
    postAuthenticationRequest(headers, data, environment) {
        const promisedResponse = axios('/publisher/services/auth/basic', {
            method: 'POST',
            data: qs.stringify(data),
            headers,
            withCredentials: true,
        });

        promisedResponse
            .then((response) => {
                const user = AuthManager.loginUserMapper(response, environment.label);
                AuthManager.setUser(user, environment.label);
                this.setupAutoRefresh(environment.label);
                // remove the swaggerjs api client which could contain old access token if
                // user login back without page reload
                new APIClientFactory().destroyAPIClient(environment.label);
                console.log(`Authentication Success in '${environment.label}' environment.`);
            })
            .catch((error) => {
                console.error(`Authentication Error in '${environment.label}' environment :\n`, error);
            });

        return promisedResponse;
    }
}

// TODO: derive this from swagger definitions ~tmkb
AuthManager.CONST = {
    USER_SCOPES: 'apim:api_view apim:api_create apim:api_publish apim:tier_view apim:tier_manage '
        + 'apim:subscription_view apim:subscription_block apim:subscribe apim:external_services_discover',
};
const { isRestricted } = AuthManager;

export { isRestricted };

export default AuthManager;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');

String.prototype.toCamelCase = function() {
  return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
    if (p2) return p2.toUpperCase();
    return p1.toLowerCase();
  });
};

gulp.task('default', function(){
  gulp.src(['./icon-font/svgs/*.svg'])

  .pipe(iconfontCss({
    fontName: 'cartoIcon',
    path: './icon-font/template.jst.ejs',
    targetPath: '../scss/_cdb-icon-font.scss',
    fontPath: '../../fonts/'
  }))

  .pipe(iconfont({
    fontName: 'cartoIcon',
    appendCodepoints: true
  }))

  .pipe(gulp.dest('src/fonts/'));
});
<commit_msg>Small touches<commit_after>var gulp = require('gulp');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');

String.prototype.toCamelCase = function () {
  return this.replace(/^([A-Z])|\s(\w)/g, function (match, p1, p2, offset) {
    if (p2) return p2.toUpperCase();
    return p1.toLowerCase();
  });
};

gulp.task('default', function () {
  gulp.src(['./icon-font/svgs/*.svg'])

  .pipe(iconfontCss({
    fontName: 'cartoIcon',
    path: './icon-font/template.jst.ejs',
    targetPath: '../scss/_cdb-icon-font.scss',
    fontPath: '../../fonts/'
  }))

  .pipe(iconfont({
    fontName: 'cartoIcon',
    appendCodepoints: true
  }))

  .pipe(gulp.dest('src/fonts/'));
});
<|endoftext|>


<commit_before>"use strict";

const plumber = require("gulp-plumber");
const through = require("through2");
const chalk = require("chalk");
const newer = require("gulp-newer");
const babel = require("gulp-babel");
const fancyLog = require("fancy-log");
const filter = require("gulp-filter");
const gulp = require("gulp");
const path = require("path");
const rollup = require("rollup");
const rollupBabel = require("@rollup/plugin-babel").default;
const rollupBabelSource = require("./scripts/rollup-plugin-babel-source");
const rollupCommonJs = require("@rollup/plugin-commonjs");
const rollupJson = require("@rollup/plugin-json");
const rollupNodePolyfills = require("rollup-plugin-node-polyfills");
const rollupNodeResolve = require("@rollup/plugin-node-resolve").default;
const rollupReplace = require("@rollup/plugin-replace");
const { terser: rollupTerser } = require("rollup-plugin-terser");

const defaultSourcesGlob = "./@(codemods|packages|eslint)/*/src/**/*.js";

function swapSrcWithLib(srcPath) {
  const parts = srcPath.split(path.sep);
  parts[2] = "lib";
  return parts.join(path.sep);
}

function getIndexFromPackage(name) {
  return `${name}/src/index.js`;
}

function compilationLogger() {
  return through.obj(function (file, enc, callback) {
    fancyLog(`Compiling '${chalk.cyan(file.relative)}'...`);
    callback(null, file);
  });
}

function errorsLogger() {
  return plumber({
    errorHandler(err) {
      fancyLog(err.stack);
    },
  });
}

function rename(fn) {
  return through.obj(function (file, enc, callback) {
    file.path = fn(file);
    callback(null, file);
  });
}

function buildBabel(exclude, sourcesGlob = defaultSourcesGlob) {
  const base = __dirname;

  let stream = gulp.src(sourcesGlob, { base: __dirname });

  if (exclude) {
    const filters = exclude.map(p => `!**/${p.src}/**`);
    filters.unshift("**");
    stream = stream.pipe(filter(filters));
  }

  return stream
    .pipe(errorsLogger())
    .pipe(newer({ dest: base, map: swapSrcWithLib }))
    .pipe(compilationLogger())
    .pipe(
      babel({
        caller: {
          // We have wrapped packages/babel-core/src/config/files/configuration.js with feature detection
          supportsDynamicImport: true,
        },
      })
    )
    .pipe(
      // Passing 'file.relative' because newer() above uses a relative
      // path and this keeps it consistent.
      rename(file => path.resolve(file.base, swapSrcWithLib(file.relative)))
    )
    .pipe(gulp.dest(base));
}

let babelVersion = require("./packages/babel-core/package.json").version;
function buildRollup(packages) {
  const sourcemap = process.env.NODE_ENV === "production";
  const minify = !!process.env.IS_PUBLISH;
  return Promise.all(
    packages.map(
      ({ src, format, dest, name, filename, version = babelVersion }) => {
        const extraPlugins = [];
        let nodeResolveBrowser = false,
          babelEnvName = "rollup";
        switch (src) {
          case "packages/babel-standalone":
            nodeResolveBrowser = true;
            babelEnvName = "standalone";
            if (minify) {
              extraPlugins.push(
                rollupTerser({
                  // workaround https://bugs.webkit.org/show_bug.cgi?id=212725
                  output: {
                    ascii_only: true,
                  },
                })
              );
            }
            break;
        }
        // If this build is part of a pull request, include the pull request number in
        // the version number.
        if (process.env.CIRCLE_PR_NUMBER) {
          const prVersion = "+pr." + process.env.CIRCLE_PR_NUMBER;
          babelVersion += prVersion;
          version += prVersion;
        }
        const input = getIndexFromPackage(src);
        fancyLog(`Compiling '${chalk.cyan(input)}' with rollup ...`);
        return rollup
          .rollup({
            input,
            plugins: [
              ...extraPlugins,
              rollupBabelSource(),
              rollupReplace({
                "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
                BABEL_VERSION: JSON.stringify(babelVersion),
                VERSION: JSON.stringify(version),
              }),
              rollupBabel({
                envName: babelEnvName,
                babelrc: false,
                babelHelpers: "bundled",
                extends: "./babel.config.js",
              }),
              rollupNodeResolve({
                browser: nodeResolveBrowser,
                preferBuiltins: true,
                //todo: remove when semver and source-map are bumped to latest versions
                dedupe(importee) {
                  return ["semver", "source-map"].includes(importee);
                },
              }),
              rollupCommonJs({
                include: [
                  /node_modules/,
                  "packages/babel-runtime/regenerator/**",
                  "packages/babel-preset-env/data/*.js",
                  // Rollup doesn't read export maps, so it loads the cjs fallback
                  "packages/babel-compat-data/*.js",
                ],
              }),
              rollupJson(),
              rollupNodePolyfills({
                sourceMap: sourcemap,
                include: "**/*.js",
              }),
            ],
          })
          .then(bundle => {
            const outputFile = path.resolve(src, dest, filename || "index.js");
            return bundle
              .write({
                file: outputFile,
                format,
                name,
                sourcemap: sourcemap,
              })
              .then(() => {
                if (!process.env.IS_PUBLISH) {
                  fancyLog(
                    chalk.yellow(
                      `Skipped minification of '${chalk.cyan(
                        path.relative(path.join(__dirname, ".."), outputFile)
                      )}' because not publishing`
                    )
                  );
                  return undefined;
                }
                fancyLog(
                  `Minifying '${chalk.cyan(
                    path.relative(path.join(__dirname, ".."), outputFile)
                  )}'...`
                );

                return bundle.write({
                  file: outputFile.replace(/\.js$/, ".min.js"),
                  format,
                  name,
                  sourcemap: sourcemap,
                });
              });
          });
      }
    )
  );
}

const libBundles = [
  {
    src: "packages/babel-parser",
    format: "cjs",
    dest: "lib",
    version: require("./packages/babel-parser/package").version,
  },
];

const standaloneBundle = [
  {
    src: "packages/babel-standalone",
    format: "umd",
    name: "Babel",
    filename: "babel.js",
    dest: "",
    version: require("./packages/babel-core/package").version,
  },
];

gulp.task("build-rollup", () => buildRollup(libBundles));
gulp.task("build-babel-standalone", () => buildRollup(standaloneBundle));

gulp.task("build-babel", () => buildBabel(/* exclude */ libBundles));
gulp.task("build", gulp.parallel("build-rollup", "build-babel"));

gulp.task("default", gulp.series("build"));

gulp.task("build-no-bundle", () => buildBabel());

gulp.task(
  "watch",
  gulp.series("build-no-bundle", function watch() {
    gulp.watch(defaultSourcesGlob, gulp.task("build-no-bundle"));
  })
);
<commit_msg>fix: apply terser plugin only on *.min.js (#12099)<commit_after>"use strict";

const plumber = require("gulp-plumber");
const through = require("through2");
const chalk = require("chalk");
const newer = require("gulp-newer");
const babel = require("gulp-babel");
const fancyLog = require("fancy-log");
const filter = require("gulp-filter");
const gulp = require("gulp");
const path = require("path");
const rollup = require("rollup");
const rollupBabel = require("@rollup/plugin-babel").default;
const rollupBabelSource = require("./scripts/rollup-plugin-babel-source");
const rollupCommonJs = require("@rollup/plugin-commonjs");
const rollupJson = require("@rollup/plugin-json");
const rollupNodePolyfills = require("rollup-plugin-node-polyfills");
const rollupNodeResolve = require("@rollup/plugin-node-resolve").default;
const rollupReplace = require("@rollup/plugin-replace");
const { terser: rollupTerser } = require("rollup-plugin-terser");

const defaultSourcesGlob = "./@(codemods|packages|eslint)/*/src/**/*.js";

function swapSrcWithLib(srcPath) {
  const parts = srcPath.split(path.sep);
  parts[2] = "lib";
  return parts.join(path.sep);
}

function getIndexFromPackage(name) {
  return `${name}/src/index.js`;
}

function compilationLogger() {
  return through.obj(function (file, enc, callback) {
    fancyLog(`Compiling '${chalk.cyan(file.relative)}'...`);
    callback(null, file);
  });
}

function errorsLogger() {
  return plumber({
    errorHandler(err) {
      fancyLog(err.stack);
    },
  });
}

function rename(fn) {
  return through.obj(function (file, enc, callback) {
    file.path = fn(file);
    callback(null, file);
  });
}

function buildBabel(exclude, sourcesGlob = defaultSourcesGlob) {
  const base = __dirname;

  let stream = gulp.src(sourcesGlob, { base: __dirname });

  if (exclude) {
    const filters = exclude.map(p => `!**/${p.src}/**`);
    filters.unshift("**");
    stream = stream.pipe(filter(filters));
  }

  return stream
    .pipe(errorsLogger())
    .pipe(newer({ dest: base, map: swapSrcWithLib }))
    .pipe(compilationLogger())
    .pipe(
      babel({
        caller: {
          // We have wrapped packages/babel-core/src/config/files/configuration.js with feature detection
          supportsDynamicImport: true,
        },
      })
    )
    .pipe(
      // Passing 'file.relative' because newer() above uses a relative
      // path and this keeps it consistent.
      rename(file => path.resolve(file.base, swapSrcWithLib(file.relative)))
    )
    .pipe(gulp.dest(base));
}

// If this build is part of a pull request, include the pull request number in
// the version number.
let versionSuffix = "";
if (process.env.CIRCLE_PR_NUMBER) {
  versionSuffix = "+pr." + process.env.CIRCLE_PR_NUMBER;
}

const babelVersion =
  require("./packages/babel-core/package.json").version + versionSuffix;
function buildRollup(packages) {
  const sourcemap = process.env.NODE_ENV === "production";
  return Promise.all(
    packages.map(async ({ src, format, dest, name, filename, version }) => {
      let nodeResolveBrowser = false,
        babelEnvName = "rollup";
      switch (src) {
        case "packages/babel-standalone":
          nodeResolveBrowser = true;
          babelEnvName = "standalone";
          break;
      }
      const input = getIndexFromPackage(src);
      fancyLog(`Compiling '${chalk.cyan(input)}' with rollup ...`);
      const bundle = await rollup.rollup({
        input,
        plugins: [
          rollupBabelSource(),
          rollupReplace({
            "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
            BABEL_VERSION: JSON.stringify(babelVersion),
            VERSION: JSON.stringify(version),
          }),
          rollupBabel({
            envName: babelEnvName,
            babelrc: false,
            babelHelpers: "bundled",
            extends: "./babel.config.js",
          }),
          rollupNodeResolve({
            browser: nodeResolveBrowser,
            preferBuiltins: true,
            //todo: remove when semver and source-map are bumped to latest versions
            dedupe(importee) {
              return ["semver", "source-map"].includes(importee);
            },
          }),
          rollupCommonJs({
            include: [
              /node_modules/,
              "packages/babel-runtime/regenerator/**",
              "packages/babel-preset-env/data/*.js",
              // Rollup doesn't read export maps, so it loads the cjs fallback
              "packages/babel-compat-data/*.js",
            ],
          }),
          rollupJson(),
          rollupNodePolyfills({
            sourceMap: sourcemap,
            include: "**/*.js",
          }),
        ],
      });

      const outputFile = path.join(src, dest, filename || "index.js");
      await bundle.write({
        file: outputFile,
        format,
        name,
        sourcemap: sourcemap,
      });

      if (!process.env.IS_PUBLISH) {
        fancyLog(
          chalk.yellow(
            `Skipped minification of '${chalk.cyan(
              outputFile
            )}' because not publishing`
          )
        );
        return undefined;
      }
      fancyLog(`Minifying '${chalk.cyan(outputFile)}'...`);

      await bundle.write({
        file: outputFile.replace(/\.js$/, ".min.js"),
        format,
        name,
        sourcemap: sourcemap,
        plugins: [
          rollupTerser({
            // workaround https://bugs.webkit.org/show_bug.cgi?id=212725
            output: {
              ascii_only: true,
            },
          }),
        ],
      });
    })
  );
}

const libBundles = [
  {
    src: "packages/babel-parser",
    format: "cjs",
    dest: "lib",
    version: require("./packages/babel-parser/package").version + versionSuffix,
  },
];

const standaloneBundle = [
  {
    src: "packages/babel-standalone",
    format: "umd",
    name: "Babel",
    filename: "babel.js",
    dest: "",
    version: babelVersion,
  },
];

gulp.task("build-rollup", () => buildRollup(libBundles));
gulp.task("build-babel-standalone", () => buildRollup(standaloneBundle));

gulp.task("build-babel", () => buildBabel(/* exclude */ libBundles));
gulp.task("build", gulp.parallel("build-rollup", "build-babel"));

gulp.task("default", gulp.series("build"));

gulp.task("build-no-bundle", () => buildBabel());

gulp.task(
  "watch",
  gulp.series("build-no-bundle", function watch() {
    gulp.watch(defaultSourcesGlob, gulp.task("build-no-bundle"));
  })
);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var mocha = require('gulp-mocha');

gulp.task('jshint', function() {
    gulp.src(['src/**/*.js', 'tests/**/*.js', 'Gulpfile.js'])
        .pipe(jshint())
        .pipe(jshint.reporter(stylish))
        .pipe(jshint.reporter('fail'));
});

gulp.task('compress', function() {
    gulp.src('src/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('build'));
});

gulp.task('test', function() {
    gulp.src('tests/**/*.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:add', function() {
    gulp.src('tests/matrix.add.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:identity', function() {
    gulp.src('tests/matrix.identity.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:multiply', function() {
    gulp.src('tests/matrix.multiply.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:transpose', function() {
    gulp.src('tests/matrix.transpose.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:valid', function() {
    gulp.src('tests/matrix.valid.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('default', ['jshint', 'test', 'compress']);<commit_msg>added gulp task to test matrix.determinant<commit_after>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var mocha = require('gulp-mocha');

gulp.task('jshint', function() {
    gulp.src(['src/**/*.js', 'tests/**/*.js', 'Gulpfile.js'])
        .pipe(jshint())
        .pipe(jshint.reporter(stylish))
        .pipe(jshint.reporter('fail'));
});

gulp.task('compress', function() {
    gulp.src('src/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('build'));
});

gulp.task('test', function() {
    gulp.src('tests/**/*.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:add', function() {
    gulp.src('tests/matrix.add.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:determinant', function() {
    gulp.src('tests/matrix.determinant.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:identity', function() {
    gulp.src('tests/matrix.identity.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:multiply', function() {
    gulp.src('tests/matrix.multiply.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:transpose', function() {
    gulp.src('tests/matrix.transpose.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('test:matrix:valid', function() {
    gulp.src('tests/matrix.valid.tests.js', { read: false })
        .pipe(mocha());
});

gulp.task('default', ['jshint', 'test', 'compress']);<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');

gulp.task('default', function() {
    gulp.src('./css/*.css')
        .pipe(concat('app.min.css'))
        .pipe(gulp.dest('./dist/css/'));
});
<commit_msg>Change spacing<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');

gulp.task('default', function() {
  gulp.src('./css/*.css')
    .pipe(concat('app.min.css'))
    .pipe(gulp.dest('./dist/css/'));
});
<|endoftext|>


<commit_before>var gulp          = require('gulp');
var eslint        = require('gulp-eslint');
var gulpStyleLint = require('gulp-stylelint');
var browserSync   = require('browser-sync').create();
var sass          = require('gulp-sass');
var autoprefixer  = require('gulp-autoprefixer');
var notify        = require('gulp-notify');
var babelify      = require('babelify');
var browserify    = require('browserify');
var source        = require('vinyl-source-stream');
var buffer        = require('vinyl-buffer');
var sourcemaps    = require('gulp-sourcemaps');

// Static Server + watching scss/html files
gulp.task('serve', ['sass', 'js'], function() {
    browserSync.init({
        server: './public'
    });
    gulp.watch('app/**/*.scss', ['sass']);
    gulp.watch('app/**/*.js', ['js']);
    gulp.watch('public/*.html').on('change', browserSync.reload);
});

// Run lint for sass
gulp.task('lint-css', function lintCssTask() {
  return gulp.src('./app/main.scss')
    .pipe(gulpStyleLint({
      reporters: [
        {formatter: 'string', console: true}
      ]
    }));
});
// Run lint for js
gulp.task('jslint', function() {
  return gulp.src(['app/**/*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src('./app/main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public/css'))
        .pipe(browserSync.stream())
        .pipe(notify({message: 'CSS created!', onLast: true}));
});

// Transpile ES6 js (React app) into JS & auto-inject into browsers
gulp.task('js', ['jslint'], function() {
    var bundler = browserify('./app/app.js').transform("babelify", {presets: ["es2015", "react"]});
    return bundler.bundle()
        .on('error', function(err) { console.error(err); this.emit('end'); })
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public/js/'))
        .pipe(browserSync.stream())
        .pipe(notify({message: 'JS bundle created!', onLast: true}));
});

// Tasks
gulp.task('default', ['serve']);
<commit_msg>Added stylelint and jslint to watch<commit_after>var gulp          = require('gulp');
var eslint        = require('gulp-eslint');
var gulpStyleLint = require('gulp-stylelint');
var browserSync   = require('browser-sync').create();
var sass          = require('gulp-sass');
var autoprefixer  = require('gulp-autoprefixer');
var notify        = require('gulp-notify');
var babelify      = require('babelify');
var browserify    = require('browserify');
var source        = require('vinyl-source-stream');
var buffer        = require('vinyl-buffer');
var sourcemaps    = require('gulp-sourcemaps');

// Static Server + watching scss/html files
gulp.task('serve', ['sass', 'js'], function() {
    browserSync.init({
        server: './public'
    });
    gulp.watch('app/**/*.scss', ['sass', 'stylelint']);
    gulp.watch('app/**/*.js', ['js', 'jslint']);
    gulp.watch('public/*.html').on('change', browserSync.reload);
});

// Run lint for sass
gulp.task('stylelint', function lintCssTask() {
  return gulp.src('./app/main.scss')
    .pipe(gulpStyleLint({
      reporters: [
        {formatter: 'string', console: true}
      ]
    }));
});

// Run lint for js
gulp.task('jslint', function() {
  return gulp.src(['app/**/*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src('./app/main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public/css'))
        .pipe(browserSync.stream())
        .pipe(notify({message: 'CSS created!', onLast: true}));
});

// Transpile ES6 js (React app) into JS & auto-inject into browsers
gulp.task('js', ['jslint'], function() {
    var bundler = browserify('./app/app.js').transform("babelify", {presets: ["es2015", "react"]});
    return bundler.bundle()
        .on('error', function(err) { console.error(err); this.emit('end'); })
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public/js/'))
        .pipe(browserSync.stream())
        .pipe(notify({message: 'JS bundle created!', onLast: true}));
});

// Tasks
gulp.task('default', ['serve']);
<|endoftext|>


<commit_before>
/*!
 * gulp
 * $ npm install gulp-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
 */

// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');
    sourcemaps = require('gulp-sourcemaps');

// Styles
gulp.task('styles', function() {
  gulp.src('./src/assets/styles/main.scss', { sourcemap: true, style: 'expanded' })
    .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

// Scripts
gulp.task('scripts', function() {
  return gulp.src('src/assets/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(addsrc('src/assets/vendor/jquery/dist/jquery.min.js'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(notify({ message: 'Scripts task complete' }));
});

// Images
gulp.task('images', function() {
  return gulp.src('src/assets/images/**/*')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(gulp.dest('dist/assets/img'))
    .pipe(notify({ message: 'Images task complete' }));
});

// Clean
gulp.task('clean', function() {
  return del(['dist/assets/css', 'dist/assests/js', 'dist/assests/img']);
});

// Default task
gulp.task('default', ['clean'], function() {
  gulp.start('styles', 'scripts', 'images');
});

// Watch
gulp.task('watch', function() {

  // Watch .scss files
  gulp.watch('src/assests/styles/**/*.scss', ['styles']);

  // Watch .js files
  gulp.watch('src/assests/scripts/**/*.js', ['scripts']);

  // Watch image files
  gulp.watch('src/assests/images/**/*', ['images']);

  // Create LiveReload server
  livereload.listen();

  // Watch any files in dist/, reload on change
  gulp.watch(['dist/**']).on('change', livereload.changed);

});
<commit_msg>Require gulp-add-src<commit_after>
/*!
 * gulp
 * $ npm install gulp-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
 */

// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');
    sourcemaps = require('gulp-sourcemaps');
    addsrc = require('gulp-add-src');

// Styles
gulp.task('styles', function() {
  gulp.src('./src/assets/styles/main.scss', { sourcemap: true, style: 'expanded' })
    .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

// Scripts
gulp.task('scripts', function() {
  return gulp.src('src/assets/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(addsrc('src/assets/vendor/jquery/dist/jquery.min.js'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(notify({ message: 'Scripts task complete' }));
});

// Images
gulp.task('images', function() {
  return gulp.src('src/assets/images/**/*')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(gulp.dest('dist/assets/img'))
    .pipe(notify({ message: 'Images task complete' }));
});

// Clean
gulp.task('clean', function() {
  return del(['dist/assets/css', 'dist/assests/js', 'dist/assests/img']);
});

// Default task
gulp.task('default', ['clean'], function() {
  gulp.start('styles', 'scripts', 'images');
});

// Watch
gulp.task('watch', function() {

  // Watch .scss files
  gulp.watch('src/assests/styles/**/*.scss', ['styles']);

  // Watch .js files
  gulp.watch('src/assests/scripts/**/*.js', ['scripts']);

  // Watch image files
  gulp.watch('src/assests/images/**/*', ['images']);

  // Create LiveReload server
  livereload.listen();

  // Watch any files in dist/, reload on change
  gulp.watch(['dist/**']).on('change', livereload.changed);

});
<|endoftext|>


<commit_before>var gulp = require('gulp');

var concat = require('gulp-concat');
var concatSourcemap = require('gulp-concat-sourcemap');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var changed = require('gulp-changed');
var rename = require('gulp-rename');
var cmq = require('gulp-combine-media-queries');
var uncss = require('gulp-uncss');
var cssmin = require('gulp-cssmin');
var zopfli = require("gulp-zopfli");
var download = require('download');
var clean = require('gulp-clean');
var xml2js = require('gulp-xml2js');

var files = [];

var paths = {
  scripts: 'js/**/*.js',
  styles: 'scss/**/*.scss',
  images: 'img/**/*'
};

gulp.task('styles', function() {
    return gulp.src(paths.styles)
      .pipe(sass({
        errLogToConsole: true,
        sourceComments: 'map',
        outputStyle: 'expanded'
      }))
      .pipe(gulp.dest('assets/css'));
});

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(concatSourcemap('scripts.js', {
      sourcesContent: true
    }))
    .pipe(gulp.dest('assets/js'));
});

gulp.task('styles-build', ['find-site-files'], function() {
  return gulp.src(paths.styles)
    .pipe(rename({suffix: '.min'}))
    .pipe(sass({
      errLogToConsole: true,
      outputStyle: 'compressed'
    }))
    .pipe(cmq({ log: true }))
    .pipe(uncss({
        html: files
    }))
    .pipe(cssmin())
    .pipe(gulp.dest('assets/css'))
    .pipe(zopfli())
    .pipe(gulp.dest('assets/css'));
})

gulp.task('scripts-build', function() {
  return gulp.src(paths.scripts)
    .pipe(concat('scripts.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('assets/js'))
    .pipe(zopfli())
    .pipe(gulp.dest('assets/js'));
});

gulp.task('images', function() {
 return gulp.src(paths.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      optimizationLevel: 7
    }))
    .pipe(gulp.dest('assets/img'));
});

// Rerun the task when a file changes
gulp.task('watch', function() {
  var server = livereload();

  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.styles, ['styles']);
  gulp.watch(paths.images, ['images']);

  gulp.watch('assets/**').on('change', function(file) {
      server.changed(file.path);
  });
});

gulp.task('download-sitemap', function(callback) {
  dl = download({
    url: 'http://jegtnes.co.uk/rss',
    name: 'rss.xml'
  }, './')

  dl.once('close', function() {
    callback();
  });
});

gulp.task('create-sitemap', ['download-sitemap'], function(cb) {
    return gulp.src('./rss.xml')
    .pipe(xml2js())
    .pipe(rename('rss.json'))
    .pipe(gulp.dest('./'));
});

gulp.task('find-site-files', ['create-sitemap'], function() {
  var json = require('./rss.json');
  json.rss.channel[0].item.forEach(function(value) {
    link = value.link[0]
    files.push(link);
  })

  return gulp.src(['rss.json', 'rss.xml'], {read: false})
    .pipe(clean());
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['styles', 'scripts', 'images']);

// Run this before deploy
gulp.task('build', ['styles-build', 'scripts-build', 'images']);
<commit_msg>Updated Gulpfile to respect styleguide and index pages<commit_after>var gulp = require('gulp');

var concat = require('gulp-concat');
var concatSourcemap = require('gulp-concat-sourcemap');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var changed = require('gulp-changed');
var rename = require('gulp-rename');
var cmq = require('gulp-combine-media-queries');
var uncss = require('gulp-uncss');
var cssmin = require('gulp-cssmin');
var zopfli = require("gulp-zopfli");
var download = require('download');
var clean = require('gulp-clean');
var xml2js = require('gulp-xml2js');

var files = [
              'http://jegtnes.co.uk',
              'http://jegtnes.co.uk/styleguide'
            ];

var paths = {
  scripts: 'js/**/*.js',
  styles: 'scss/**/*.scss',
  images: 'img/**/*'
};

gulp.task('styles', function() {
    return gulp.src(paths.styles)
      .pipe(sass({
        errLogToConsole: true,
        sourceComments: 'map',
        outputStyle: 'expanded'
      }))
      .pipe(gulp.dest('assets/css'));
});

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(concatSourcemap('scripts.js', {
      sourcesContent: true
    }))
    .pipe(gulp.dest('assets/js'));
});

gulp.task('styles-build', ['find-site-files'], function() {
  return gulp.src(paths.styles)
    .pipe(rename({suffix: '.min'}))
    .pipe(sass({
      errLogToConsole: true,
      outputStyle: 'compressed'
    }))
    .pipe(cmq({ log: true }))
    .pipe(uncss({
        html: files
    }))
    .pipe(cssmin())
    .pipe(gulp.dest('assets/css'))
    .pipe(zopfli())
    .pipe(gulp.dest('assets/css'));
})

gulp.task('scripts-build', function() {
  return gulp.src(paths.scripts)
    .pipe(concat('scripts.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('assets/js'))
    .pipe(zopfli())
    .pipe(gulp.dest('assets/js'));
});

gulp.task('images', function() {
 return gulp.src(paths.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      optimizationLevel: 7
    }))
    .pipe(gulp.dest('assets/img'));
});

// Rerun the task when a file changes
gulp.task('watch', function() {
  var server = livereload();

  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.styles, ['styles']);
  gulp.watch(paths.images, ['images']);

  gulp.watch('assets/**').on('change', function(file) {
      server.changed(file.path);
  });
});

gulp.task('download-sitemap', function(callback) {
  dl = download({
    url: 'http://jegtnes.co.uk/rss',
    name: 'rss.xml'
  }, './')

  dl.once('close', function() {
    callback();
  });
});

gulp.task('create-sitemap', ['download-sitemap'], function(cb) {
    return gulp.src('./rss.xml')
    .pipe(xml2js())
    .pipe(rename('rss.json'))
    .pipe(gulp.dest('./'));
});

gulp.task('find-site-files', ['create-sitemap'], function() {
  var json = require('./rss.json');
  json.rss.channel[0].item.forEach(function(value) {
    link = value.link[0]
    files.push(link);
  })

  return gulp.src(['rss.json', 'rss.xml'], {read: false})
    .pipe(clean());
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['styles', 'scripts', 'images']);

// Run this before deploy
gulp.task('build', ['styles-build', 'scripts-build', 'images']);
<|endoftext|>


<commit_before>var gulp=require("gulp");
var uglify=require("gulp-uglify");
var rimraf=require("rimraf");
var imagemin=require("gulp-imagemin");
var minifyCSS=require("gulp-minify-css");
var fs=require("fs");
var EasyZip=require("easy-zip").EasyZip;
var filesize=require("filesize");

gulp.task("clean",function(cb){
  rimraf("build",cb);
});

gulp.task("javascript",function(){
  return gulp.src("src/index.js")
    .pipe(uglify())
    .pipe(gulp.dest("build/"));
});

gulp.task("html",function(){
  return gulp.src("src/index.html")
    .pipe(gulp.dest("build/"));
});

gulp.task("css",function(){
  return gulp.src("src/index.css")
    .pipe(minifyCSS())
    .pipe(gulp.dest("build/"));
});

gulp.task("zip",function(cb){
  var zip=new EasyZip();
  zip.zipFolder("build/",function(){
    zip.writeToFile("miss-city.zip",cb);
  },{rootFolder: "/"});
});

gulp.task("check-size",function(cb){
  var stats=fs.statSync("miss-city.zip");
  var size=stats["size"];
  console.log("ZIP size is: "+filesize(size));
  if(filesize(size,{output: "array"})[0] > 13){
    console.log("Size is over 13kb. Please clean!!");
  }
  cb();
});

gulp.task("images",function(){
  return gulp.src("res/*.gif")
    .pipe(imagemin())
    .pipe(gulp.dest("build/"));
});

gulp.task("default",["clean","javascript","html","css","images","zip","check-size"]);
<commit_msg>Good parallel<commit_after>var gulp=require("gulp");
var uglify=require("gulp-uglify");
var rimraf=require("rimraf");
var imagemin=require("gulp-imagemin");
var minifyCSS=require("gulp-minify-css");
var fs=require("fs");
var EasyZip=require("easy-zip").EasyZip;
var filesize=require("filesize");

gulp.task("clean",function(cb){
  rimraf("build",cb);
});

gulp.task("javascript",function(){
  return gulp.src("src/index.js")
    .pipe(uglify())
    .pipe(gulp.dest("build/"));
});

gulp.task("html",function(){
  return gulp.src("src/index.html")
    .pipe(gulp.dest("build/"));
});

gulp.task("css",function(){
  return gulp.src("src/index.css")
    .pipe(minifyCSS())
    .pipe(gulp.dest("build/"));
});

gulp.task("zip",["html","css","javascript","images"],function(cb){
  var zip=new EasyZip();
  zip.zipFolder("build/",function(){
    zip.writeToFile("miss-city.zip",cb);
  },{rootFolder: "/"});
});

gulp.task("check-size",function(cb){
  var stats=fs.statSync("miss-city.zip");
  var size=stats["size"];
  console.log("ZIP size is: "+filesize(size));
  if(filesize(size,{output: "array"})[0] > 13){
    console.log("Size is over 13kb. Please clean!!");
  }
  cb();
});

gulp.task("images",function(){
  return gulp.src("res/*.gif")
    .pipe(imagemin())
    .pipe(gulp.dest("build/"));
});

gulp.task("default",["zip","check-size"]);
<|endoftext|>