<commit_before>const merge = require('webpack-merge')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { commonConfig } = require('./webpack.common.js')
const { GenerateSW } = require('workbox-webpack-plugin')

module.exports = () => {
  const CHUNKS = {
    MAP:
      'leaflet|leaflet-draw|leaflet-rotatedmarker|leaflet.markercluster|leaflet.nontiledlayer|proj4|proj4leaflet',
    DATAPUNT: '@datapunt',
    STYLED: 'styled-components|polished|style-loader|css-loader|sass-loader|postcss-loader',
    PANORAMA: 'marzipano',
    POLYFILL: '@babel/polyfill|objectFitPolyfill',
    ANGULAR: 'angular|angular-aria|angular-i18n|angular-sanitize|react-angular',
    REACT:
      'react|react-dom|redux-first-router|redux-first-router-link|redux-first-router-restore-scroll|reselect|redux|@?redux-saga|react-redux|react-helmet|prop-types',
  }

  const getTestRegex = path => new RegExp(`/node_modules/(${path})/`)

  return merge(commonConfig(), {
    output: {
      filename: '[name].js?id=[chunkhash]',
      chunkFilename: '[name].bundle.js?id=[chunkhash]',
    },
    mode: 'production',
    devtool: 'source-map',
    optimization: {
      minimizer: [
        new UglifyJSPlugin({
          // Do not minify our legacy code (app.bundle.js); this doesn't work with
          // angular dependancy injection
          exclude: /modules/,
          sourceMap: true,
        }),
      ],
      splitChunks: {
        chunks: 'all',
        minSize: 30000,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 3,
        name: true,
        cacheGroups: {
          vendor: {
            test: new RegExp(
              `/node_modules/(?!${[
                CHUNKS.DATAPUNT,
                CHUNKS.POLYFILL,
                CHUNKS.MAP,
                CHUNKS.STYLED,
                CHUNKS.REACT,
                CHUNKS.PANORAMA,
                CHUNKS.BBGA,
                CHUNKS.ANGULAR,
              ].join('|')})/`,
            ),
            name: 'vendor',
            chunks: 'all',
          },
          datapunt: {
            test: getTestRegex(CHUNKS.DATAPUNT),
            name: 'datapunt',
            chunks: 'all',
            enforce: true,
          },
          polyfill: {
            test: getTestRegex(CHUNKS.POLYFILL),
            name: 'polyfill',
            chunks: 'all',
            enforce: true,
          },
          map: {
            test: getTestRegex(CHUNKS.MAP),
            name: 'map',
            chunks: 'async',
            enforce: true,
          },
          bbga: {
            test: getTestRegex(CHUNKS.BBGA),
            name: 'bbga',
            chunks: 'async',
            enforce: true,
          },
          panorama: {
            test: getTestRegex(CHUNKS.PANORAMA),
            name: 'panorama',
            chunks: 'async',
            enforce: true,
          },
          styled: {
            test: getTestRegex(CHUNKS.STYLED),
            name: 'styled',
            chunks: 'all',
            enforce: true,
          },
          react: {
            test: getTestRegex(CHUNKS.REACT),
            name: 'react',
            chunks: 'all',
            enforce: true,
          },
          angular: {
            test: getTestRegex(CHUNKS.ANGULAR),
            name: 'angular',
            chunks: 'async',
            enforce: true,
          },
          main: {
            chunks: 'all',
            minChunks: 2,
            reuseExistingChunk: true,
          },
        },
      },
      runtimeChunk: true,
    },
    plugins: [
      new MiniCssExtractPlugin('main.[contenthash].css'),
      new GenerateSW({
        importWorkboxFrom: 'local',
        clientsClaim: true,
        skipWaiting: true,
        exclude: [/\.map$/, /\.json$/],
        navigateFallbackBlacklist: [
          // Exclude any URLs whose last part seems to be a file extension
          // as they're likely a resource and not a SPA route.
          // URLs containing a "?" character won't be blacklisted as they're likely
          // a route with query params (e.g. auth callbacks).
          new RegExp('/[^/?]+\\.[^/]+$'),
        ],
        cleanupOutdatedCaches: true,
        // Temporary disabled this, since we do not want to cache responses that require authorization
        //
        // runtimeCaching: [
        //   {
        //     urlPattern: new RegExp(apiUrl),
        //     handler: 'StaleWhileRevalidate',
        //     options: {
        //       cacheName: 'api',
        //       expiration: {
        //         maxAgeSeconds: 60 * 60 * 12, // 12h
        //       },
        //       cacheableResponse: {
        //         statuses: [0, 200],
        //       },
        //     },
        //   },
        //   {
        //     urlPattern: new RegExp(`${cmsUrl}(?!/jsonapi/node/notification)`),
        //     handler: 'StaleWhileRevalidate',
        //     options: {
        //       cacheName: 'cms',
        //       expiration: {
        //         maxAgeSeconds: 60 * 60 * 12, // 12h
        //       },
        //       cacheableResponse: {
        //         statuses: [0, 200],
        //       },
        //     },
        //   },
        // ],
      }),
    ],
  })
}
<commit_msg>Cachebust css files<commit_after>const merge = require('webpack-merge')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { commonConfig } = require('./webpack.common.js')
const { GenerateSW } = require('workbox-webpack-plugin')

module.exports = () => {
  const CHUNKS = {
    MAP:
      'leaflet|leaflet-draw|leaflet-rotatedmarker|leaflet.markercluster|leaflet.nontiledlayer|proj4|proj4leaflet',
    DATAPUNT: '@datapunt',
    STYLED: 'styled-components|polished|style-loader|css-loader|sass-loader|postcss-loader',
    PANORAMA: 'marzipano',
    POLYFILL: '@babel/polyfill|objectFitPolyfill',
    ANGULAR: 'angular|angular-aria|angular-i18n|angular-sanitize|react-angular',
    REACT:
      'react|react-dom|redux-first-router|redux-first-router-link|redux-first-router-restore-scroll|reselect|redux|@?redux-saga|react-redux|react-helmet|prop-types',
  }

  const getTestRegex = path => new RegExp(`/node_modules/(${path})/`)

  return merge(commonConfig(), {
    output: {
      filename: '[name].js?id=[chunkhash]',
      chunkFilename: '[name].bundle.js?id=[chunkhash]',
    },
    mode: 'production',
    devtool: 'source-map',
    optimization: {
      minimizer: [
        new UglifyJSPlugin({
          // Do not minify our legacy code (app.bundle.js); this doesn't work with
          // angular dependancy injection
          exclude: /modules/,
          sourceMap: true,
        }),
      ],
      splitChunks: {
        chunks: 'all',
        minSize: 30000,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 3,
        name: true,
        cacheGroups: {
          vendor: {
            test: new RegExp(
              `/node_modules/(?!${[
                CHUNKS.DATAPUNT,
                CHUNKS.POLYFILL,
                CHUNKS.MAP,
                CHUNKS.STYLED,
                CHUNKS.REACT,
                CHUNKS.PANORAMA,
                CHUNKS.BBGA,
                CHUNKS.ANGULAR,
              ].join('|')})/`,
            ),
            name: 'vendor',
            chunks: 'all',
          },
          datapunt: {
            test: getTestRegex(CHUNKS.DATAPUNT),
            name: 'datapunt',
            chunks: 'all',
            enforce: true,
          },
          polyfill: {
            test: getTestRegex(CHUNKS.POLYFILL),
            name: 'polyfill',
            chunks: 'all',
            enforce: true,
          },
          map: {
            test: getTestRegex(CHUNKS.MAP),
            name: 'map',
            chunks: 'async',
            enforce: true,
          },
          bbga: {
            test: getTestRegex(CHUNKS.BBGA),
            name: 'bbga',
            chunks: 'async',
            enforce: true,
          },
          panorama: {
            test: getTestRegex(CHUNKS.PANORAMA),
            name: 'panorama',
            chunks: 'async',
            enforce: true,
          },
          styled: {
            test: getTestRegex(CHUNKS.STYLED),
            name: 'styled',
            chunks: 'all',
            enforce: true,
          },
          react: {
            test: getTestRegex(CHUNKS.REACT),
            name: 'react',
            chunks: 'all',
            enforce: true,
          },
          angular: {
            test: getTestRegex(CHUNKS.ANGULAR),
            name: 'angular',
            chunks: 'async',
            enforce: true,
          },
          main: {
            chunks: 'all',
            minChunks: 2,
            reuseExistingChunk: true,
          },
        },
      },
      runtimeChunk: true,
    },
    plugins: [
      new MiniCssExtractPlugin({
        filename: 'main.[name].css',
        chunkFilename: '[id].css?id=[chunkhash]',
      }),
      new GenerateSW({
        importWorkboxFrom: 'local',
        clientsClaim: true,
        skipWaiting: true,
        exclude: [/\.map$/, /\.json$/],
        navigateFallbackBlacklist: [
          // Exclude any URLs whose last part seems to be a file extension
          // as they're likely a resource and not a SPA route.
          // URLs containing a "?" character won't be blacklisted as they're likely
          // a route with query params (e.g. auth callbacks).
          new RegExp('/[^/?]+\\.[^/]+$'),
        ],
        cleanupOutdatedCaches: true,
        // Temporary disabled this, since we do not want to cache responses that require authorization
        //
        // runtimeCaching: [
        //   {
        //     urlPattern: new RegExp(apiUrl),
        //     handler: 'StaleWhileRevalidate',
        //     options: {
        //       cacheName: 'api',
        //       expiration: {
        //         maxAgeSeconds: 60 * 60 * 12, // 12h
        //       },
        //       cacheableResponse: {
        //         statuses: [0, 200],
        //       },
        //     },
        //   },
        //   {
        //     urlPattern: new RegExp(`${cmsUrl}(?!/jsonapi/node/notification)`),
        //     handler: 'StaleWhileRevalidate',
        //     options: {
        //       cacheName: 'cms',
        //       expiration: {
        //         maxAgeSeconds: 60 * 60 * 12, // 12h
        //       },
        //       cacheableResponse: {
        //         statuses: [0, 200],
        //       },
        //     },
        //   },
        // ],
      }),
    ],
  })
}
<|endoftext|>


<commit_before>(function(Hammer) {
    /**
     * ShowTouches gesture
     * requires jQuery
     * show all touch on the screen by placing elements at there pageX and pageY
     */
    Hammer.plugins.showTouches = function() {
        // the circles under your fingers
        var template = '

';

        // elements by identifier
        var touch_elements = {};

        Hammer.gesture.register({
            name: 'show_touches',
            priority: 0,
            handler: function(ev, inst) {
                // get touches by ID
                var touches_index = {};

                // place touches by index
                for(var t= 0,total_touches=ev.touches.length; t<total_touches;t++) {
                    var touch = ev.touches[t];
                    var id = touch.identifier;
                    touches_index[id] = touch;

                    // new touch element
                    if(!touch_elements[id]) {
                        touch_elements[id] = $(template).appendTo(document.body);
                    }

                    // Paul Irish says that translate is faster then left/top
                    touch_elements[id].css({
                        left: touch.pageX,
                        top: touch.pageY
                    });
                }

                // remove unused touch elements
                for(var key in touch_elements) {
                    if(touch_elements.hasOwnProperty(key) && !touches_index[key]) {
                        touch_elements[key].remove();
                        delete touch_elements[key];
                    }
                }

            }
        });
    };
})(window.Hammer);<commit_msg>higher zIndex for the dots<commit_after>(function(Hammer) {
    /**
     * ShowTouches gesture
     * requires jQuery
     * show all touch on the screen by placing elements at there pageX and pageY
     */
    Hammer.plugins.showTouches = function() {
        // the circles under your fingers
        var template = '

';

        // elements by identifier
        var touch_elements = {};

        Hammer.gesture.register({
            name: 'show_touches',
            priority: 0,
            handler: function(ev, inst) {
                // get touches by ID
                var touches_index = {};

                // place touches by index
                for(var t= 0,total_touches=ev.touches.length; t<total_touches;t++) {
                    var touch = ev.touches[t];
                    var id = touch.identifier;
                    touches_index[id] = touch;

                    // new touch element
                    if(!touch_elements[id]) {
                        touch_elements[id] = $(template).appendTo(document.body);
                    }

                    // Paul Irish says that translate is faster then left/top
                    touch_elements[id].css({
                        left: touch.pageX,
                        top: touch.pageY
                    });
                }

                // remove unused touch elements
                for(var key in touch_elements) {
                    if(touch_elements.hasOwnProperty(key) && !touches_index[key]) {
                        touch_elements[key].remove();
                        delete touch_elements[key];
                    }
                }

            }
        });
    };
})(window.Hammer);<|endoftext|>


<commit_before>var Promise = require('bluebird');
var Transaction = require('../../transaction');
var Helpers = require('../../helpers');
var Plugin = require('../../plugin');
var MediaPlugin = require('../media-plugin');

function AudiobridgePlugin() {
  AudiobridgePlugin.super_.apply(this, arguments);
}

AudiobridgePlugin.NAME = 'janus.plugin.audiobridge';
Helpers.inherits(AudiobridgePlugin, MediaPlugin);
Plugin.register(AudiobridgePlugin.NAME, AudiobridgePlugin);

AudiobridgePlugin.prototype.createRoom = function(roomId) {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    if ('success' == response['janus']) {
      return Promise.resolve(response['plugindata']['data']);
    }
    return Promise.reject(new Error('Failed room create'));
  });
  var message = {
    janus: 'message',
    transaction: transactionId,
    body: {
      request: 'create',
      room: roomId
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

AudiobridgePlugin.prototype.listRooms = function() {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    if ('success' == response['janus']) {
      return Promise.resolve(response['plugindata']['data']['list']);
    }
    return Promise.reject(new Error('Failed list rooms'));
  });
  var message = {
    janus: 'message',
    transaction: transactionId,
    body: {
      request: 'list'
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

AudiobridgePlugin.prototype.joinRoom = function(roomId) {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    if ('error' == response['janus'] || response['plugindata']['data']['error']) {
      return Promise.reject(new Error('Failed room join'));
    }
    return Promise.resolve();
  }.bind(this));
  var message = {
    janus: 'message',
    transaction: transactionId,
    body: {
      request: 'join',
      room: roomId
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

AudiobridgePlugin.prototype.startOffer = function() {
  var self = this;
  return Promise
    .try(function() {
      return self.getLocalMedia({audio: true, video: false});
    })
    .then(function(stream) {
      self.createPeerConnection();
      self.addStream(stream);
    })
    .then(function() {
      return self.createOffer();
    })
    .then(function(jsep) {
      return self.sendOffer(jsep);
    });
};

AudiobridgePlugin.prototype.sendOffer = function(jsep) {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    var jsep = response['jsep'];
    if (jsep) {
      this.setRemoteSDP(jsep);
      return jsep;
    }
    return Promise.reject(new Error('Failed sendOffer'));
  }.bind(this));

  this.addTransaction(transaction);
  var message = {janus: 'message', body: {request: 'configure', muted: false}, jsep: jsep, transaction: transactionId};
  return this.sendSync(message);
};

module.exports = AudiobridgePlugin;
<commit_msg>Streamline<commit_after>var Promise = require('bluebird');
var Transaction = require('../../transaction');
var Helpers = require('../../helpers');
var Plugin = require('../../plugin');
var MediaPlugin = require('../media-plugin');

function AudiobridgePlugin() {
  AudiobridgePlugin.super_.apply(this, arguments);
}

AudiobridgePlugin.NAME = 'janus.plugin.audiobridge';
Helpers.inherits(AudiobridgePlugin, MediaPlugin);
Plugin.register(AudiobridgePlugin.NAME, AudiobridgePlugin);

AudiobridgePlugin.prototype.createRoom = function(roomId) {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    if ('success' == response['janus']) {
      return Promise.resolve(response['plugindata']['data']);
    }
    return Promise.reject(new Error('Failed room create'));
  });
  var message = {
    janus: 'message',
    transaction: transactionId,
    body: {
      request: 'create',
      room: roomId
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

AudiobridgePlugin.prototype.listRooms = function() {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    if ('success' == response['janus']) {
      return Promise.resolve(response['plugindata']['data']['list']);
    }
    return Promise.reject(new Error('Failed list rooms'));
  });
  var message = {
    janus: 'message',
    transaction: transactionId,
    body: {
      request: 'list'
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

AudiobridgePlugin.prototype.joinRoom = function(roomId) {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    if ('error' == response['janus'] || response['plugindata']['data']['error']) {
      return Promise.reject(new Error('Failed room join'));
    }
    return Promise.resolve();
  });
  var message = {
    janus: 'message',
    transaction: transactionId,
    body: {
      request: 'join',
      room: roomId
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

AudiobridgePlugin.prototype.startOffer = function() {
  var self = this;
  return Promise
    .try(function() {
      return self.getLocalMedia({audio: true, video: false});
    })
    .then(function(stream) {
      self.createPeerConnection();
      self.addStream(stream);
    })
    .then(function() {
      return self.createOffer();
    })
    .then(function(jsep) {
      return self.sendOffer(jsep);
    });
};

AudiobridgePlugin.prototype.sendOffer = function(jsep) {
  var transactionId = Transaction.generateRandomId();
  var transaction = new Transaction(transactionId, function(response) {
    var jsep = response['jsep'];
    if (jsep) {
      this.setRemoteSDP(jsep);
      return jsep;
    }
    return Promise.reject(new Error('Failed sendOffer'));
  }.bind(this));
  var message = {
    janus: 'message',
    transaction: transactionId,
    jsep: jsep,
    body: {
      request: 'configure', muted: false
    }
  };

  this.addTransaction(transaction);
  return this.sendSync(message);
};

module.exports = AudiobridgePlugin;
<|endoftext|>


<commit_before>'use strict';

/**
 * Profile Core directive. Used in default.html and play.me.html to render
 * the core profile update fields (name / favorite color / etc).
 *
 * @ngdoc directive
 * @name profileCore
 * @description
 * #
 * Factory in the playerApp.
 */
angular.module('playerApp')
.directive('profileCore', function() {
  return {
    scope: {
      user: '=',
      form: '='
    },
    restrict: 'E',
    templateUrl: 'templates/profileCore.html'
  };
});
<commit_msg>Missed a templateUrl<commit_after>'use strict';

/**
 * Profile Core directive. Used in default.html and play.me.html to render
 * the core profile update fields (name / favorite color / etc).
 *
 * @ngdoc directive
 * @name profileCore
 * @description
 * #
 * Factory in the playerApp.
 */
angular.module('playerApp')
.directive('profileCore', function() {
  return {
    scope: {
      user: '=',
      form: '='
    },
    restrict: 'E',
    templateUrl: 'profileCore.html'
  };
});
<|endoftext|>


<commit_before>var sourceMap;
if (typeof exports !== 'undefined') {
	var req = require; // fool streamline-require so that we don't load source-map client-side
	try { sourceMap = req('source-map'); } catch (ex) {}
}
if (!sourceMap) {
	// Mock it for client-side
	sourceMap = {
		SourceNode: function(l, c, str) {
			this.children = [];
		}
	};
	sourceMap.SourceNode.prototype.add = function(elt) {
		if (Array.isArray(elt)) this.children = this.children.concat(elt);
		else this.children.push(elt);
		return this;
	};
	sourceMap.SourceNode.prototype.prepend = function(elt) {
		if (Array.isArray(elt)) this.children = elt.concat(this.children.concat);
		else this.children.unshift(elt);
		return this;
	};
	sourceMap.SourceNode.prototype.toString = function() {
	    var str = "";
	    this.walk(function (chunk) {
	      str += chunk;
	    });
	    return str;
	};
	sourceMap.SourceNode.prototype.walk = function(f) {
		this.children.forEach(function(n) {
			if (n instanceof sourceMap.SourceNode) n.walk(f);
			else f(n);
		});
		return this;
	};
}
(function(exports) {
function SourceNode() {
	sourceMap.SourceNode.apply(this, arguments);
}

SourceNode.prototype = Object.create(sourceMap.SourceNode.prototype, {
	constructor: {
		value: SourceNode,
		enumerable: false,
		writable: true,
		configurable: true
	},
	length: {
		get: function() {
			var len = 0;
			this.walk(function(str) { len += str.length; });
			return len;
		}
	}
});
SourceNode.prototype.stripPrefix = function(offset) {
	var _len;
	while (this.children.length > 0 && offset > 0 && (_len = this.children[0].length) <= offset) {
		this.children.shift();
		offset -= _len;
	}
	if (this.children.length == 0 || offset == 0) return this;
	if (typeof this.children[0] == 'string') {
		this.children[0] = this.children[0].substring(offset);
	} else {
		this.children[0].stripPrefix(offset);
	}
	return this;
};
SourceNode.prototype.stripSuffix = function(offset) {
	var _len, chlen;
	while ((chlen = this.children.length) > 0 && offset > 0 && (_len = this.children[chlen - 1].length) <= offset) {
		this.children.pop();
		offset -= _len;
	}
	if (chlen == 0 || offset == 0) return this;
	if (typeof this.children[chlen-1] == 'string') {
		this.children[chlen-1] = this.children[0].slice(0, -offset);
	} else {
		this.children[chlen-1].stripSuffix(offset);
	}
	return this;
};
SourceNode.prototype.map = function(f) {
	this.children = this.children.map(function(chunk) {
		if (chunk instanceof sourceMap.SourceNode) {
			return chunk.map(f);
		} else {
			return f(chunk);
		}
	});
	return this;
};
SourceNode.prototype.lastChar = function() {
	for (var i = this.children.length; i--; ) {
		var ret;
		if (typeof this.children[i] == 'string') {
			ret = this.children[i].slice(-1);
		} else {
			ret = this.children[i].lastChar();
		}
		if (ret) return ret;
	}
	return '';
};
module.exports = Object.create(sourceMap, { SourceNode: { value: SourceNode } });

})(typeof exports !== 'undefined' ? exports : (Streamline.sourceMap = Streamline.sourceMap || {}));

<commit_msg>issue #156 - fixed client-side transform-test<commit_after>var sourceMap;
if (typeof exports !== 'undefined') {
	var req = require; // fool streamline-require so that we don't load source-map client-side
	try { sourceMap = req('source-map'); } catch (ex) {}
}
if (!sourceMap) {
	// Mock it for client-side
	sourceMap = {
		SourceNode: function(lineno, column, source, content) {
			this.children = content ? [content] : [];
		}
	};
	sourceMap.SourceNode.prototype.add = function(elt) {
		if (Array.isArray(elt)) this.children = this.children.concat(elt);
		else this.children.push(elt);
		return this;
	};
	sourceMap.SourceNode.prototype.prepend = function(elt) {
		if (Array.isArray(elt)) this.children = elt.concat(this.children.concat);
		else this.children.unshift(elt);
		return this;
	};
	sourceMap.SourceNode.prototype.toString = function() {
	    var str = "";
	    this.walk(function (chunk) {
	      str += chunk;
	    });
	    return str;
	};
	sourceMap.SourceNode.prototype.walk = function(f) {
		this.children.forEach(function(n) {
			if (n instanceof sourceMap.SourceNode) n.walk(f);
			else f(n);
		});
		return this;
	};
}
(function(exports) {
function SourceNode() {
	sourceMap.SourceNode.apply(this, arguments);
}

SourceNode.prototype = Object.create(sourceMap.SourceNode.prototype, {
	constructor: {
		value: SourceNode,
		enumerable: false,
		writable: true,
		configurable: true
	},
	length: {
		get: function() {
			var len = 0;
			this.walk(function(str) { len += str.length; });
			return len;
		}
	}
});
SourceNode.prototype.stripPrefix = function(offset) {
	var _len;
	while (this.children.length > 0 && offset > 0 && (_len = this.children[0].length) <= offset) {
		this.children.shift();
		offset -= _len;
	}
	if (this.children.length == 0 || offset == 0) return this;
	if (typeof this.children[0] == 'string') {
		this.children[0] = this.children[0].substring(offset);
	} else {
		this.children[0].stripPrefix(offset);
	}
	return this;
};
SourceNode.prototype.stripSuffix = function(offset) {
	var _len, chlen;
	while ((chlen = this.children.length) > 0 && offset > 0 && (_len = this.children[chlen - 1].length) <= offset) {
		this.children.pop();
		offset -= _len;
	}
	if (chlen == 0 || offset == 0) return this;
	if (typeof this.children[chlen-1] == 'string') {
		this.children[chlen-1] = this.children[0].slice(0, -offset);
	} else {
		this.children[chlen-1].stripSuffix(offset);
	}
	return this;
};
SourceNode.prototype.map = function(f) {
	this.children = this.children.map(function(chunk) {
		if (chunk instanceof sourceMap.SourceNode) {
			return chunk.map(f);
		} else {
			return f(chunk);
		}
	});
	return this;
};
SourceNode.prototype.lastChar = function() {
	for (var i = this.children.length; i--; ) {
		var ret;
		if (typeof this.children[i] == 'string') {
			ret = this.children[i].slice(-1);
		} else {
			ret = this.children[i].lastChar();
		}
		if (ret) return ret;
	}
	return '';
};
module.exports = Object.create(sourceMap, { SourceNode: { value: SourceNode } });

})(typeof exports !== 'undefined' ? exports : (Streamline.sourceMap = Streamline.sourceMap || {}));

<|endoftext|>


<commit_before>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true, unused: false*/
/*global prepros,  _, $*/

//Title Bar controls
prepros.controller('TitlebarCtrl', function ($scope, config, utils) {

    'use strict';

    var path = require('path');

    //Support Author Link
    $scope.supportAuthor = function () {

        utils.openBrowser(config.online.loveUrl);

    };

    //Help Link
    $scope.help = function () {

        utils.openBrowser(config.online.helpUrl);

    };

    //Open about window on click
    var aboutWindow;
    $scope.openAboutWindow = function () {

        if (aboutWindow) {

            aboutWindow.show();
            aboutWindow.focus();

        } else {

            var aboutPath = 'file:///' + path.normalize(config.basePath + '/html/about.html');

            aboutWindow = require('nw.gui').Window.open(aboutPath, {
                position: 'center',
                width: 500,
                height: 400,
                frame: true,
                toolbar: false,
                icon: 'app/assets/img/icons/128.png',
                resizable: false
            });

            aboutWindow.on('close', function () {
                aboutWindow.close(true);
                aboutWindow = null;
            });
        }

        //Close about window when main window is closed
        require('nw.gui').Window.get().on('close', function () {

            if (aboutWindow) {
                aboutWindow.close();
            }

        });
    };

    //Open Log window
    var logWindow;
    $scope.openLogWindow = function () {

        if (logWindow) {

            logWindow.focus();
            logWindow.show();

        } else {

            var logPath = 'file:///' + path.normalize(config.basePath + '/html/log.html');

            logWindow = require('nw.gui').Window.open(logPath, {
                position: 'center',
                width: 850,
                height: 500,
                frame: true,
                toolbar: false,
                icon: 'app/assets/img/icons/128.png',
                resizable: false
            });

            logWindow.on('close', function () {
                logWindow.close(true);
                logWindow = null;
            });
        }

        //Close log window when main window close
        require('nw.gui').Window.get().on('close', function () {

            if (logWindow) {
                logWindow.close();
            }

        });
    };

    //Open Options Window
    var optionsWindow;
    $scope.openOptionsWindow = function () {

        //Inject config object to global so options window can read it
        global.userConfig = config.getUserOptions();

        if (optionsWindow) {

            optionsWindow.show();
            optionsWindow.focus();

        } else {

            var optionsPath = 'file:///' + path.normalize(config.basePath + '/html/options.html');

            optionsWindow = require('nw.gui').Window.open(optionsPath, {
                position: 'center',
                width: 600,
                height: 620,
                frame: true,
                toolbar: false,
                icon: 'app/assets/img/icons/128.png',
                resizable: false
            });

            optionsWindow.on('close', function () {
                config.saveUserOptions(global.userConfig);
                optionsWindow.close(true);
                optionsWindow = null;
            });
        }

        //Close options window when main window is closed
        require('nw.gui').Window.get().on('close', function () {

            if (optionsWindow) {
                optionsWindow.close();
            }
        });

    };

    //Minimize app to tray by hiding the window
    $scope.toTray = function(){
        require('nw.gui').Window.get().hide();
    };

    //Minimize app
    $scope.minimize = function(){
        require('nw.gui').Window.get().minimize();
    };

    //Close App
    $scope.close = function(){
        require('nw.gui').Window.get().close();
    };

    //Update Checker

    $scope.appUpdate = false;

    $scope.goWebsite = function(){

        utils.openBrowser(config.online.url);

    };

    $.ajaxSetup({
        cache: false
    });

    $.getJSON(config.online.updateFileUrl, {version: config.version}).done(function(data) {

        if(config.version !== data[0].version){

            $scope.appUpdate = true;

            if(!$scope.$$phase){
                $scope.$apply();
            }
        }
    });
});<commit_msg>updated update checker<commit_after>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true, unused: false*/
/*global prepros,  _, $*/

//Title Bar controls
prepros.controller('TitlebarCtrl', function ($scope, config, utils) {

    'use strict';

    var path = require('path');

    //Support Author Link
    $scope.supportAuthor = function () {

        utils.openBrowser(config.online.loveUrl);

    };

    //Help Link
    $scope.help = function () {

        utils.openBrowser(config.online.helpUrl);

    };

    //Open about window on click
    var aboutWindow;
    $scope.openAboutWindow = function () {

        if (aboutWindow) {

            aboutWindow.show();
            aboutWindow.focus();

        } else {

            var aboutPath = 'file:///' + path.normalize(config.basePath + '/html/about.html');

            aboutWindow = require('nw.gui').Window.open(aboutPath, {
                position: 'center',
                width: 500,
                height: 400,
                frame: true,
                toolbar: false,
                icon: 'app/assets/img/icons/128.png',
                resizable: false
            });

            aboutWindow.on('close', function () {
                aboutWindow.close(true);
                aboutWindow = null;
            });
        }

        //Close about window when main window is closed
        require('nw.gui').Window.get().on('close', function () {

            if (aboutWindow) {
                aboutWindow.close();
            }

        });
    };

    //Open Log window
    var logWindow;
    $scope.openLogWindow = function () {

        if (logWindow) {

            logWindow.focus();
            logWindow.show();

        } else {

            var logPath = 'file:///' + path.normalize(config.basePath + '/html/log.html');

            logWindow = require('nw.gui').Window.open(logPath, {
                position: 'center',
                width: 850,
                height: 500,
                frame: true,
                toolbar: false,
                icon: 'app/assets/img/icons/128.png',
                resizable: false
            });

            logWindow.on('close', function () {
                logWindow.close(true);
                logWindow = null;
            });
        }

        //Close log window when main window close
        require('nw.gui').Window.get().on('close', function () {

            if (logWindow) {
                logWindow.close();
            }

        });
    };

    //Open Options Window
    var optionsWindow;
    $scope.openOptionsWindow = function () {

        //Inject config object to global so options window can read it
        global.userConfig = config.getUserOptions();

        if (optionsWindow) {

            optionsWindow.show();
            optionsWindow.focus();

        } else {

            var optionsPath = 'file:///' + path.normalize(config.basePath + '/html/options.html');

            optionsWindow = require('nw.gui').Window.open(optionsPath, {
                position: 'center',
                width: 600,
                height: 620,
                frame: true,
                toolbar: false,
                icon: 'app/assets/img/icons/128.png',
                resizable: false
            });

            optionsWindow.on('close', function () {
                config.saveUserOptions(global.userConfig);
                optionsWindow.close(true);
                optionsWindow = null;
            });
        }

        //Close options window when main window is closed
        require('nw.gui').Window.get().on('close', function () {

            if (optionsWindow) {
                optionsWindow.close();
            }
        });

    };

    //Minimize app to tray by hiding the window
    $scope.toTray = function(){
        require('nw.gui').Window.get().hide();
    };

    //Minimize app
    $scope.minimize = function(){
        require('nw.gui').Window.get().minimize();
    };

    //Close App
    $scope.close = function(){
        require('nw.gui').Window.get().close();
    };

    //Update Checker
    $scope.goWebsite = function(){

        utils.openBrowser(config.online.url);

    };

    $.ajaxSetup({
        cache: false
    });

    $scope.appUpdate = false;

    $.getJSON(config.online.updateFileUrl, {version: config.version}).done(function(data) {

        if(config.version !== data[0].version){

            $scope.appUpdate = true;

            if(!$scope.$$phase){
                $scope.$apply();
            }
        }
    });
});<|endoftext|>


<commit_before>const fs = require('fs');
const mongoose = require('mongoose');
const path = require('path');
const {execSync} = require('child_process');
const Country = require('../models/Country.js');

const testUri = 'mongodb://localhost:27017/country-love-test';
mongoose.connect(testUri, {useMongoClient: true});

const defaultUrl = '../factbook.json';
module.exports = (url = defaultUrl) => {
    try {
        let factbook = fs.readdirSync(url);
        factbook = factbook.filter(area => !area.split('').includes('.'));
        factbook.forEach(area => {
            let countries = fs.readdirSync(path.join(url, area));
            countries.forEach(country => {
                execSync(`mongoimport --db country-love-test --collection countriesRaw --file ${path.join(url, area, country)}`);
            });
        });
    }
    catch(err) {
        console.log('ERROR: fillMongo failed'); // eslint-disable-line
        console.log(err);                       // eslint-disable-line
    }

    return true;
};<commit_msg>removed uneccesary Country declaration<commit_after>const fs = require('fs');
const mongoose = require('mongoose');
const path = require('path');
const {execSync} = require('child_process');

const testUri = 'mongodb://localhost:27017/country-love-test';
mongoose.connect(testUri, {useMongoClient: true});

const defaultUrl = '../factbook.json';
module.exports = (url = defaultUrl) => {
    try {
        let factbook = fs.readdirSync(url);
        factbook = factbook.filter(area => !area.split('').includes('.'));
        factbook.forEach(area => {
            let countries = fs.readdirSync(path.join(url, area));
            countries.forEach(country => {
                execSync(`mongoimport --db country-love-test --collection countriesRaw --file ${path.join(url, area, country)}`);
            });
        });
    }
    catch(err) {
        console.log('ERROR: fillMongo failed'); // eslint-disable-line
        console.log(err);                       // eslint-disable-line
    }

    return true;
};<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name eventPlannerApp.controller:AddeventformCtrl
 * @description
 * # AddeventformCtrl
 * Controller of the eventPlannerApp
 */

angular.module('eventPlannerApp')
  .controller('AddeventformCtrl', ['$firebaseArray', 'FireBase', function ($firebaseArray, FireBase) {

    var ref = new Firebase(FireBase.link + '/events');
    var vm = this;
    var date = moment().format('YYYY-MM-DD');
    var time = moment().format('hh:mm');
    this.setDate = date + 'T' + time;
    this.collection = $firebaseArray(ref);
    this.eventDefault = function(){
      vm.selectedStartDate = new Date(vm.setDate);
      vm.selectedEndDate = vm.selectedStartDate;
      return {
        name: '',
        category: '',
        startDate: date,
        startTime: time,
        endDate: '',
        endTime: '',
        host: '',
        guests: [],
        eventLocation: '',
        additionalInfo: ''
      };
    };

    this.event = this.eventDefault();

    this.addEvent = function(){
      vm.event.startDate = moment(vm.selectedStartDate).format('YYYY-MM-DD');
      vm.event.startTime = moment(vm.selectedStartDate).format('hh:mm');
      vm.event.endDate = moment(vm.selectedEndDate).format('YYYY-MM-DD');
      vm.event.endTime = moment(vm.selectedEndDate).format('hh:mm');
      vm.collection.$add(vm.event);
      vm.event = vm.eventDefault();
    };

    this.submit = function(isValid){
      if(isValid){
        vm.addEvent();
      }
    };

    this.updateEndDate = function(){
      vm.selectedEndDate = vm.selectedStartDate;
    };

  }

]);
<commit_msg>Added function for add guest input<commit_after>'use strict';

/**
 * @ngdoc function
 * @name eventPlannerApp.controller:AddeventformCtrl
 * @description
 * # AddeventformCtrl
 * Controller of the eventPlannerApp
 */

angular.module('eventPlannerApp')
  .controller('AddeventformCtrl', ['$firebaseArray', 'FireBase', function ($firebaseArray, FireBase) {

    var ref = new Firebase(FireBase.link + '/events');
    var vm = this;
    var date = moment().format('YYYY-MM-DD');
    var time = moment().format('hh:mm');
    this.setDate = date + 'T' + time;
    this.collection = $firebaseArray(ref);
    this.eventDefault = function(){
      vm.selectedStartDate = new Date(vm.setDate);
      vm.selectedEndDate = vm.selectedStartDate;
      return {
        name: '',
        category: '',
        startDate: date,
        startTime: time,
        endDate: '',
        endTime: '',
        host: '',
        guests: [],
        eventLocation: '',
        additionalInfo: ''
      };
    };

    this.event = this.eventDefault();

    this.addEvent = function(){
      vm.event.startDate = moment(vm.selectedStartDate).format('YYYY-MM-DD');
      vm.event.startTime = moment(vm.selectedStartDate).format('hh:mm');
      vm.event.endDate = moment(vm.selectedEndDate).format('YYYY-MM-DD');
      vm.event.endTime = moment(vm.selectedEndDate).format('hh:mm');
      vm.collection.$add(vm.event);
      vm.event = vm.eventDefault();
    };

    this.submit = function(isValid){
      if(isValid){
        vm.addEvent();
      }
    };

    this.updateEndDate = function(){
      vm.selectedEndDate = vm.selectedStartDate;
    };

    this.addGuest = function(e){
      var duplicate = false;
      console.log(e);
      for(var i = 0; i<vm.event.guests.length && !duplicate; i++){
        if(vm.guest === vm.event.guests[i]){
          duplicate = true;
          console.log(duplicate);
        }
      }

      if(e.which === 13 || e === 'click'){

        if(!duplicate){
          vm.event.guests.push(vm.guest);
          console.log(vm.guest.length);
          vm.guest = ' ';

        }

      }
    };

    this.removeGuest = function(index){
      console.log(index);
      vm.event.guests.splice(index, 1);
    };

  }

]);
<|endoftext|>


<commit_before>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log.js")
  , exec = require("./exec.js")
  , npm = require("../npm.js")
  , path = require("path")
  , readJson = require("./read-json.js")
  , fs = require("graceful-fs")
  , chain = require("slide").chain
  , constants = require("constants")
  , output = require("./output.js")

function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
  if (typeof cb !== "function") cb = failOk, failOk = false
  if (typeof cb !== "function") cb = unsafe, unsafe = false
  if (typeof cb !== "function") cb = wd, wd = null

  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))

  log(pkg._id, stage)
  if (!pkg.scripts) pkg.scripts = {}

  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)

    unsafe = unsafe || npm.config.get("unsafe-perm")

    if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
        && !unsafe && pkg.scripts[stage]) {
      log.warn(pkg._id+" "+pkg.scripts[stage], "skipping, cannot run in "+wd)
      return cb()
    }

    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage

    // "nobody" typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd

    lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
  })
}

function checkForLink (pkg, cb) {
  var f = path.join(npm.dir, pkg.name)
  fs.lstat(f, function (er, s) {
    cb(null, !(er || !s.isSymbolicLink()))
  })
}

function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
  var PATH = []
    , p = wd.split("node_modules")
    , acc = path.resolve(p.shift())
  p.forEach(function (pp) {
    PATH.unshift(path.join(acc, "node_modules", ".bin"))
    acc = path.join(acc, "node_modules", pp)
  })
  PATH.unshift(path.join(acc, "node_modules", ".bin"))
  if (env.PATH) PATH.push(env.PATH)
  env.PATH = PATH.join(process.platform === "win32" ? ";" : ":")

  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)

  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
  }

  if (failOk) {
    cb = (function (cb_) { return function (er) {
      if (er) log.warn(er.message, "continuing anyway")
      cb_()
    }})(cb)
  }

  if (npm.config.get("force")) {
    cb = (function (cb_) { return function (er) {
      if (er) log(er, "forced, continuing")
      cb_()
    }})(cb)
  }

  chain
    ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
      , [runHookLifecycle, pkg, env, wd, unsafe] ]
    , cb )
}

function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error("Could not find suitable wd"))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}

function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = env.npm_lifecycle_script
    , sh = "sh"
    , shFlag = "-c"

  if (process.platform === "win32") {
    sh = "cmd"
    shFlag = "/c"
  }

  log.verbose(unsafe, "unsafe-perm in lifecycle")

  output.write("\n> "+pkg._id+" " + stage+" "+wd+"\n> "+cmd+"\n", function (er) {
    if (er) return cb(er)

    exec( sh, [shFlag, cmd], env, true, wd
        , user, group
        , function (er, code, stdout, stderr) {
      if (er && !npm.ROLLBACK) {
        log("Failed to exec "+stage+" script", pkg._id)
        er.message = pkg._id + " "
                   + stage + ": `" + env.npm_lifecycle_script+"`\n"
                   + er.message
        if (er.errno !== constants.EPERM) {
          er.errno = npm.ELIFECYCLE
        }
        er.pkgid = pkg._id
        er.stage = stage
        er.script = env.npm_lifecycle_script
        er.pkgname = pkg.name
        return cb(er)
      } else if (er) {
        log.error(er, pkg._id+"."+stage)
        log.error("failed, but continuing anyway", pkg._id+"."+stage)
        return cb()
      }
      cb(er)
    })
  })
}

function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
    , hook = path.join(npm.dir, ".hooks", stage)
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = hook

  fs.stat(hook, function (er) {
    if (er) return cb()

    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er) {
      if (er) {
        er.message += "\nFailed to exec "+stage+" hook script"
        log(er, pkg._id)
      }
      if (npm.ROLLBACK) return cb()
      cb(er)
    })
  })
}

function makeEnv (data, prefix, env) {
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) if (!i.match(/^npm_/)) {
      env[i] = process.env[i]
    }

    // npat asks for tap output
    if (npm.config.get("npat")) env.TAP = 1

    // express and others respect the NODE_ENV value.
    if (npm.config.get("production")) env.NODE_ENV = "production"

  } else if (!data.hasOwnProperty("_lifecycleEnv")) {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      try {
        // quick and dirty detection for cyclical structures
        JSON.stringify(data[i])
        makeEnv(data[i], envKey+"_", env)
      } catch (ex) {
        // usually these are package objects.
        // just get the path and basic details.
        var d = data[i]
        makeEnv( { name: d.name, version: d.version, path:d.path }
               , envKey+"_", env)
      }
    } else {
      env[envKey] = String(data[i])
      env[envKey] = -1 !== env[envKey].indexOf("\n")
                  ? JSON.stringify(env[envKey])
                  : env[envKey]
    }

  }

  if (prefix !== "npm_package_") return env

  prefix = "npm_config_"
  var pkgConfig = {}
    , ini = require("./ini.js")
    , keys = ini.keys
    , pkgVerConfig = {}
    , namePref = data.name + ":"
    , verPref = data.name + "@" + data.version + ":"

  keys.forEach(function (i) {
    if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
      return
    }
    var value = String(ini.get(i))
    value = -1 !== value.indexOf("\n")
          ? JSON.stringify(value)
          : value
    i = i.replace(/^_+/, "")
    if (i.indexOf(namePref) === 0) {
      var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgConfig[ k ] = value
    } else if (i.indexOf(verPref) === 0) {
      var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgVerConfig[ k ] = value
    }
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
    env[envKey] = value
  })

  prefix = "npm_package_config_"
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix+i)
      env[envKey] = conf[i]
    }
  })

  return env
}

function cmd (stage) {
  function CMD (args, cb) {
    if (args.length) {
      chain(args.map(function (p) {
        return [npm.commands, "run-script", [p, stage]]
      }), cb)
    } else npm.commands["run-script"]([stage], cb)
 }
  CMD.usage = "npm "+stage+" <name>"
  var installedShallow = require("./completion/installed-shallow.js")
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
<commit_msg>Don't pass false confs to child procs as 'false' string<commit_after>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log.js")
  , exec = require("./exec.js")
  , npm = require("../npm.js")
  , path = require("path")
  , readJson = require("./read-json.js")
  , fs = require("graceful-fs")
  , chain = require("slide").chain
  , constants = require("constants")
  , output = require("./output.js")

function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
  if (typeof cb !== "function") cb = failOk, failOk = false
  if (typeof cb !== "function") cb = unsafe, unsafe = false
  if (typeof cb !== "function") cb = wd, wd = null

  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))

  log(pkg._id, stage)
  if (!pkg.scripts) pkg.scripts = {}

  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)

    unsafe = unsafe || npm.config.get("unsafe-perm")

    if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
        && !unsafe && pkg.scripts[stage]) {
      log.warn(pkg._id+" "+pkg.scripts[stage], "skipping, cannot run in "+wd)
      return cb()
    }

    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage

    // "nobody" typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd

    lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
  })
}

function checkForLink (pkg, cb) {
  var f = path.join(npm.dir, pkg.name)
  fs.lstat(f, function (er, s) {
    cb(null, !(er || !s.isSymbolicLink()))
  })
}

function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
  var PATH = []
    , p = wd.split("node_modules")
    , acc = path.resolve(p.shift())
  p.forEach(function (pp) {
    PATH.unshift(path.join(acc, "node_modules", ".bin"))
    acc = path.join(acc, "node_modules", pp)
  })
  PATH.unshift(path.join(acc, "node_modules", ".bin"))
  if (env.PATH) PATH.push(env.PATH)
  env.PATH = PATH.join(process.platform === "win32" ? ";" : ":")

  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)

  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
  }

  if (failOk) {
    cb = (function (cb_) { return function (er) {
      if (er) log.warn(er.message, "continuing anyway")
      cb_()
    }})(cb)
  }

  if (npm.config.get("force")) {
    cb = (function (cb_) { return function (er) {
      if (er) log(er, "forced, continuing")
      cb_()
    }})(cb)
  }

  chain
    ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
      , [runHookLifecycle, pkg, env, wd, unsafe] ]
    , cb )
}

function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error("Could not find suitable wd"))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}

function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = env.npm_lifecycle_script
    , sh = "sh"
    , shFlag = "-c"

  if (process.platform === "win32") {
    sh = "cmd"
    shFlag = "/c"
  }

  log.verbose(unsafe, "unsafe-perm in lifecycle")

  output.write("\n> "+pkg._id+" " + stage+" "+wd+"\n> "+cmd+"\n", function (er) {
    if (er) return cb(er)

    exec( sh, [shFlag, cmd], env, true, wd
        , user, group
        , function (er, code, stdout, stderr) {
      if (er && !npm.ROLLBACK) {
        log("Failed to exec "+stage+" script", pkg._id)
        er.message = pkg._id + " "
                   + stage + ": `" + env.npm_lifecycle_script+"`\n"
                   + er.message
        if (er.errno !== constants.EPERM) {
          er.errno = npm.ELIFECYCLE
        }
        er.pkgid = pkg._id
        er.stage = stage
        er.script = env.npm_lifecycle_script
        er.pkgname = pkg.name
        return cb(er)
      } else if (er) {
        log.error(er, pkg._id+"."+stage)
        log.error("failed, but continuing anyway", pkg._id+"."+stage)
        return cb()
      }
      cb(er)
    })
  })
}

function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
    , hook = path.join(npm.dir, ".hooks", stage)
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = hook

  fs.stat(hook, function (er) {
    if (er) return cb()

    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er) {
      if (er) {
        er.message += "\nFailed to exec "+stage+" hook script"
        log(er, pkg._id)
      }
      if (npm.ROLLBACK) return cb()
      cb(er)
    })
  })
}

function makeEnv (data, prefix, env) {
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) if (!i.match(/^npm_/)) {
      env[i] = process.env[i]
    }

    // npat asks for tap output
    if (npm.config.get("npat")) env.TAP = 1

    // express and others respect the NODE_ENV value.
    if (npm.config.get("production")) env.NODE_ENV = "production"

  } else if (!data.hasOwnProperty("_lifecycleEnv")) {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      try {
        // quick and dirty detection for cyclical structures
        JSON.stringify(data[i])
        makeEnv(data[i], envKey+"_", env)
      } catch (ex) {
        // usually these are package objects.
        // just get the path and basic details.
        var d = data[i]
        makeEnv( { name: d.name, version: d.version, path:d.path }
               , envKey+"_", env)
      }
    } else {
      env[envKey] = String(data[i])
      env[envKey] = -1 !== env[envKey].indexOf("\n")
                  ? JSON.stringify(env[envKey])
                  : env[envKey]
    }

  }

  if (prefix !== "npm_package_") return env

  prefix = "npm_config_"
  var pkgConfig = {}
    , ini = require("./ini.js")
    , keys = ini.keys
    , pkgVerConfig = {}
    , namePref = data.name + ":"
    , verPref = data.name + "@" + data.version + ":"

  keys.forEach(function (i) {
    if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
      return
    }
    var value = ini.get(i)
    if (!value) value = ""
    else if (typeof value !== "string") value = JSON.stringify(value)

    value = -1 !== value.indexOf("\n")
          ? JSON.stringify(value)
          : value
    i = i.replace(/^_+/, "")
    if (i.indexOf(namePref) === 0) {
      var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgConfig[ k ] = value
    } else if (i.indexOf(verPref) === 0) {
      var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgVerConfig[ k ] = value
    }
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
    env[envKey] = value
  })

  prefix = "npm_package_config_"
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix+i)
      env[envKey] = conf[i]
    }
  })

  return env
}

function cmd (stage) {
  function CMD (args, cb) {
    if (args.length) {
      chain(args.map(function (p) {
        return [npm.commands, "run-script", [p, stage]]
      }), cb)
    } else npm.commands["run-script"]([stage], cb)
 }
  CMD.usage = "npm "+stage+" <name>"
  var installedShallow = require("./completion/installed-shallow.js")
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
<|endoftext|>


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

  angular.module('dimApp')
    .factory('infuseService', infuseService);

  infuseService.$inject = [];

  function infuseService() {

    var _data = {
      source: null,
      targets: [],
      infused: 0,
      view: [],
      infusable: [],
      // huge props to /u/Apswny https://github.com/Apsu
      calculate: function() {
        var base = _data.source.primStat.value,
            scaler = _data.source.tier === 'Exotic' ? 0.7 : 0.8,
            step = _data.source.tier === 'Exotic' ? 4 : 6;

        _data.targets.forEach(function(target) {
          var target = target.primStat.value,
              diff = target - base;

        if (diff <= step) {
            base = target;
          } else {
            base += Math.round(diff * scaler);
          }
        });
        return base;
      }
    };

    return {
      setSourceItem: function(item) {
        // Set the source and reset the targets
        _data.source = item;
        _data.infused = 0;
        _data.targets = [];
      },
      setInfusibleItems: function(items) {
        _data.infusable = items;
        _data.view = items;
      },
      toggleItem: function(item) {

        // Add or remove the item from the infusion chain
        var index = _.indexOf(_data.targets, item);
        if (index > -1) {
          _data.targets.splice(index, 1);
        }
        else {
          _data.targets.push(item);
        }

        // Value of infused result
        _data.infused = _data.calculate();
        // The difference from start to finish
        _data.difference = _data.infused - _data.source.primStat.value;

        // let's remove the used gear and the one that are lower than the infused result
        _data.view = _.chain(_data.infusable)
          .difference(_data.targets)
          .filter(function(item) {
            return item.primStat.value > _data.infused;
          })
          .value();

      },
      data: _data,
    }

  }

})();
<commit_msg>separate out the infuse logic from the calculate logic<commit_after>(function() {
  'use strict';

  angular.module('dimApp')
    .factory('infuseService', infuseService);

  infuseService.$inject = [];

  function infuseService() {

    var _data = {
      source: null,
      targets: [],
      infused: 0,
      view: [],
      infusable: [],
      // huge props to /u/Apswny https://github.com/Apsu
      infuse: function(source, target, scaler, step) {
        var diff = target - source;

        if (diff <= step) {
            return target;
        }
        return source + Math.round(diff * scaler);
      },
      calculate: function() {
        var base = _data.source.primStat.value,
            scaler = _data.source.tier === 'Exotic' ? 0.7 : 0.8,
            step = _data.source.tier === 'Exotic' ? 4 : 6;

        _data.targets.forEach(function(target) {
          base = _data.infuse(base, target.primStat.value, scaler, step);
        });
        return base;
      }
    };

    return {
      setSourceItem: function(item) {
        // Set the source and reset the targets
        _data.source = item;
        _data.infused = 0;
        _data.targets = [];
      },
      setInfusibleItems: function(items) {
        _data.infusable = items;
        _data.view = items;
      },
      toggleItem: function(item) {

        // Add or remove the item from the infusion chain
        var index = _.indexOf(_data.targets, item);
        if (index > -1) {
          _data.targets.splice(index, 1);
        }
        else {
          _data.targets.push(item);
        }

        // Value of infused result
        _data.infused = _data.calculate();
        // The difference from start to finish
        _data.difference = _data.infused - _data.source.primStat.value;

        // let's remove the used gear and the one that are lower than the infused result
        _data.view = _.chain(_data.infusable)
          .difference(_data.targets)
          .filter(function(item) {
            return item.primStat.value > _data.infused;
          })
          .value();

      },
      data: _data,
    }

  }

})();
<|endoftext|>


<commit_before>const parseDiff = require('parse-diff')
const shouldExcludeFile = require('./should-exclude-file')
const getDiff = require('./get-diff')
const getDetails = require('./get-details')
const checkForBody = require('./check-for-body')
const defaultConfig = require('./default-config')
const generateLabel = require('./generate-label')

module.exports = async (context, handler) => {
  // Grab the config file
  const configFile = await context.config('config.yml')
  const config = configFile && configFile.todo ? Object.assign({}, defaultConfig, configFile.todo) : defaultConfig
  const keywords = Array.isArray(config.keyword) ? config.keyword : [config.keyword]

  // Ensure that all the labels we need are present
  const labels = await generateLabel(context, config)

  // Get the diff for this commit or PR
  const diff = await getDiff(context)

  // RegEx that matches lines with the configured keywords
  const regex = new RegExp(`.*(?<keyword>${keywords.join('|')})\\s?:?(?<title>.*)`)

  // Parse the diff as files
  const files = parseDiff(diff)

  for (const file of files) {
    if (shouldExcludeFile(context.log, file.to, config.exclude)) continue

    // Loop through every chunk in the file
    for (const chunk of file.chunks) {
      // Chunks can have multiple changes
      for (const indexStr in chunk.changes) {
        const index = parseInt(indexStr, 10)
        const change = chunk.changes[index]

        // Only act on added or deleted lines
        if (!['add', 'del'].includes(change.type)) continue

        // Attempt to find a matching line: TODO Something something
        const matches = regex.exec(change.content)
        if (!matches) continue

        // Get the details of this commit or PR
        const deets = getDetails({ context, config, chunk, line: change.ln || change.ln2 })

        const { owner, repo } = context.repo()
        context.log(`Item found [${matches.groups.title}] in [${owner}/${repo}] at [${deets.sha}]`)

        // Run the handler for this webhook listener
        await handler({
          title: matches.groups.title,
          keyword: matches.groups.keyword,
          bodyComment: checkForBody(chunk.changes, index, config),
          filename: file.to,
          config,
          chunk,
          index,
          labels,
          ...deets
        })
      }
    }
  }
}
<commit_msg>Trim the title<commit_after>const parseDiff = require('parse-diff')
const shouldExcludeFile = require('./should-exclude-file')
const getDiff = require('./get-diff')
const getDetails = require('./get-details')
const checkForBody = require('./check-for-body')
const defaultConfig = require('./default-config')
const generateLabel = require('./generate-label')

module.exports = async (context, handler) => {
  // Grab the config file
  const configFile = await context.config('config.yml')
  const config = configFile && configFile.todo ? Object.assign({}, defaultConfig, configFile.todo) : defaultConfig
  const keywords = Array.isArray(config.keyword) ? config.keyword : [config.keyword]

  // Ensure that all the labels we need are present
  const labels = await generateLabel(context, config)

  // Get the diff for this commit or PR
  const diff = await getDiff(context)

  // RegEx that matches lines with the configured keywords
  const regex = new RegExp(`.*(?<keyword>${keywords.join('|')})\\s?:?(?<title>.*)`)

  // Parse the diff as files
  const files = parseDiff(diff)

  for (const file of files) {
    if (shouldExcludeFile(context.log, file.to, config.exclude)) continue

    // Loop through every chunk in the file
    for (const chunk of file.chunks) {
      // Chunks can have multiple changes
      for (const indexStr in chunk.changes) {
        const index = parseInt(indexStr, 10)
        const change = chunk.changes[index]

        // Only act on added or deleted lines
        if (!['add', 'del'].includes(change.type)) continue

        // Attempt to find a matching line: TODO Something something
        const matches = regex.exec(change.content)
        if (!matches) continue

        const title = matches.groups.title.trim()

        // Get the details of this commit or PR
        const deets = getDetails({ context, config, chunk, line: change.ln || change.ln2 })

        const { owner, repo } = context.repo()
        context.log(`Item found [${title}] in [${owner}/${repo}] at [${deets.sha}]`)

        // Run the handler for this webhook listener
        await handler({
          keyword: matches.groups.keyword,
          bodyComment: checkForBody(chunk.changes, index, config),
          filename: file.to,
          title,
          config,
          chunk,
          index,
          labels,
          ...deets
        })
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

// Summary
//  API wrapper for managing Rekit elements.

const _ = require('lodash');
const component = require('./component');
const style = require('./style');
const test = require('./test');
const action = require('./action');
const featureMgr = require('./feature');
const utils = require('./utils');
const vio = require('./vio');
const refactor = require('./refactor');
const entry = require('./entry');
const route = require('./route');
const template = require('./template');
const plugin = require('./plugin');
const constant = require('./constant');

const injectExtensionPoints = plugin.injectExtensionPoints;

function addComponent(feature, name, args) {
  feature = _.kebabCase(feature);
  name = _.pascalCase(name);

  args = args || {};
  component.add(feature, name, {
    templateFile: args.connect ? 'ConnectedComponent.js' : 'Component.js',
  });
  if (args.urlPath) {
    let urlPath = args.urlPath;
    if (urlPath === '$auto') urlPath = name;
    urlPath = _.kebabCase(urlPath);
    route.add(feature, name, { urlPath, isIndex: !!args.isIndex });
  }
  style.add(feature, name);
  test.add(feature, name);
}

function removeComponent(feature, name) {
  feature = _.kebabCase(feature);
  name = _.pascalCase(name);
  component.remove(feature, name);
  route.remove(feature, name);
  style.remove(feature, name);
  test.remove(feature, name);
}

function moveComponent(source, target) {
  source.feature = _.kebabCase(source.feature);
  source.name = _.pascalCase(source.name);
  target.feature = _.kebabCase(target.feature);
  target.name = _.pascalCase(target.name);

  component.move(source, target);
  test.move(source, target);
  style.move(source, target);
  route.move(source, target);
}

// function addPage(feature, name, args) {
//   feature = _.kebabCase(feature);
//   name = _.pascalCase(name);

//   component.add(feature, name, { templateFile: 'ConnectedComponent.js' });
//   entry.addToRoute(feature, name, args);
//   style.add(feature, name);
//   test.add(feature, name, { templateFile: 'ConnectedComponent.test.js' });
// }

// function removePage(feature, name, args) {
//   feature = _.kebabCase(feature);
//   name = _.pascalCase(name);

//   component.remove(feature, name);
//   entry.removeFromRoute(feature, name, args);
//   style.remove(feature, name);
//   test.remove(feature, name);
// }

// function movePage(source, target) {
//   source.feature = _.kebabCase(source.feature);
//   source.name = _.pascalCase(source.name);
//   target.feature = _.kebabCase(target.feature);
//   target.name = _.pascalCase(target.name);

//   moveComponent(source, target);
//   entry.moveRoute(source, target);
// }

function addAsyncAction(feature, name) {
  action.addAsync(feature, name);
  test.addAction(feature, name, { isAsync: true });
}

function removeAsyncAction(feature, name) {
  action.removeAsync(feature, name);
  test.removeAction(feature, name);
}

function moveAsyncAction(source, dest) {
  action.moveAsync(source, dest);
  test.moveAction(source, dest, true);
}

function addAction(feature, name, args) {
  args = args || {};
  if (args.async) {
    addAsyncAction(feature, name);
    return;
  }
  action.add(feature, name);
  test.addAction(feature, name);
}

function removeAction(feature, name, args) {
  args = args || {};
  if (args.async) {
    removeAsyncAction(feature, name);
    return;
  }
  action.remove(feature, name);
  test.removeAction(feature, name);
}

function moveAction(source, dest, args) {
  args = args || {};
  if (args.async) {
    moveAsyncAction(source, dest);
    return;
  }
  action.move(source, dest);
  test.moveAction(source, dest);
}

function addFeature(name) {
  featureMgr.add(name);
  entry.addToRootReducer(name);
  entry.addToRouteConfig(name);
  entry.addToRootStyle(name);

  // Add default page and sample action
  addComponent(name, 'default-page', { isIndex: true, connect: true, urlPath: '$auto' });
  addAction(name, 'sample-action');
}

function removeFeature(name) {
  featureMgr.remove(name);
  entry.removeFromRootReducer(name);
  entry.removeFromRouteConfig(name);
  entry.removeFromRootStyle(name);
}

function moveFeature(oldName, newName) {
  featureMgr.move(oldName, newName);
}

const coreCommands = {
  addComponent: injectExtensionPoints(addComponent, 'add', 'component'),
  removeComponent: injectExtensionPoints(removeComponent, 'remove', 'component'),
  moveComponent: injectExtensionPoints(moveComponent, 'move', 'component'),
  // addPage: injectExtensionPoints(addPage, 'add', 'page'),
  // removePage: injectExtensionPoints(removePage, 'remove', 'page'),
  // movePage: injectExtensionPoints(movePage, 'move', 'page'),
  addAction: injectExtensionPoints(addAction, 'add', 'action'),
  removeAction: injectExtensionPoints(removeAction, 'remove', 'action'),
  moveAction: injectExtensionPoints(moveAction, 'move', 'action'),
  addAsyncAction: injectExtensionPoints(addAsyncAction, 'add', 'async-action'),
  removeAsyncAction: injectExtensionPoints(removeAsyncAction, 'remove', 'async-action'),
  moveAsyncAction: injectExtensionPoints(moveAsyncAction, 'move', 'async-action'),
  addFeature: injectExtensionPoints(addFeature, 'add', 'feature'),
  removeFeature: injectExtensionPoints(removeFeature, 'remove', 'feature'),
  moveFeature: injectExtensionPoints(moveFeature, 'move', 'feature'),
};

function splitName(name) {
  const arr = name.split('/');
  return {
    feature: arr[0],
    name: arr[1],
  };
}

function handleCommand(args) {
  const params = [];
  switch (args.commandName) {
    case 'add':
    case 'remove': {
      if (args.type === 'feature') params.push(args.name);
      else {
        params.push(splitName(args.name).feature);
        params.push(splitName(args.name).name);
      }
      break;
    }
    case 'move': {
      if (args.type === 'feature') {
        params.push(args.source);
        params.push(args.target);
      } else {
        params.push(splitName(args.source));
        params.push(splitName(args.target));
      }
      break;
    }
    default:
      break;
  }
  params.push(args);

  let cmd = plugin.getCommand(args.commandName, args.type);
  if (!cmd) {
    cmd = coreCommands[_.camelCase(args.commandName + '-' + args.type)];
  }

  if (!cmd) {
    utils.fatalError(`Can't find the desired command: ${args.commandName}`);
  }
  cmd.apply(null, params);
}

module.exports = Object.assign({
  vio,
  refactor,
  utils,
  component,
  constant,
  style,
  test,
  action,
  template,
  feature: featureMgr,
  entry,
  route,

  handleCommand,
}, coreCommands);

// NOTE: plugin.loadPlutins should be executed after module.exports to avoid circular dependency
plugin.loadPlugins();
<commit_msg>Fix connected component test<commit_after>'use strict';

// Summary
//  API wrapper for managing Rekit elements.

const _ = require('lodash');
const component = require('./component');
const style = require('./style');
const test = require('./test');
const action = require('./action');
const featureMgr = require('./feature');
const utils = require('./utils');
const vio = require('./vio');
const refactor = require('./refactor');
const entry = require('./entry');
const route = require('./route');
const template = require('./template');
const plugin = require('./plugin');
const constant = require('./constant');

const injectExtensionPoints = plugin.injectExtensionPoints;

function addComponent(feature, name, args) {
  feature = _.kebabCase(feature);
  name = _.pascalCase(name);

  args = args || {};
  component.add(feature, name, {
    templateFile: args.connect ? 'ConnectedComponent.js' : 'Component.js',
  });
  if (args.urlPath) {
    let urlPath = args.urlPath;
    if (urlPath === '$auto') urlPath = name;
    urlPath = _.kebabCase(urlPath);
    route.add(feature, name, { urlPath, isIndex: !!args.isIndex });
  }
  style.add(feature, name);
  test.add(feature, name, {
    templateFile: args.connect ? 'ConnectedComponent.test.js' : 'Component.test.js',
  });
}

function removeComponent(feature, name) {
  feature = _.kebabCase(feature);
  name = _.pascalCase(name);
  component.remove(feature, name);
  route.remove(feature, name);
  style.remove(feature, name);
  test.remove(feature, name);
}

function moveComponent(source, target) {
  source.feature = _.kebabCase(source.feature);
  source.name = _.pascalCase(source.name);
  target.feature = _.kebabCase(target.feature);
  target.name = _.pascalCase(target.name);

  component.move(source, target);
  test.move(source, target);
  style.move(source, target);
  route.move(source, target);
}

// function addPage(feature, name, args) {
//   feature = _.kebabCase(feature);
//   name = _.pascalCase(name);

//   component.add(feature, name, { templateFile: 'ConnectedComponent.js' });
//   entry.addToRoute(feature, name, args);
//   style.add(feature, name);
//   test.add(feature, name, { templateFile: 'ConnectedComponent.test.js' });
// }

// function removePage(feature, name, args) {
//   feature = _.kebabCase(feature);
//   name = _.pascalCase(name);

//   component.remove(feature, name);
//   entry.removeFromRoute(feature, name, args);
//   style.remove(feature, name);
//   test.remove(feature, name);
// }

// function movePage(source, target) {
//   source.feature = _.kebabCase(source.feature);
//   source.name = _.pascalCase(source.name);
//   target.feature = _.kebabCase(target.feature);
//   target.name = _.pascalCase(target.name);

//   moveComponent(source, target);
//   entry.moveRoute(source, target);
// }

function addAsyncAction(feature, name) {
  action.addAsync(feature, name);
  test.addAction(feature, name, { isAsync: true });
}

function removeAsyncAction(feature, name) {
  action.removeAsync(feature, name);
  test.removeAction(feature, name);
}

function moveAsyncAction(source, dest) {
  action.moveAsync(source, dest);
  test.moveAction(source, dest, true);
}

function addAction(feature, name, args) {
  args = args || {};
  if (args.async) {
    addAsyncAction(feature, name);
    return;
  }
  action.add(feature, name);
  test.addAction(feature, name);
}

function removeAction(feature, name, args) {
  args = args || {};
  if (args.async) {
    removeAsyncAction(feature, name);
    return;
  }
  action.remove(feature, name);
  test.removeAction(feature, name);
}

function moveAction(source, dest, args) {
  args = args || {};
  if (args.async) {
    moveAsyncAction(source, dest);
    return;
  }
  action.move(source, dest);
  test.moveAction(source, dest);
}

function addFeature(name) {
  featureMgr.add(name);
  entry.addToRootReducer(name);
  entry.addToRouteConfig(name);
  entry.addToRootStyle(name);

  // Add default page and sample action
  addComponent(name, 'default-page', { isIndex: true, connect: true, urlPath: '$auto' });
  addAction(name, 'sample-action');
}

function removeFeature(name) {
  featureMgr.remove(name);
  entry.removeFromRootReducer(name);
  entry.removeFromRouteConfig(name);
  entry.removeFromRootStyle(name);
}

function moveFeature(oldName, newName) {
  featureMgr.move(oldName, newName);
}

const coreCommands = {
  addComponent: injectExtensionPoints(addComponent, 'add', 'component'),
  removeComponent: injectExtensionPoints(removeComponent, 'remove', 'component'),
  moveComponent: injectExtensionPoints(moveComponent, 'move', 'component'),
  // addPage: injectExtensionPoints(addPage, 'add', 'page'),
  // removePage: injectExtensionPoints(removePage, 'remove', 'page'),
  // movePage: injectExtensionPoints(movePage, 'move', 'page'),
  addAction: injectExtensionPoints(addAction, 'add', 'action'),
  removeAction: injectExtensionPoints(removeAction, 'remove', 'action'),
  moveAction: injectExtensionPoints(moveAction, 'move', 'action'),
  addAsyncAction: injectExtensionPoints(addAsyncAction, 'add', 'async-action'),
  removeAsyncAction: injectExtensionPoints(removeAsyncAction, 'remove', 'async-action'),
  moveAsyncAction: injectExtensionPoints(moveAsyncAction, 'move', 'async-action'),
  addFeature: injectExtensionPoints(addFeature, 'add', 'feature'),
  removeFeature: injectExtensionPoints(removeFeature, 'remove', 'feature'),
  moveFeature: injectExtensionPoints(moveFeature, 'move', 'feature'),
};

function splitName(name) {
  const arr = name.split('/');
  return {
    feature: arr[0],
    name: arr[1],
  };
}

function handleCommand(args) {
  const params = [];
  switch (args.commandName) {
    case 'add':
    case 'remove': {
      if (args.type === 'feature') params.push(args.name);
      else {
        params.push(splitName(args.name).feature);
        params.push(splitName(args.name).name);
      }
      break;
    }
    case 'move': {
      if (args.type === 'feature') {
        params.push(args.source);
        params.push(args.target);
      } else {
        params.push(splitName(args.source));
        params.push(splitName(args.target));
      }
      break;
    }
    default:
      break;
  }
  params.push(args);

  let cmd = plugin.getCommand(args.commandName, args.type);
  if (!cmd) {
    cmd = coreCommands[_.camelCase(args.commandName + '-' + args.type)];
  }

  if (!cmd) {
    utils.fatalError(`Can't find the desired command: ${args.commandName}`);
  }
  cmd.apply(null, params);
}

module.exports = Object.assign({
  vio,
  refactor,
  utils,
  component,
  constant,
  style,
  test,
  action,
  template,
  feature: featureMgr,
  entry,
  route,

  handleCommand,
}, coreCommands);

// NOTE: plugin.loadPlutins should be executed after module.exports to avoid circular dependency
plugin.loadPlugins();
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

const { Transform } = DS;
const { A } = Ember;

export default Transform.extend({
  deserialize: function(serialized) {
    serialized = A(serialized);
    return serialized;
  },
  serialize: function(deserialized) {
    if(!isBlank(deserialized)){
      deserialized = deserialized.toArray();
    }
    return deserialized;
  }
});
<commit_msg>missing Import<commit_after>import Ember from 'ember';
import DS from 'ember-data';

const { Transform } = DS;
const { A } = Ember;
const { isBlank } = Ember;

export default Transform.extend({
  deserialize: function(serialized) {
    serialized = A(serialized);
    return serialized;
  },
  serialize: function(deserialized) {
    if(!isBlank(deserialized)){
      deserialized = deserialized.toArray();
    }
    return deserialized;
  }
});
<|endoftext|>