<commit_before>import React from 'react';
import {BackHandler} from 'react-native';
import {StateNavigator, StateContext} from 'navigation';
import {NavigationContext} from 'navigation-react';

class NavigationMotion extends React.Component {
    constructor(props) {
        super(props);
        this.state = {navigationEvent: null};
        this.handleBack = this.handleBack.bind(this);
    }
    static defaultProps = {
        crumb: 0,
        tab: 0,
        renderScene: (state, data) => state.renderScene(data)
    }
    static getDerivedStateFromProps(props, {navigationEvent: prevNavigationEvent}) {
        var {crumb, navigationEvent} = props;
        var {state, crumbs} = navigationEvent.stateNavigator.stateContext;
        if (state && crumbs.length === crumb)
            return {navigationEvent};
        if (state && !prevNavigationEvent && crumb < crumbs.length) {
            var {stateNavigator} = navigationEvent;
            var caretakerNavigator = new StateNavigator(stateNavigator, stateNavigator.historyManager);
            caretakerNavigator.stateContext = NavigationMotion.createStateContext(crumbs, crumb);
            caretakerNavigator.configure = stateNavigator.configure;
            caretakerNavigator.onBeforeNavigate = stateNavigator.onBeforeNavigate;
            caretakerNavigator.offBeforeNavigate = stateNavigator.offBeforeNavigate;
            caretakerNavigator.onNavigate = stateNavigator.onNavigate;
            caretakerNavigator.offNavigate = stateNavigator.offNavigate;
            caretakerNavigator.navigateLink = stateNavigator.navigateLink.bind(stateNavigator);
            var {oldState, state, data, asyncData} = caretakerNavigator.stateContext;
            return {navigationEvent: {oldState, state, data, asyncData, stateNavigator: caretakerNavigator}};
        }
        return null;
    }
    static createStateContext(crumbs, crumb) {
        var stateContext = new StateContext();
        var {state, data, url, title} = crumbs[crumb];
        stateContext.state = state;
        stateContext.data = data;
        stateContext.url = url;
        stateContext.title = title;
        stateContext.crumbs = crumbs.slice(0, crumb);
        stateContext.nextCrumb = crumbs[crumb];
        if (crumb > 1) {
            var {state, data, url} = crumbs[crumb - 1];
            stateContext.previousState = stateContext.oldState = state;
            stateContext.previousData = stateContext.oldData = data;
            stateContext.previousUrl = stateContext.oldUrl = url;
        }
        return stateContext;
    }
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBack);
    }
    shouldComponentUpdate(props, state) {
        return state.navigationEvent === props.navigationEvent;
    }
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
    }
    handleBack() {
        var {navigationEvent} = this.state;
        if (navigationEvent && navigationEvent.stateNavigator.canNavigateBack(1)) {
            this.state.navigationEvent.stateNavigator.navigateBack(1);
            return true;
        }
        return false;
}
    render() {
        var {navigationEvent} = this.state;
        if (!navigationEvent) return null;
        var {state, data} = navigationEvent.stateNavigator.stateContext;
        return (
            <NavigationContext.Provider value={navigationEvent}>
                {this.props.renderScene(state, data)}
            </NavigationContext.Provider>
        );
    }
}

export default props => (
    <NavigationContext.Consumer>
        {(navigationEvent) => <NavigationMotion navigationEvent={navigationEvent} {...props} />}
    </NavigationContext.Consumer>
)
<commit_msg>Tweaked format<commit_after>import React from 'react';
import {BackHandler} from 'react-native';
import {StateNavigator, StateContext} from 'navigation';
import {NavigationContext} from 'navigation-react';

class NavigationMotion extends React.Component {
    constructor(props) {
        super(props);
        this.state = {navigationEvent: null};
        this.handleBack = this.handleBack.bind(this);
    }
    static defaultProps = {
        crumb: 0,
        tab: 0,
        renderScene: (state, data) => state.renderScene(data)
    }
    static getDerivedStateFromProps(props, {navigationEvent: prevNavigationEvent}) {
        var {crumb, navigationEvent} = props;
        var {state, crumbs} = navigationEvent.stateNavigator.stateContext;
        if (state && crumbs.length === crumb)
            return {navigationEvent};
        if (state && !prevNavigationEvent && crumb < crumbs.length) {
            var {stateNavigator} = navigationEvent;
            var caretakerNavigator = new StateNavigator(stateNavigator, stateNavigator.historyManager);
            caretakerNavigator.stateContext = NavigationMotion.createStateContext(crumbs, crumb);
            caretakerNavigator.configure = stateNavigator.configure;
            caretakerNavigator.onBeforeNavigate = stateNavigator.onBeforeNavigate;
            caretakerNavigator.offBeforeNavigate = stateNavigator.offBeforeNavigate;
            caretakerNavigator.onNavigate = stateNavigator.onNavigate;
            caretakerNavigator.offNavigate = stateNavigator.offNavigate;
            caretakerNavigator.navigateLink = stateNavigator.navigateLink.bind(stateNavigator);
            var {oldState, state, data, asyncData} = caretakerNavigator.stateContext;
            return {navigationEvent: {oldState, state, data, asyncData, stateNavigator: caretakerNavigator}};
        }
        return null;
    }
    static createStateContext(crumbs, crumb) {
        var stateContext = new StateContext();
        var {state, data, url, title} = crumbs[crumb];
        stateContext.state = state;
        stateContext.data = data;
        stateContext.url = url;
        stateContext.title = title;
        stateContext.crumbs = crumbs.slice(0, crumb);
        stateContext.nextCrumb = crumbs[crumb];
        if (crumb > 1) {
            var {state, data, url} = crumbs[crumb - 1];
            stateContext.previousState = stateContext.oldState = state;
            stateContext.previousData = stateContext.oldData = data;
            stateContext.previousUrl = stateContext.oldUrl = url;
        }
        return stateContext;
    }
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBack);
    }
    shouldComponentUpdate(props, state) {
        return state.navigationEvent === props.navigationEvent;
    }
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
    }
    handleBack() {
        var {navigationEvent} = this.state;
        if (navigationEvent && navigationEvent.stateNavigator.canNavigateBack(1)) {
            navigationEvent.stateNavigator.navigateBack(1);
            return true;
        }
        return false;
}
    render() {
        var {navigationEvent} = this.state;
        if (!navigationEvent) return null;
        var {state, data} = navigationEvent.stateNavigator.stateContext;
        return (
            <NavigationContext.Provider value={navigationEvent}>
                {this.props.renderScene(state, data)}
            </NavigationContext.Provider>
        );
    }
}

export default props => (
    <NavigationContext.Consumer>
        {(navigationEvent) => <NavigationMotion navigationEvent={navigationEvent} {...props} />}
    </NavigationContext.Consumer>
)
<|endoftext|>


<commit_before>import { graphql } from 'react-apollo';
import { compose } from 'recompose';
import {
  AsyncStorage,
} from 'react-native';
import personQuery from './personQuery';
import loginMutation from './loginMutation';
import registerMutation from './registerMutation';
import changePasswordMutation from './changePasswordMutation';
import forgotPasswordMutation from './forgotPasswordMutation';
import resetPasswordMutation from './resetPasswordMutation';

// TODO: Set login token in local storage
const loginAction = graphql(loginMutation, {
  props: ({ mutate }) => ({
    login: async ({ email, password } = {}) => {
      try {
        const result = await mutate({
          variables: {
            email,
            password,
          },
        });

        await AsyncStorage.setItem('authToken', `${btoa(email)}::${btoa(password)}`);
        return result;
      } catch (err) {
        throw err;
      }
    },
  }),
});

const registerAction = graphql(registerMutation, {
  props: ({ mutate }) => ({
    register: (params = {}) => {
      const {
        email,
        password,
        firstName,
        lastName,
      } = params;

      mutate({
        variables: {
          email,
          password,
          firstName,
          lastName,
        },
      });
    },
  }),
});

const changePasswordAction = graphql(changePasswordMutation, {
  props: ({ mutate }) => ({
    changePassword: (params = {}) => {
      const {
        oldPassword,
        newPassword,
      } = params;

      mutate({
        variables: {
          oldPassword,
          newPassword,
        },
      });
    },
  }),
});

const forgotPasswordAction = graphql(forgotPasswordMutation, {
  props: ({ mutate }) => ({
    forgotPassword: (params = {}) => {
      const {
        email,
        sourceURL,
      } = params;

      mutate({
        variables: {
          email,
          sourceURL,
        },
      });
    },
  }),
});

const resetPasswordAction = graphql(resetPasswordMutation, {
  props: ({ mutate }) => ({
    resetPassword: (params = {}) => {
      const {
        token,
        newPassword,
      } = params;

      mutate({
        variables: {
          token,
          newPassword,
        },
      });
    },
  }),
});

const user = graphql(personQuery, {
  props: ({ data: { person } }) => ({
    user: person,
  }),
});

export default compose(
  loginAction,
  registerAction,
  changePasswordAction,
  forgotPasswordAction,
  resetPasswordAction,
  user,
);
<commit_msg>Clean up<commit_after>import { graphql } from 'react-apollo';
import { compose } from 'recompose';
import {
  AsyncStorage,
} from 'react-native';
import personQuery from './personQuery';
import loginMutation from './loginMutation';
import registerMutation from './registerMutation';
import changePasswordMutation from './changePasswordMutation';
import forgotPasswordMutation from './forgotPasswordMutation';
import resetPasswordMutation from './resetPasswordMutation';

const loginAction = graphql(loginMutation, {
  props: ({ mutate }) => ({
    login: async ({ email, password } = {}) => {
      try {
        const result = await mutate({
          variables: {
            email,
            password,
          },
        });

        await AsyncStorage.setItem('authToken', `${btoa(email)}::${btoa(password)}`);
        return result;
      } catch (err) {
        throw err;
      }
    },
  }),
});

const registerAction = graphql(registerMutation, {
  props: ({ mutate }) => ({
    register: (params = {}) => {
      const {
        email,
        password,
        firstName,
        lastName,
      } = params;

      mutate({
        variables: {
          email,
          password,
          firstName,
          lastName,
        },
      });
    },
  }),
});

const changePasswordAction = graphql(changePasswordMutation, {
  props: ({ mutate }) => ({
    changePassword: (params = {}) => {
      const {
        oldPassword,
        newPassword,
      } = params;

      mutate({
        variables: {
          oldPassword,
          newPassword,
        },
      });
    },
  }),
});

const forgotPasswordAction = graphql(forgotPasswordMutation, {
  props: ({ mutate }) => ({
    forgotPassword: (params = {}) => {
      const {
        email,
        sourceURL,
      } = params;

      mutate({
        variables: {
          email,
          sourceURL,
        },
      });
    },
  }),
});

const resetPasswordAction = graphql(resetPasswordMutation, {
  props: ({ mutate }) => ({
    resetPassword: (params = {}) => {
      const {
        token,
        newPassword,
      } = params;

      mutate({
        variables: {
          token,
          newPassword,
        },
      });
    },
  }),
});

const user = graphql(personQuery, {
  props: ({ data: { person } }) => ({
    user: person,
  }),
});

export default compose(
  loginAction,
  registerAction,
  changePasswordAction,
  forgotPasswordAction,
  resetPasswordAction,
  user,
);
<|endoftext|>


<commit_before>var b64pad  = "";
var chrsz   = 8;

function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}

function core_sha1(x, len)
{
    x[len >> 5] |= 0x80 << (24 - len % 32);
    x[((len + 64 >> 9) << 4) + 15] = len;

    var w = Array(80);
    var a =  1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d =  271733878;
    var e = -1009589776;

    for(var i = 0; i < x.length; i += 16)
    {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        var olde = e;

        for(var j = 0; j < 80; j++)
        {
            if(j < 16) w[j] = x[i + j];
            else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
            var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                safe_add(safe_add(e, w[j]), sha1_kt(j)));
            e = d;
            d = c;
            c = rol(b, 30);
            b = a;
            a = t;
        }

        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
        e = safe_add(e, olde);
    }
    return Array(a, b, c, d, e);

}

function sha1_ft(t, b, c, d)
{
    if(t < 20) return (b & c) | ((~b) & d);
    if(t < 40) return b ^ c ^ d;
    if(t < 60) return (b & c) | (b & d) | (c & d);
    return b ^ c ^ d;
}

function sha1_kt(t)
{
    return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
        (t < 60) ? -1894007588 : -899497514;
}

function safe_add(x, y)
{
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
}

function rol(num, cnt)
{
    return (num << cnt) | (num >>> (32 - cnt));
}

function str2binb(str)
{
    var bin = Array();
    var mask = (1 << chrsz) - 1;
    for(var i = 0; i < str.length * chrsz; i += chrsz)
        bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
    return bin;
}

function binb2b64(binarray)
{
    var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var str = "";
    for(var i = 0; i < binarray.length * 4; i += 3)
    {
        var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
            | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
            |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
        for(var j = 0; j < 4; j++)
        {
            if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
            else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
        }
    }
    return str;
}

var form = document.f;

form.addEventListener("submit", function () {
    event.preventDefault();
    form.password.value = b64_sha1(form.master.value+':'+form.site.value).substr(0,1) + '1a';
    document.f.password.focus();
    document.f.password.select();
    return false;
});

<commit_msg>chrome extension tunned<commit_after>var b64pad  = "";
var chrsz   = 8;

function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}

function core_sha1(x, len)
{
    x[len >> 5] |= 0x80 << (24 - len % 32);
    x[((len + 64 >> 9) << 4) + 15] = len;

    var w = Array(80);
    var a =  1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d =  271733878;
    var e = -1009589776;

    for(var i = 0; i < x.length; i += 16)
    {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        var olde = e;

        for(var j = 0; j < 80; j++)
        {
            if(j < 16) w[j] = x[i + j];
            else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
            var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                safe_add(safe_add(e, w[j]), sha1_kt(j)));
            e = d;
            d = c;
            c = rol(b, 30);
            b = a;
            a = t;
        }

        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
        e = safe_add(e, olde);
    }
    return Array(a, b, c, d, e);

}

function sha1_ft(t, b, c, d)
{
    if(t < 20) return (b & c) | ((~b) & d);
    if(t < 40) return b ^ c ^ d;
    if(t < 60) return (b & c) | (b & d) | (c & d);
    return b ^ c ^ d;
}

function sha1_kt(t)
{
    return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
        (t < 60) ? -1894007588 : -899497514;
}

function safe_add(x, y)
{
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
}

function rol(num, cnt)
{
    return (num << cnt) | (num >>> (32 - cnt));
}

function str2binb(str)
{
    var bin = Array();
    var mask = (1 << chrsz) - 1;
    for(var i = 0; i < str.length * chrsz; i += chrsz)
        bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
    return bin;
}

function binb2b64(binarray)
{
    var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var str = "";
    for(var i = 0; i < binarray.length * 4; i += 3)
    {
        var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
            | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
            |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
        for(var j = 0; j < 4; j++)
        {
            if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
            else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
        }
    }
    return str;
}

var form = document.f;

form.addEventListener("submit", function () {
    event.preventDefault();
    form.password.value = b64_sha1(document.f.master.value+':'+document.f.site.value).substr(0,8) + '1a';
    document.f.password.focus();
    document.f.password.select();
    return false;
});

<|endoftext|>


<commit_before>angular.module('d3', [])
    .factory('d3', ['$document', '$q', '$rootScope',
    function($document, $q, $rootScope) {
        var d = $q.defer();
        function onScriptLoad() {
          // Load client in the browser
          $rootScope.$apply(function() { d.resolve(window.d3); });
        }
        // Create a script tag with d3 as the source
        // and call our onScriptLoad callback when it
        // has been loaded
        var scriptTag = $document[0].createElement('script');
        scriptTag.type = 'text/javascript';
        scriptTag.src = 'https://d3js.org/d3.v4.min.js';
        scriptTag.onreadystatechange = function () {
          if (this.readyState == 'complete') onScriptLoad();
        }
        scriptTag.onload = onScriptLoad;

        var s = $document[0].getElementsByTagName('body')[0];
        s.appendChild(scriptTag);

        return {
          d3: function() { return d.promise; }
        };
    }]);

angular.module('d3App', ['d3']).
    directive('d3Test', ['d3', function (d3) {
        return {
            restrict: 'EA',
            scope:{},
            link: function(scope, element, attrs)
            {
                d3.d3().then(function(d3){
                    scope.nodes =
                    [{"name": "Travis", "sex": "M"},
                    {"name": "Rake", "sex": "M"},
                    {"name": "Diana", "sex": "F"},
                    {"name": "Rachel", "sex": "F"},
                    {"name": "Shawn", "sex": "M"},
                    {"name": "Emerald", "sex": "F"}];

                    scope.links =
                    [{"source": "Travis", "target": "Rake"},
                    {"source": "Diana", "target": "Rake"},
                    {"source": "Diana", "target": "Rachel"},
                    {"source": "Rachel", "target": "Rake"},
                    {"source": "Rachel", "target": "Shawn"},
                    {"source": "Emerald", "target": "Rachel"}];

                    var width = 960, height = 500, radius = 8;
                    var svg = d3.select(element [0])
                                .append('svg')
                                .attr('width', width)
                                .attr('height', height);

                    var simulation = d3.forceSimulation().nodes(scope.nodes);
                    var link_force = d3.forceLink(scope.links).id(function(d){ return d.name; });

                    simulation
                        .force("charge_force", d3.forceManyBody().strength(-200))
                        .force("center_force", d3.forceCenter(width/2, height/2))
                        .force("links", link_force);

                    simulation.on("tick", tickActions);

                    var g = svg.append("g")
                        .attr("class", "everything");

                    var link = g.append("g")
                        .attr("class", "link")
                        .selectAll("line")
                        .data(scope.links)
                        .enter().append("line")
                        .attr("stroke-width", 2)
                        .style("stroke", linkColour);

                    var node = g.append("g")
                       .attr("class", "node")
                       .selectAll("circle")
                       .data(scope.nodes)
                       .enter()
                       .append("g")
                       .attr("transform",
                           function(d)
                           {
                               return "translate(" + d.x + "," + d.y + ")";
                           })
                        .on("mouseover", hover_on)
                        .on("mousemove", hover_move)
                        .on("mouseout", hover_end);
                    node
                        .append("circle")
                        .attr("r", radius)
                        .attr("fill", circleColour);

                    node
                        .append("text")
                        .text(texto);

                    var tooltip = d3.select("body")
			            .append("div")
        			    .style("position", "absolute")
        			    .style("z-index", "10")
        			    .style("visibility", "hidden")
        			    .attr("id", "rcorners6");

                    var drag_handler = d3.drag()
    						.on("start", drag_start)
    						.on("drag", drag_drag)
    						.on("end", drag_end);

            	    drag_handler(node);

            	    var zoom_handler = d3.zoom()
            		    .on("zoom", zoom_actions);

            		zoom_handler(svg);

                    function hover_on(d)
            		{
            			if(d.sex == "F")
            			{
            				return tooltip
                    				.text("-"+d.name+"\n-"+d.sex)
                    				.style("visibility", "visible");
            			}
            		}

            		function hover_move(d)
            		{
            			return tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            		}

            		function hover_end(d)
            		{
            			return tooltip.style("visibility", "hidden");
            		}

            		function texto(d)
            		{
            			if(d.sex == "M")
            			{
            				return d.name
            			}

            		}

            		function circleColour(d)
            	    {
            	    	if(d.sex == "M")
            	    	{
            	    		return "blue";
            	    	}
            	    	else
            	    	{
            	    		return "red";
            	    	}
            	    }

            	    function linkColour(d)
            	    {
            	    	if(d.type == "E")
            	    	{
            	    		return "red";
            	    	}
            	    	else
            	    	{
            	    		return "green";
            	    	}
            	    }

            		function drag_start(d){
            			if(!d3.event.active) simulation.alphaTarget(0.3).restart();
            			tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            			d.fx = d.x;
            			d.fy = d.y;
            		}

            		function drag_drag(d)
            		{
            			tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            			d.fx = d3.event.x;
            			d.fy = d3.event.y;
            		}

            		function drag_end(d){
            			if(!d3.event.active) simulation.alphaTarget(0);
            			tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            			d.fx = null;
            			d.fy = null;
            		}

            		function zoom_actions(){
            		    g.attr("transform", d3.event.transform)
            		}

                    function tickActions()
                    {
                        node
                            .attr("transform", function(d)
                            {
                                return "translate(" + d.x + "," + d.y + ")";
                            });

                        link
                            .attr("x1", function(d) { return d.source.x; })
                            .attr("y1", function(d) { return d.source.y; })
                            .attr("x2", function(d) { return d.target.x; })
                            .attr("y2", function(d) { return d.target.y; });
                    }

                });
            }
        };
    }]);
<commit_msg>Directiva de prueba d3<commit_after>angular.module('d3', [])
    .factory('d3', ['$document', '$q', '$rootScope',
    function($document, $q, $rootScope) {
        var d = $q.defer();
        function onScriptLoad() {
          // Load client in the browser
          $rootScope.$apply(function() { d.resolve(window.d3); });
        }
        // Create a script tag with d3 as the source
        // and call our onScriptLoad callback when it
        // has been loaded
        var scriptTag = $document[0].createElement('script');
        scriptTag.type = 'text/javascript';
        scriptTag.src = 'https://d3js.org/d3.v4.min.js';
        scriptTag.onreadystatechange = function () {
          if (this.readyState == 'complete') onScriptLoad();
        }
        scriptTag.onload = onScriptLoad;

        var s = $document[0].getElementsByTagName('body')[0];
        s.appendChild(scriptTag);

        return {
          d3: function() { return d.promise; }
        };
    }]);

angular.module('d3App', ['d3']).
    directive('d3Test', ['d3', function (d3) {
        return {
            restrict: 'EA',
            scope:{},
            link: function(scope, element, attrs)
            {
                d3.d3().then(function(d3){
                    scope.nodes =
                    [{"name": "Travis", "sex": "M"},
                    {"name": "Rake", "sex": "M"},
                    {"name": "Diana", "sex": "F"},
                    {"name": "Rachel", "sex": "F"},
                    {"name": "Shawn", "sex": "M"},
                    {"name": "Emerald", "sex": "F"}];

                    scope.links =
                    [{"source": "Travis", "target": "Rake"},
                    {"source": "Diana", "target": "Rake"},
                    {"source": "Diana", "target": "Rachel"},
                    {"source": "Rachel", "target": "Rake"},
                    {"source": "Rachel", "target": "Shawn"},
                    {"source": "Emerald", "target": "Rachel"}];

                    var width = 960, height = 500, radius = 8;
                    var svg = d3.select(element [0])
                                .append('svg')
                                .attr('width', width)
                                .attr('height', height);

                    var simulation = d3.forceSimulation().nodes(scope.nodes);
                    var link_force = d3.forceLink(scope.links).id(function(d){ return d.name; });

                    simulation
                        .force("charge_force", d3.forceManyBody().strength(-200))
                        .force("center_force", d3.forceCenter(width/2, height/2))
                        .force("links", link_force);

                    simulation.on("tick", tickActions);

                    var g = svg.append("g")
                        .attr("class", "everything");

                    var link = g.append("g")
                        .attr("class", "link")
                        .selectAll("line")
                        .data(scope.links)
                        .enter().append("line")
                        .attr("stroke-width", 2)
                        .style("stroke", linkColour);

                    var node = g.append("g")
                       .attr("class", "node")
                       .selectAll("circle")
                       .data(scope.nodes)
                       .enter()
                       .append("g")
                       .attr("transform",
                           function(d)
                           {
                               return "translate(" + d.x + "," + d.y + ")";
                           })
                        .on("mouseover", hover_on)
                        .on("mousemove", hover_move)
                        .on("mouseout", hover_end);
                    node
                        .append("circle")
                        .attr("r", radius)
                        .attr("fill", circleColour);

                    node
                        .append("text")
                        .text(texto);

                    var tooltip = d3.select("body")
			            .append("div")
        			    .style("position", "absolute")
        			    .style("z-index", "10")
        			    .style("visibility", "hidden")
        			    .attr("id", "rcorners6");

                    var drag_handler = d3.drag()
    						.on("start", drag_start)
    						.on("drag", drag_drag)
    						.on("end", drag_end);

            	    drag_handler(node);

            	    var zoom_handler = d3.zoom()
            		    .on("zoom", zoom_actions);

            		zoom_handler(svg);

                    function hover_on(d)
            		{
            			if(d.sex == "F")
            			{
            				return tooltip
                    				.text("-"+d.name+"\n-"+d.sex)
                    				.style("visibility", "visible");
            			}
            		}

            		function hover_move(d)
            		{
            			return tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            		}

            		function hover_end(d)
            		{
            			return tooltip.style("visibility", "hidden");
            		}

            		function texto(d)
            		{
            			if(d.sex == "M")
            			{
            				return d.name
            			}

            		}

            		function circleColour(d)
            	    {
            	    	if(d.sex == "M")
            	    	{
            	    		return "blue";
            	    	}
            	    	else
            	    	{
            	    		return "red";
            	    	}
            	    }

            	    function linkColour(d)
            	    {
            	    	if(d.type == "E")
            	    	{
            	    		return "red";
            	    	}
            	    	else
            	    	{
            	    		return "green";
            	    	}
            	    }

            		function drag_start(d){
            			if(!d3.event.active) simulation.alphaTarget(0.3).restart();
            			tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            			d.fx = d.x;
            			d.fy = d.y;
            		}

            		function drag_drag(d)
            		{
            			tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            			d.fx = d3.event.x;
            			d.fy = d3.event.y;
            		}

            		function drag_end(d){
            			if(!d3.event.active) simulation.alphaTarget(0);
            			tooltip.style("top",
            				    (d3.event.y-10)+"px").style("left",(d3.event.x+10)+"px");
            			d.fx = null;
            			d.fy = null;
            		}

            		function zoom_actions(){
            		    g.attr("transform", d3.event.transform)
            		}

                    function tickActions()
                    {
                        node
                            .attr("transform", function(d)
                            {
                                return "translate(" + d.x + "," + d.y + ")";
                            });

                        link
                            .attr("x1", function(d) { return d.source.x; })
                            .attr("y1", function(d) { return d.source.y; })
                            .attr("x2", function(d) { return d.target.x; })
                            .attr("y2", function(d) { return d.target.y; });
                    }

                });
            }
        };
    }]);

    angular.module('d3App').
        directive(/*nombre directiva*/, ['d3', function (d3) {
            return {
                restrict: 'EA',
                scope:{},
                link: function(scope, element, attrs)
                {
                    d3.d3().then(function(d3){

                        /*Código d3*/

                    });
                }
            };
        }]);
<|endoftext|>


<commit_before>#!/usr/bin/env node

const Chalk = require('chalk');
const fs = require('mz/fs');
const path = require('path');
const Program = require('commander');
const semver = require('semver');

const ShopwareStoreCommander = require('../shopware_store_commander');
const PluginJSONReader = require('../plugin_json_reader');
const PluginChangelogParser = require('../plugin_changelog_parser');
const publishPluginReleaseEvent = require('../publish_plugin_release_event');
const util = require('../util');
const programVersion = require('../version');

// Define CLI
Program
    .version(programVersion)
    .arguments('<file>')
    .option('-u, --username <username>', 'The shopware username.')
    .option('-R, --no_release', 'Set this option to not submit the uploaded binary for review.')
    .option('-f, --force', 'Replace plugin version if it exists')
    .parse(process.argv);

// Load an .env config if available
require('../env_loader').loadConfig(Program);

// Validate arguments
if (Program.args.length < 1) {
    console.error(Chalk.white.bgRed.bold('No file given!'));
    process.exit(1);
}
if (typeof Program.username === 'undefined') {
    console.error(Chalk.white.bgRed.bold('No username given!'));
    process.exit(1);
}

// Run program
const filePath = path.resolve(process.cwd(), Program.args[0]);
const commander = new ShopwareStoreCommander(Program.username, Program.password);
fs.exists(filePath)
    .then((exists) => {
        if (!exists) {
            throw new Error(`File ${filePath} does not exist`);
        }

        // Read the plugin.json of the provided zip file
        const reader = new PluginJSONReader();
        return reader.readZip(filePath);
    })
    .then((pluginInfo) => {
        if (!pluginInfo) {
            throw new Error('Cannot upload plugin binary, because it is missing a plugin.json file.');
        }

        // Try to parse the plugin's changelog file
        const parser = new PluginChangelogParser(true);
        return parser.readZip(filePath).then((pluginChangeLog) => {
            if (pluginChangeLog) {
                // Add the parsed changelog to the plugin info
                console.log('Use changlog from \'CHANGELOG.md\'');
                pluginInfo.info.changelogs = pluginChangeLog;
            }

            return pluginInfo;
        });
    })
    .then(pluginInfo =>
        // Try to find the plugin
        commander
            .findPlugin(pluginInfo.getName(), ['binaries', 'reviews'])
            .then(plugin => [plugin, pluginInfo]))
    .then((args) => {
        const plugin = args[0];
        const pluginInfo = args[1];

        // Make sure that the version of the passed binary does not exist yet
        const conflictingBinary = plugin.binaries.find(
            binary => semver.eq(binary.version, pluginInfo.getCurrentVersion())
        );
        if (conflictingBinary) {
            if (Program.force) {
                return commander.updatePluginBinary(plugin, conflictingBinary, filePath)
                    .then(updatedPlugin => [updatedPlugin, pluginInfo]);
            }

            throw new Error(`The binary version ${conflictingBinary.version} you're trying to upload already exists ` +
                `for plugin ${plugin.name}`);
        }

        // Upload the binary
        return commander.uploadPluginBinary(plugin, filePath).then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
    })
    .then(({ updatedPlugin: plugin, pluginInfo }) => {
        // Update the updloaded binary using the plugin info
        console.log(`Set version to ${pluginInfo.getCurrentVersion()}`);
        plugin.latestBinary.version = pluginInfo.getCurrentVersion();
        plugin.latestBinary.changelogs.forEach((changelog) => {
            const lang = changelog.locale.name.split('_').shift();
            try {
                changelog.text = pluginInfo.getChangelog(lang);
                console.log(`Set changelog for language '${lang}'`);
            } catch (e) {
                console.log(Chalk.yellow.bold(`\u{26A0} ${e.message}`));
            }
        });
        const shopwareVersions = commander.statics.softwareVersions;
        plugin.latestBinary.compatibleSoftwareVersions = shopwareVersions.filter(
            version => version.selectable && pluginInfo.isCompatible(version.name)
        );
        const compatibleVersionStrings = plugin.latestBinary.compatibleSoftwareVersions.map(version => version.name);
        if (compatibleVersionStrings.length > 0) {
            console.log(`Set shopware version compatiblity: ${compatibleVersionStrings.join(', ')}`);
        } else {
            console.log(
                Chalk.yellow.bold(
                    '\u{26A0} Warning: The plugin\'s compatibility constraints don\'t match any available shopware ' +
                    'versions!'
                )
            );
        }

        return commander.savePluginBinary(plugin, plugin.latestBinary)
            .then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
    })
    .then(({ updatedPlugin: plugin, pluginInfo }) => {
        const uploadSuccessMessage =
            `New version ${plugin.latestBinary.version} of plugin ${plugin.name} uploaded! \u{2705}`;
        console.log(Chalk.green.bold(uploadSuccessMessage));
        if (Program.no_release) {
            util.showGrowlIfEnabled(uploadSuccessMessage);
            console.log(Chalk.yellow.bold('Don\'t forget to manually release the version by requesting a review.'));
            process.exit(0);
        }

        // Request a review for the uploaded binary
        return commander.requestBinaryReview(plugin).then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
    })
    .then(({ updatedPlugin: plugin, pluginInfo }) => {
        // Check review status
        const review = plugin.reviews[plugin.reviews.length - 1];
        if (review.status.name !== 'approved') {
            throw new Error(
                `The review of ${plugin.name} v${plugin.latestBinary.version} finished with status ` +
                `'${review.status.name}':\n\n${review.comment}`
            );
        }

        const successMessage =
            `Review succeeded! Version ${plugin.latestBinary.version} of plugin ${plugin.name} is now available in ` +
            'the store. \u{1F389}';
        util.showGrowlIfEnabled(successMessage);
        console.log(Chalk.green.bold(successMessage));

        return pluginInfo;
    })
    .then(publishPluginReleaseEvent)
    .catch((err) => {
        const errorMessage = `\u{1F6AB} Error: ${err.message}`;
        util.showGrowlIfEnabled(errorMessage);
        console.error(Chalk.white.bgRed.bold(errorMessage));
        console.error(err);
        process.exit(-1);
    });
<commit_msg>Fix error when using ‘upload’ command with ‘-f|—force’<commit_after>#!/usr/bin/env node

const Chalk = require('chalk');
const fs = require('mz/fs');
const path = require('path');
const Program = require('commander');
const semver = require('semver');

const ShopwareStoreCommander = require('../shopware_store_commander');
const PluginJSONReader = require('../plugin_json_reader');
const PluginChangelogParser = require('../plugin_changelog_parser');
const publishPluginReleaseEvent = require('../publish_plugin_release_event');
const util = require('../util');
const programVersion = require('../version');

// Define CLI
Program
    .version(programVersion)
    .arguments('<file>')
    .option('-u, --username <username>', 'The shopware username.')
    .option('-R, --no_release', 'Set this option to not submit the uploaded binary for review.')
    .option('-f, --force', 'Replace plugin version if it exists')
    .parse(process.argv);

// Load an .env config if available
require('../env_loader').loadConfig(Program);

// Validate arguments
if (Program.args.length < 1) {
    console.error(Chalk.white.bgRed.bold('No file given!'));
    process.exit(1);
}
if (typeof Program.username === 'undefined') {
    console.error(Chalk.white.bgRed.bold('No username given!'));
    process.exit(1);
}

// Run program
const filePath = path.resolve(process.cwd(), Program.args[0]);
const commander = new ShopwareStoreCommander(Program.username, Program.password);
fs.exists(filePath)
    .then((exists) => {
        if (!exists) {
            throw new Error(`File ${filePath} does not exist`);
        }

        // Read the plugin.json of the provided zip file
        const reader = new PluginJSONReader();
        return reader.readZip(filePath);
    })
    .then((pluginInfo) => {
        if (!pluginInfo) {
            throw new Error('Cannot upload plugin binary, because it is missing a plugin.json file.');
        }

        // Try to parse the plugin's changelog file
        const parser = new PluginChangelogParser(true);
        return parser.readZip(filePath).then((pluginChangeLog) => {
            if (pluginChangeLog) {
                // Add the parsed changelog to the plugin info
                console.log('Use changlog from \'CHANGELOG.md\'');
                pluginInfo.info.changelogs = pluginChangeLog;
            }

            return pluginInfo;
        });
    })
    .then(pluginInfo =>
        // Try to find the plugin
        commander
            .findPlugin(pluginInfo.getName(), ['binaries', 'reviews'])
            .then(plugin => [plugin, pluginInfo]))
    .then((args) => {
        const plugin = args[0];
        const pluginInfo = args[1];

        // Make sure that the version of the passed binary does not exist yet
        const conflictingBinary = plugin.binaries.find(
            binary => semver.eq(binary.version, pluginInfo.getCurrentVersion())
        );
        if (conflictingBinary) {
            if (Program.force) {
                return commander.updatePluginBinary(plugin, conflictingBinary, filePath)
                    .then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
            }

            throw new Error(`The binary version ${conflictingBinary.version} you're trying to upload already exists ` +
                `for plugin ${plugin.name}`);
        }

        // Upload the binary
        return commander.uploadPluginBinary(plugin, filePath).then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
    })
    .then(({ updatedPlugin: plugin, pluginInfo }) => {
        // Update the updloaded binary using the plugin info
        console.log(`Set version to ${pluginInfo.getCurrentVersion()}`);
        plugin.latestBinary.version = pluginInfo.getCurrentVersion();
        plugin.latestBinary.changelogs.forEach((changelog) => {
            const lang = changelog.locale.name.split('_').shift();
            try {
                changelog.text = pluginInfo.getChangelog(lang);
                console.log(`Set changelog for language '${lang}'`);
            } catch (e) {
                console.log(Chalk.yellow.bold(`\u{26A0} ${e.message}`));
            }
        });
        const shopwareVersions = commander.statics.softwareVersions;
        plugin.latestBinary.compatibleSoftwareVersions = shopwareVersions.filter(
            version => version.selectable && pluginInfo.isCompatible(version.name)
        );
        const compatibleVersionStrings = plugin.latestBinary.compatibleSoftwareVersions.map(version => version.name);
        if (compatibleVersionStrings.length > 0) {
            console.log(`Set shopware version compatiblity: ${compatibleVersionStrings.join(', ')}`);
        } else {
            console.log(
                Chalk.yellow.bold(
                    '\u{26A0} Warning: The plugin\'s compatibility constraints don\'t match any available shopware ' +
                    'versions!'
                )
            );
        }

        return commander.savePluginBinary(plugin, plugin.latestBinary)
            .then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
    })
    .then(({ updatedPlugin: plugin, pluginInfo }) => {
        const uploadSuccessMessage =
            `New version ${plugin.latestBinary.version} of plugin ${plugin.name} uploaded! \u{2705}`;
        console.log(Chalk.green.bold(uploadSuccessMessage));
        if (Program.no_release) {
            util.showGrowlIfEnabled(uploadSuccessMessage);
            console.log(Chalk.yellow.bold('Don\'t forget to manually release the version by requesting a review.'));
            process.exit(0);
        }

        // Request a review for the uploaded binary
        return commander.requestBinaryReview(plugin).then(updatedPlugin => ({ updatedPlugin, pluginInfo }));
    })
    .then(({ updatedPlugin: plugin, pluginInfo }) => {
        // Check review status
        const review = plugin.reviews[plugin.reviews.length - 1];
        if (review.status.name !== 'approved') {
            throw new Error(
                `The review of ${plugin.name} v${plugin.latestBinary.version} finished with status ` +
                `'${review.status.name}':\n\n${review.comment}`
            );
        }

        const successMessage =
            `Review succeeded! Version ${plugin.latestBinary.version} of plugin ${plugin.name} is now available in ` +
            'the store. \u{1F389}';
        util.showGrowlIfEnabled(successMessage);
        console.log(Chalk.green.bold(successMessage));

        return pluginInfo;
    })
    .then(publishPluginReleaseEvent)
    .catch((err) => {
        const errorMessage = `\u{1F6AB} Error: ${err.message}`;
        util.showGrowlIfEnabled(errorMessage);
        console.error(Chalk.white.bgRed.bold(errorMessage));
        console.error(err);
        process.exit(-1);
    });
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const Promise = require('promise');
const declareOpts = require('../lib/declareOpts');
const os = require('os');
const util = require('util');
const workerFarm = require('worker-farm');
const debug = require('debug')('ReactNativePackager:JStransformer');

// Avoid memory leaks caused in workers. This number seems to be a good enough number
// to avoid any memory leak while not slowing down initial builds.
// TODO(amasad): Once we get bundle splitting, we can drive this down a bit more.
const MAX_CALLS_PER_WORKER = 600;

// Worker will timeout if one of the callers timeout.
const DEFAULT_MAX_CALL_TIME = 301000;

// How may times can we tolerate failures from the worker.
const MAX_RETRIES = 2;

const validateOpts = declareOpts({
  transformModulePath: {
    type:'string',
    required: false,
  },
  transformTimeoutInterval: {
    type: 'number',
    default: DEFAULT_MAX_CALL_TIME,
  },
});

const maxConcurrentWorkers = ((cores, override) => {
  if (override) {
    return Math.min(cores, override);
  }

  if (cores < 3) {
    return cores;
  }
  if (cores < 8) {
    return Math.floor(cores * 0.75);
  }
  if (cores < 24) {
    return Math.floor(3/8 * cores + 3); // between cores *.75 and cores / 2
  }
  return cores / 2;
})(os.cpus().length, process.env.REACT_NATIVE_MAX_WORKERS);

class Transformer {
  constructor(options) {
    const opts = this._opts = validateOpts(options);

    const {transformModulePath} = opts;

    if (transformModulePath) {
      this._transformModulePath = require.resolve(transformModulePath);

      this._workers = workerFarm(
        {
          autoStart: true,
          maxConcurrentCallsPerWorker: 1,
          maxConcurrentWorkers: maxConcurrentWorkers,
          maxCallsPerWorker: MAX_CALLS_PER_WORKER,
          maxCallTime: opts.transformTimeoutInterval,
          maxRetries: MAX_RETRIES,
        },
        require.resolve('./worker'),
        ['minify', 'transformAndExtractDependencies']
      );

      this._transform = Promise.denodeify(this._workers.transformAndExtractDependencies);
      this.minify = Promise.denodeify(this._workers.minify);
    }
  }

  kill() {
    this._workers && workerFarm.end(this._workers);
  }

  transformFile(fileName, code, options) {
    if (!this._transform) {
      return Promise.reject(new Error('No transform module'));
    }
    debug('transforming file', fileName);
    return this
      ._transform(this._transformModulePath, fileName, code, options)
      .then(result => {
        debug('done transforming file', fileName);
        return result;
      })
      .catch(error => {
        if (error.type === 'TimeoutError') {
          const timeoutErr = new Error(
            `TimeoutError: transforming ${fileName} took longer than ` +
            `${this._opts.transformTimeoutInterval / 1000} seconds.\n` +
            `You can adjust timeout via the 'transformTimeoutInterval' option`
          );
          timeoutErr.type = 'TimeoutError';
          throw timeoutErr;
        } else if (error.type === 'ProcessTerminatedError') {
          const uncaughtError = new Error(
            'Uncaught error in the transformer worker: ' +
            this._opts.transformModulePath
          );
          uncaughtError.type = 'ProcessTerminatedError';
          throw uncaughtError;
        }

        throw formatError(error, fileName);
      });
  }
}

module.exports = Transformer;

Transformer.TransformError = TransformError;

function TransformError() {
  Error.captureStackTrace && Error.captureStackTrace(this, TransformError);
}
util.inherits(TransformError, SyntaxError);

function formatError(err, filename, source) {
  if (err.loc) {
    return formatBabelError(err, filename, source);
  } else {
    return formatGenericError(err, filename, source);
  }
}

function formatGenericError(err, filename) {
  var msg = 'TransformError: ' + filename + ': ' + err.message;
  var error = new TransformError();
  var stack = (err.stack || '').split('\n').slice(0, -1);
  stack.push(msg);
  error.stack = stack.join('\n');
  error.message = msg;
  error.type = 'TransformError';
  return error;
}

function formatBabelError(err, filename) {
  var error = new TransformError();
  error.type = 'TransformError';
  error.message = (err.type || error.type) + ' ' + err.message;
  error.stack = err.stack;
  error.snippet = err.codeFrame;
  error.lineNumber = err.loc.line;
  error.column = err.loc.column;
  error.filename = filename;
  error.description = err.message;
  return error;
}
<commit_msg>Add file transform event to Activity<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const Activity = require('../Activity');
const Promise = require('promise');
const declareOpts = require('../lib/declareOpts');
const os = require('os');
const util = require('util');
const workerFarm = require('worker-farm');
const debug = require('debug')('ReactNativePackager:JStransformer');

// Avoid memory leaks caused in workers. This number seems to be a good enough number
// to avoid any memory leak while not slowing down initial builds.
// TODO(amasad): Once we get bundle splitting, we can drive this down a bit more.
const MAX_CALLS_PER_WORKER = 600;

// Worker will timeout if one of the callers timeout.
const DEFAULT_MAX_CALL_TIME = 301000;

// How may times can we tolerate failures from the worker.
const MAX_RETRIES = 2;

const validateOpts = declareOpts({
  transformModulePath: {
    type:'string',
    required: false,
  },
  transformTimeoutInterval: {
    type: 'number',
    default: DEFAULT_MAX_CALL_TIME,
  },
});

const maxConcurrentWorkers = ((cores, override) => {
  if (override) {
    return Math.min(cores, override);
  }

  if (cores < 3) {
    return cores;
  }
  if (cores < 8) {
    return Math.floor(cores * 0.75);
  }
  if (cores < 24) {
    return Math.floor(3/8 * cores + 3); // between cores *.75 and cores / 2
  }
  return cores / 2;
})(os.cpus().length, process.env.REACT_NATIVE_MAX_WORKERS);

class Transformer {
  constructor(options) {
    const opts = this._opts = validateOpts(options);

    const {transformModulePath} = opts;

    if (transformModulePath) {
      this._transformModulePath = require.resolve(transformModulePath);

      this._workers = workerFarm(
        {
          autoStart: true,
          maxConcurrentCallsPerWorker: 1,
          maxConcurrentWorkers: maxConcurrentWorkers,
          maxCallsPerWorker: MAX_CALLS_PER_WORKER,
          maxCallTime: opts.transformTimeoutInterval,
          maxRetries: MAX_RETRIES,
        },
        require.resolve('./worker'),
        ['minify', 'transformAndExtractDependencies']
      );

      this._transform = Promise.denodeify(this._workers.transformAndExtractDependencies);
      this.minify = Promise.denodeify(this._workers.minify);
    }
  }

  kill() {
    this._workers && workerFarm.end(this._workers);
  }

  transformFile(fileName, code, options) {
    if (!this._transform) {
      return Promise.reject(new Error('No transform module'));
    }
    debug('transforming file', fileName);
    const transformEventId = Activity.startEvent(
      'Transforming file',
      fileName,
      {
        telemetric: true,
        silent: true,
      },
    );
    return this
      ._transform(this._transformModulePath, fileName, code, options)
      .then(result => {
        debug('done transforming file', fileName);
        Activity.endEvent(transformEventId);
        return result;
      })
      .catch(error => {
        if (error.type === 'TimeoutError') {
          const timeoutErr = new Error(
            `TimeoutError: transforming ${fileName} took longer than ` +
            `${this._opts.transformTimeoutInterval / 1000} seconds.\n` +
            `You can adjust timeout via the 'transformTimeoutInterval' option`
          );
          timeoutErr.type = 'TimeoutError';
          throw timeoutErr;
        } else if (error.type === 'ProcessTerminatedError') {
          const uncaughtError = new Error(
            'Uncaught error in the transformer worker: ' +
            this._opts.transformModulePath
          );
          uncaughtError.type = 'ProcessTerminatedError';
          throw uncaughtError;
        }

        throw formatError(error, fileName);
      });
  }
}

module.exports = Transformer;

Transformer.TransformError = TransformError;

function TransformError() {
  Error.captureStackTrace && Error.captureStackTrace(this, TransformError);
}
util.inherits(TransformError, SyntaxError);

function formatError(err, filename, source) {
  if (err.loc) {
    return formatBabelError(err, filename, source);
  } else {
    return formatGenericError(err, filename, source);
  }
}

function formatGenericError(err, filename) {
  var msg = 'TransformError: ' + filename + ': ' + err.message;
  var error = new TransformError();
  var stack = (err.stack || '').split('\n').slice(0, -1);
  stack.push(msg);
  error.stack = stack.join('\n');
  error.message = msg;
  error.type = 'TransformError';
  return error;
}

function formatBabelError(err, filename) {
  var error = new TransformError();
  error.type = 'TransformError';
  error.message = (err.type || error.type) + ' ' + err.message;
  error.stack = err.stack;
  error.snippet = err.codeFrame;
  error.lineNumber = err.loc.line;
  error.column = err.loc.column;
  error.filename = filename;
  error.description = err.message;
  return error;
}
<|endoftext|>


<commit_before>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Swagger integration
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2015 triAGENS GmbH, Cologne, Germany
///
/// Licensed 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Alan Plum
/// @author Copyright 2015, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var _ = require('underscore');
var fs = require('fs');
var resultNotFound = require('org/arangodb/actions').resultNotFound;
var FoxxManager = require('org/arangodb/foxx/manager');
var jsonSchemaPrimitives = [
  'array',
  'boolean',
  'integer',
  'number',
  'null',
  'object',
  'string'
];

function createSwaggerRouteHandler(appPath, opts) {
  if (!opts) {
    opts = {};
  }
  if (typeof opts === 'function') {
    opts = {before: opts};
  }
  return function (req, res) {
    var result;
    if (typeof opts.before === 'function') {
      result = opts.before.apply(this, arguments);
      if (result === false) {
        return;
      }
    }
    var pathInfo = req.suffix.join('/');
    if (!pathInfo) {
      var params = Object.keys(req.parameters || {}).reduce(function (part, name) {
        return part + encodeURIComponent(name) + '=' + encodeURIComponent(req.parameters[name]) + '&';
      }, '?');
      params = params.slice(0, params.length - 1);
      res.status(302);
      res.set('location', req.absoluteUrl(appPath + req.path(null, 'index.html') + params));
      return;
    }
    if (pathInfo === 'swagger.json') {
      var swaggerJsonHandler = opts.swaggerJson || swaggerJson;
      if (typeof swaggerJsonHandler === 'string') {
        pathInfo = swaggerJsonHandler;
      } else if (typeof swaggerJsonHandler === 'function') {
        swaggerJsonHandler(req, res, {appPath: result ? result.appPath : (opts.appPath || appPath)});
        return;
      }
    } else if (pathInfo === 'index.html') {
      var indexFile = result ? result.indexFile : opts.indexFile;
      if (indexFile) {
        pathInfo = indexFile;
      }
    }
    var path = swaggerPath(pathInfo, result ? result.swaggerRoot : opts.swaggerRoot);
    if (!fs.isFile(path)) {
      resultNotFound(req, res, 404, "unknown path '" + req.url + "'");
      return;
    }
    res.sendFile(path);
  };
}

function swaggerPath(path, basePath) {
  if (path.charAt(0) === '/') {
    return path;
  }
  if (!basePath) {
    basePath = fs.join(module.startupPath(), 'server', 'assets', 'swagger');
  }
  return fs.safeJoin(basePath, path);
}

function swaggerJson(req, res, opts) {
  var foxx = FoxxManager.routes(opts.appPath);
  var app = foxx.appContext && foxx.appContext.app;
  var swagger = parseRoutes(opts.appPath, foxx.routes, foxx.models);
  res.json({
    swagger: '2.0',
    info: {
      description: app && app._manifest.description,
      version: app && app._manifest.version,
      title: app && app._manifest.name,
      license: app && app._manifest.license && {name: app._manifest.license}
    },
    basePath: '/_db/' + encodeURIComponent(req.database) + (app ? app._mount : opts.appPath),
    schemes: [req.protocol],
    paths: swagger.paths,
    // securityDefinitions: {},
    definitions: swagger.definitions
  });
}

function fixSchema(model) {
  if (!model) {
    return undefined;
  }
  if (!model.type) {
    model.type = 'object';
  }
  if (model.type === 'object') {
    _.each(model.properties, function (prop, key) {
      model.properties[key] = fixSchema(prop);
    });
  } else if (model.type === 'array') {
    if (!model.items) {
      model.items = {
        anyOf: _.map(jsonSchemaPrimitives, function (type) {
          return {type: type};
        })
      };
    }
  }
  return model;
}

function swaggerifyPath(path) {
  return path.replace(/(?::)([^\/]*)/g, '{$1}');
}

function parseRoutes(tag, routes, models) {
  var paths = {};
  var definitions = {};

  _.each(routes, function (route) {
    var path = swaggerifyPath(route.url.match);
    _.each(route.url.methods, function (method) {
      if (!paths[path]) {
        paths[path] = {};
      }
      if (!route.docs) {
        return;
      }
      paths[path][method] = {
        tags: [tag],
        summary: route.docs.summary,
        description: route.docs.notes,
        operationId: route.docs.nickname,
        responses: {
          default: {
            description: 'undocumented body',
            schema: {properties: {}, type: 'object'}
          }
        },
        parameters: route.docs.parameters.map(function (param) {
          var parameter = {
            in: param.paramType,
            name: param.name,
            description: param.description,
            required: param.required
          };
          var schema;
          if (jsonSchemaPrimitives.indexOf(param.dataType) !== -1) {
            schema = {type: param.dataType};
          } else {
            schema = {'$ref': '#/definitions/' + param.dataType};
            if (!definitions[param.dataType]) {
              definitions[param.dataType] = fixSchema(_.clone(models[param.dataType]));
            }
          }
          if (param.paramType === 'body') {
            parameter.schema = schema;
          } else if (schema.type) {
            parameter.type = schema.type;
          } else {
            parameter.type = 'string';
          }
          return parameter;
        })
      };
    });
  });

  return {
    paths: paths,
    definitions: definitions
  };
}

exports.swaggerJson = swaggerJson;
exports.createSwaggerRouteHandler = createSwaggerRouteHandler;
<commit_msg>More graceful error if mount point doesn't exist.<commit_after>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Swagger integration
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2015 triAGENS GmbH, Cologne, Germany
///
/// Licensed 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Alan Plum
/// @author Copyright 2015, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var _ = require('underscore');
var fs = require('fs');
var ArangoError = require('org/arangodb').ArangoError;
var errors = require('org/arangodb').errors;
var resultNotFound = require('org/arangodb/actions').resultNotFound;
var FoxxManager = require('org/arangodb/foxx/manager');
var jsonSchemaPrimitives = [
  'array',
  'boolean',
  'integer',
  'number',
  'null',
  'object',
  'string'
];

function createSwaggerRouteHandler(appPath, opts) {
  if (!opts) {
    opts = {};
  }
  if (typeof opts === 'function') {
    opts = {before: opts};
  }
  return function (req, res) {
    var result;
    if (typeof opts.before === 'function') {
      result = opts.before.apply(this, arguments);
      if (result === false) {
        return;
      }
    }
    var pathInfo = req.suffix.join('/');
    if (!pathInfo) {
      var params = Object.keys(req.parameters || {}).reduce(function (part, name) {
        return part + encodeURIComponent(name) + '=' + encodeURIComponent(req.parameters[name]) + '&';
      }, '?');
      params = params.slice(0, params.length - 1);
      res.status(302);
      res.set('location', req.absoluteUrl(appPath + req.path(null, 'index.html') + params));
      return;
    }
    if (pathInfo === 'swagger.json') {
      var swaggerJsonHandler = opts.swaggerJson || swaggerJson;
      if (typeof swaggerJsonHandler === 'string') {
        pathInfo = swaggerJsonHandler;
      } else if (typeof swaggerJsonHandler === 'function') {
        swaggerJsonHandler(req, res, {appPath: result ? result.appPath : (opts.appPath || appPath)});
        return;
      }
    } else if (pathInfo === 'index.html') {
      var indexFile = result ? result.indexFile : opts.indexFile;
      if (indexFile) {
        pathInfo = indexFile;
      }
    }
    var path = swaggerPath(pathInfo, result ? result.swaggerRoot : opts.swaggerRoot);
    if (!fs.isFile(path)) {
      resultNotFound(req, res, 404, "unknown path '" + req.url + "'");
      return;
    }
    res.sendFile(path);
  };
}

function swaggerPath(path, basePath) {
  if (path.charAt(0) === '/') {
    return path;
  }
  if (!basePath) {
    basePath = fs.join(module.startupPath(), 'server', 'assets', 'swagger');
  }
  return fs.safeJoin(basePath, path);
}

function swaggerJson(req, res, opts) {
  var foxx;
  try {
    foxx = FoxxManager.routes(opts.appPath);
  } catch (e) {
    if (e instanceof ArangoError && e.errorNum === errors.ERROR_APP_NOT_FOUND.code) {
      resultNotFound(req, res, 404, e.errorMessage);
      return;
    }
    throw e;
  }
  var app = foxx.appContext && foxx.appContext.app;
  var swagger = parseRoutes(opts.appPath, foxx.routes, foxx.models);
  res.json({
    swagger: '2.0',
    info: {
      description: app && app._manifest.description,
      version: app && app._manifest.version,
      title: app && app._manifest.name,
      license: app && app._manifest.license && {name: app._manifest.license}
    },
    basePath: '/_db/' + encodeURIComponent(req.database) + (app ? app._mount : opts.appPath),
    schemes: [req.protocol],
    paths: swagger.paths,
    // securityDefinitions: {},
    definitions: swagger.definitions
  });
}

function fixSchema(model) {
  if (!model) {
    return undefined;
  }
  if (!model.type) {
    model.type = 'object';
  }
  if (model.type === 'object') {
    _.each(model.properties, function (prop, key) {
      model.properties[key] = fixSchema(prop);
    });
  } else if (model.type === 'array') {
    if (!model.items) {
      model.items = {
        anyOf: _.map(jsonSchemaPrimitives, function (type) {
          return {type: type};
        })
      };
    }
  }
  return model;
}

function swaggerifyPath(path) {
  return path.replace(/(?::)([^\/]*)/g, '{$1}');
}

function parseRoutes(tag, routes, models) {
  var paths = {};
  var definitions = {};

  _.each(routes, function (route) {
    var path = swaggerifyPath(route.url.match);
    _.each(route.url.methods, function (method) {
      if (!paths[path]) {
        paths[path] = {};
      }
      if (!route.docs) {
        return;
      }
      paths[path][method] = {
        tags: [tag],
        summary: route.docs.summary,
        description: route.docs.notes,
        operationId: route.docs.nickname,
        responses: {
          default: {
            description: 'undocumented body',
            schema: {properties: {}, type: 'object'}
          }
        },
        parameters: route.docs.parameters.map(function (param) {
          var parameter = {
            in: param.paramType,
            name: param.name,
            description: param.description,
            required: param.required
          };
          var schema;
          if (jsonSchemaPrimitives.indexOf(param.dataType) !== -1) {
            schema = {type: param.dataType};
          } else {
            schema = {'$ref': '#/definitions/' + param.dataType};
            if (!definitions[param.dataType]) {
              definitions[param.dataType] = fixSchema(_.clone(models[param.dataType]));
            }
          }
          if (param.paramType === 'body') {
            parameter.schema = schema;
          } else if (schema.type) {
            parameter.type = schema.type;
          } else {
            parameter.type = 'string';
          }
          return parameter;
        })
      };
    });
  });

  return {
    paths: paths,
    definitions: definitions
  };
}

exports.swaggerJson = swaggerJson;
exports.createSwaggerRouteHandler = createSwaggerRouteHandler;
<|endoftext|>


<commit_before>'use strict';

requirejs.config({
    baseUrl: './scripts',
    paths: {
        almond: '../scripts/bower_components/almond/almond',
        phaser: '../scripts/bower_components/phaser/index',

        game: 'game/states/game',
        preloader: 'game/states/preloader'
    },
    shim: {
        phaser: { exports: 'Phaser' }
    }
});

require([
    'phaser', 'game', 'preloader'
], function(Phaser, game, preloader) {
    var phaserGame = new Phaser.Game(800, 600, Phaser.AUTO, 'gameContainer');

    phaserGame.state.add('Game', game);
    phaserGame.state.add('Preloader', preloader);

    phaserGame.state.start('Preloader');

    return phaserGame;
});
<commit_msg>Minor refactoring for main requires list.<commit_after>'use strict';

requirejs.config({
    baseUrl: './scripts',
    paths: {
        almond: '../scripts/bower_components/almond/almond',
        Phaser: '../scripts/bower_components/phaser/index',

        game: 'game/states/game',
        preloader: 'game/states/preloader'
    },
});

require([
    'require',
    'Phaser',
    'game',
    'preloader'
], function(require) {
    var Phaser = require('Phaser'),
        game = require('game'),
        preloader = require('preloader');

    var phaserGame = new Phaser.Game(800, 600, Phaser.AUTO, 'gameContainer');

    phaserGame.state.add('Game', game);
    phaserGame.state.add('Preloader', preloader);

    phaserGame.state.start('Preloader');

    return phaserGame;
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  const supertest = require('supertest'),
    server = require('../server'),
    request = supertest(server),
    helper = require('./helpers/helper');

  let adminToken, adminId, userToken, userId, viewerId, viewerToken;
  beforeAll(function (done) {
    helper.adminLogin(function (body) {
      adminToken = body.token;
      adminId = body.user._id;
      done();
    });
    helper.userLogin(function (body) {
      userToken = body.token;
      userId = body.user._id;
      done();
    });
    helper.viewerLogin(function (body) {
      viewerToken = body.token;
      viewerId = body.user._id;
      done();
    });
  });

  describe('Document suite', function () {
    it('allows only authenticated users to create documents', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: adminId,
          title: 'Admin\'s document',
          content: 'This document belongs to the adminstrator and can only be viewed by admins',
          accessLevel: 'admin'
        })
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(res.status).toBe(401);
          expect(res.body).toBeDefined();
          expect(res.body.error).toBeDefined();
          expect(res.body.error).toBe('You are not authenticated');
          done();
        });
    });

    it('allows only authenticated users to view documents', function (done) {
      request
        .get('/documents')
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(res.status).toBe(401);
          expect(res.body.error).toBeDefined();
          expect(res.body.error).toBe('You are not authenticated');
          done();
        });
    });

    it('Document created must have a title and content', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: adminId,
          accessLevel: 'admin'
        })
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeDefined();
          expect(res.body).toBeDefined();
          expect(res.body.errors).toBeDefined();
          expect(res.body.message).toBe('Document validation failed');
          expect(res.body.name).toBe('ValidationError');
          done();
        });
    });

    it('creates a document successfully', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: adminId,
          title: 'Create Test Document',
          content: 'This document has been created by a test spec on the 14th',
          accessLevel: 'admin',
          dateCreated: '2016-03-14T18:05:00.209Z'
        })
        .set('Accept', 'application/json')
        .set('x-access-token', adminToken)
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.body).toBeDefined();
          expect(res.status).toBe(200);
          expect(res.body.document.dateCreated).toBeDefined();
          expect(res.body.document.title).toBe('Create Test Document');
          expect(res.body.message).toBe('Document created successfully');
          done();
        });
    });

    it('creates a document only for existing users', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: '56f3b1e608588e1d4c54744d',
          title: 'Create Test Document',
          content: 'This document has been created by a test spec on the 14th',
          accessLevel: 'private'
        })
        .set('Accept', 'application/json')
        .set('x-access-token', adminToken)
        .end(function (err, res) {
          expect(res.body).toBeDefined();
          expect(res.status).toBe(404);
          expect(res.body.error).toBe('User not found');
          done();
        });
    });

    it('returns one document whose id is issued', function (done) {
      helper.createDoc(adminToken, adminId, function (body) {
        let doc_id = body.document._id;
        request
          .get('/documents/' + doc_id)
          .set('x-access-token', adminToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.title).toBe('Only document to be returned');
            done();
          });
      });
    });

    it('returns all documents if user is admin', function (done) {
      request
        .get('/documents')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(res.body).toBeDefined();
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(5);
          done();
        });
    });

    it('returns the exact number of documents if specified', function (done) {
      request
        .get('/documents?limit=2')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(2);
          done();
        });
    });

    it('returns only documents within the dates specified', function (done) {
      request
        .get('/documents?from=03-10-2016&to=03-15-2016')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(1);
          expect(res.body[0].title).toBe('Create Test Document');
          done();
        });
    });

    it('returns only the documents that are public', function (done) {
        request
          .get('/documents')
          .set('x-access-token', viewerToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(Array.isArray(res.body)).toBeTruthy();
            expect(res.body.length).toBe(1);
            done();
          });
    });

    it('returns all documents accessible to a specific role ', function (done) {
      request
        .get('/documents?role=user')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(4);
          done();
        });
    });

    it('allows a user to update a user document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated',
            accessLevel: 'private'
          })
          .set('x-access-token', userToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();

            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.document.title).toBe('Updated Title');
            expect(res.body.message).toBe('Document updated successfully');
            done();
          });
      });
    });

    it('allows an admin to update a document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated by the admin',
            accessLevel: 'private'
          })
          .set('x-access-token', adminToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.document.title).toBe('Updated Title');
            expect(res.body.message).toBe('Document updated successfully');
            done();
          });
      });
    });

    it('does not allow a viewer to edit any document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated'
          })
          .set('x-access-token', viewerToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('does not allow a user to edit an admin document', function (done) {
      helper.createDoc(adminToken, adminId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated'
          })
          .set('x-access-token', viewerToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('allows a admin to delete any document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', adminToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.message).toBe('Document deleted successfully.');
            done();
          });
      });
    });

    it('allows a user to delete their own document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', userToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.message).toBe('Document deleted successfully.');
            done();
          });
      });
    });

    it('does not allow a viewer to delete a user document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', viewerToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('does not allow a user to delete an admin document', function (done) {
      helper.createDoc(adminToken, adminId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', userToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('returns the documents containing the provided search term', function (done) {
      request
        .get('/documents/results?q=viewed')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(res.body.length).toBe(2);
          expect(res.body[0].content).toContain('viewed');
          done();
        });
    });
  });
})();
<commit_msg>[#117693649] fix script in coverage<commit_after>(function () {
  'use strict';

  const supertest = require('supertest'),
    server = require('../server'),
    request = supertest(server),
    helper = require('./helpers/helper');

  let adminToken, adminId, userToken, userId, viewerId, viewerToken;
  beforeAll(function (done) {
    helper.adminLogin(function (body) {
      adminToken = body.token;
      adminId = body.user._id;
      done();
    });
    helper.userLogin(function (body) {
      userToken = body.token;
      userId = body.user._id;
      done();
    });
    helper.viewerLogin(function (body) {
      viewerToken = body.token;
      viewerId = body.user._id;
      done();
    });
  });

  describe('Document suite', function () {
    it('allows only authenticated users to create documents', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: adminId,
          title: 'Admin\'s document',
          content: 'This document belongs to the adminstrator and can only be viewed by admins',
          accessLevel: 'admin'
        })
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(res.status).toBe(401);
          expect(res.body).toBeDefined();
          expect(res.body.error).toBeDefined();
          expect(res.body.error).toBe('You are not authenticated');
          done();
        });
    });

    it('allows only authenticated users to view documents', function (done) {
      request
        .get('/documents')
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(res.status).toBe(401);
          expect(res.body.error).toBeDefined();
          expect(res.body.error).toBe('You are not authenticated');
          done();
        });
    });

    it('Document created must have a title and content', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: adminId,
          accessLevel: 'admin'
        })
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeDefined();
          expect(res.body).toBeDefined();
          expect(res.body.errors).toBeDefined();
          expect(res.body.message).toBe('Document validation failed');
          expect(res.body.name).toBe('ValidationError');
          done();
        });
    });

    it('creates a document successfully', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: adminId,
          title: 'Create Test Document',
          content: 'This document has been created by a test spec on the 14th',
          accessLevel: 'admin',
          dateCreated: '2016-03-14T18:05:00.209Z'
        })
        .set('Accept', 'application/json')
        .set('x-access-token', adminToken)
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.body).toBeDefined();
          expect(res.status).toBe(200);
          expect(res.body.document.dateCreated).toBeDefined();
          expect(res.body.document.title).toBe('Create Test Document');
          expect(res.body.message).toBe('Document created successfully');
          done();
        });
    });

    it('creates a document only for existing users', function (done) {
      request
        .post('/documents')
        .send({
          ownerId: '56f3b1e608588e1d4c54744d',
          title: 'Create Test Document',
          content: 'This document has been created by a test spec on the 14th',
          accessLevel: 'private'
        })
        .set('Accept', 'application/json')
        .set('x-access-token', adminToken)
        .end(function (err, res) {
          expect(res.body).toBeDefined();
          expect(res.status).toBe(404);
          expect(res.body.error).toBe('User not found');
          done();
        });
    });

    it('returns one document whose id is issued', function (done) {
      helper.createDoc(adminToken, adminId, function (body) {
        let doc_id = body.document._id;
        request
          .get('/documents/' + doc_id)
          .set('x-access-token', adminToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.title).toBe('Only document to be returned');
            done();
          });
      });
    });

    it('returns all documents if user is admin', function (done) {
      request
        .get('/documents')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(res.body).toBeDefined();
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(5);
          done();
        });
    });

    it('returns the exact number of documents if specified', function (done) {
      request
        .get('/documents?limit=2')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(2);
          done();
        });
    });

    it('returns only documents within the dates specified', function (done) {
      request
        .get('/documents?from=03-10-2016&to=03-15-2016')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(Array.isArray(res.body)).toBeTruthy();
          expect(res.body.length).toBe(1);
          expect(res.body[0].title).toBe('Create Test Document');
          done();
        });
    });

    it('allows a user to update a user document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated',
            accessLevel: 'private'
          })
          .set('x-access-token', userToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();

            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.document.title).toBe('Updated Title');
            expect(res.body.message).toBe('Document updated successfully');
            done();
          });
      });
    });

    it('allows an admin to update a document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated by the admin',
            accessLevel: 'private'
          })
          .set('x-access-token', adminToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.document.title).toBe('Updated Title');
            expect(res.body.message).toBe('Document updated successfully');
            done();
          });
      });
    });

    it('does not allow a viewer to edit any document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated'
          })
          .set('x-access-token', viewerToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('does not allow a user to edit an admin document', function (done) {
      helper.createDoc(adminToken, adminId, function (body) {
        let doc_id = body.document._id;
        request
          .put('/documents/' + doc_id)
          .send({
            title: 'Updated Title',
            content: 'This document just got updated'
          })
          .set('x-access-token', viewerToken)
          .set('Accept', 'application/json')
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('allows a admin to delete any document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', adminToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.message).toBe('Document deleted successfully.');
            done();
          });
      });
    });

    it('allows a user to delete their own document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', userToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(200);
            expect(res.body).toBeDefined();
            expect(res.body.message).toBe('Document deleted successfully.');
            done();
          });
      });
    });

    it('does not allow a viewer to delete a user document', function (done) {
      helper.createDoc(userToken, userId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', viewerToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('does not allow a user to delete an admin document', function (done) {
      helper.createDoc(adminToken, adminId, function (body) {
        let doc_id = body.document._id;
        request
          .delete('/documents/' + doc_id)
          .set('x-access-token', userToken)
          .end(function (err, res) {
            expect(err).toBeNull();
            expect(res.status).toBe(403);
            expect(res.body.error.message)
              .toBe('You have no permission to make changes to this document');
            done();
          });
      });
    });

    it('returns the documents containing the provided search term', function (done) {
      request
        .get('/documents/results?q=viewed')
        .set('x-access-token', adminToken)
        .set('Accept', 'application/json')
        .end(function (err, res) {
          expect(err).toBeNull();
          expect(res.status).toBe(200);
          expect(res.body.length).toBe(2);
          expect(res.body[0].content).toContain('viewed');
          done();
        });
    });
  });
})();
<|endoftext|>