<commit_before>'use strict';

(function() {
	var _           = require('lodash')
	  , jsonxml     = require('jsontoxml')
	  , qtmrt       = require('./qtmrt')
	  , Packet      = require('./packet')
	  , Component   = require('./component')
	  , writeUInt32 = require('./buffer-io').writeUInt32
	  , byteOrder   = qtmrt.LITTLE_ENDIAN
	;

	class Command {
		static get _byteOrder() { return byteOrder; }
		static set _byteOrder(value) { byteOrder = value; }

		static createPacket(cmdStr) {
			var buf = new Buffer(qtmrt.HEADER_SIZE + cmdStr.length);

			writeUInt32(buf, buf.length, 0, Command._byteOrder);
			writeUInt32(buf, qtmrt.COMMAND, qtmrt.UINT32_SIZE, Command._byteOrder);
			buf.write(cmdStr, qtmrt.HEADER_SIZE, cmdStr.length, 'utf8');

			return new Packet(buf, Command._byteOrder);
		}

		static qtmVersion()             { return this.createPacket('QTMVersion'); }
		static byteOrder()              { return this.createPacket('ByteOrder'); }
		static getState()               { return this.createPacket('GetState'); }
		static releaseControl()         { return this.createPacket('ReleaseControl'); }
		static newMeasurement()         { return this.createPacket('New'); }
		static close()                  { return this.createPacket('Close'); }
		static start()                  { return this.createPacket('Start'); }
		static stop()                   { return this.createPacket('Stop'); }
		static getCaptureC3D()          { return this.createPacket('GetCaptureC3D'); }
		static getCaptureQtm()          { return this.createPacket('GetCaptureQtm'); }
		static trig()                   { return this.createPacket('Trig'); }
		static stopStreaming()          { return this.createPacket('StreamFrames Stop'); }
		static setQtmEvent(label)       { return this.createPacket('SetQTMEvent ' + label); }
		static takeControl(pass)        { return this.createPacket('TakeControl ' + (_.isUndefined(pass) ? '' : pass)); }
		static load(filename)           { return this.createPacket('Load ' + filename); }
		static loadProject(projectPath) { return this.createPacket('LoadProject ' + projectPath); }
		static version(major, minor)    { return this.createPacket('Version ' + major + '.' + minor); }

		static getParameters() {
			var predicate = (component) => {
					return _.includes(['All', 'General', '3D', '6D', 'Analog', 'Force', 'Image'], component);
				}
			   , components = _.filter(arguments, predicate)
			;

			if (_.includes(components, 'All'))
				components = ['All'];

			return this.createPacket('GetParameters ' + components.join(' '));
		}

		static setParameters(params, byteOrder) {
			var xml = jsonxml({ 'QTM_Settings': params }) + '\0'
			  , buf = new Buffer(qtmrt.HEADER_SIZE + xml.length + 1)
			;

			writeUInt32(buf, buf.length, 0);
			writeUInt32(buf, qtmrt.XML, qtmrt.UINT32_SIZE);
			buf.write(xml, qtmrt.HEADER_SIZE);

			return Packet.create(buf, byteOrder);
		}

		static getCurrentFrame() {
			var predicate  = function(component) { return _.includes(_.union(['All'], Object.keys(qtmrt.COMPONENTS)), component); }
			  , components = arguments.length === 0 ? ['All'] : _.filter(arguments, predicate);
			;

			if (_.isEmpty(components))
				throw new TypeError('No valid components specified');

			if (_.includes(components, 'All'))
				components = ['All'];

			return this.createPacket('GetCurrentFrame ' + components.join(' '));
		}

		static streamFrames(options) {
			if (arguments.length === 0)
				options = {};

			options = _.defaults(options, {
				frequency: 100,
				components: ['All'],
			});

			var udp        = _.isUndefined(options.udpPort) ? '' : ' UDP:' + (_.isUndefined(options.udpAddress) ? '' : options.udpAddress + ':') + options.udpPort
			  , frequency  = ''
			  , predicate  = function(component) { return _.includes(_.union(['All'], Object.keys(qtmrt.COMPONENTS)), component); }
			  , components = _.filter(options.components, predicate)
			;

			if (options.frequency < 1)
				frequency = 'FrequencyDivisor:' + (1 / options.frequency);
			else if (isNaN(options.frequency))
				frequency = 'AllFrames';
			else
				frequency = 'Frequency:' + options.frequency;

			if (_.isEmpty(components))
				throw new TypeError('No valid components specified');

			if (_.includes(components, 'All'))
				components = ['All'];

			var cmdStr = 'StreamFrames ' + frequency + udp + ' ' + components.join(' ');
			return this.createPacket(cmdStr);
		}

		static save(filename, overwrite) {
			var cmdStr = 'Save ' + filename + (_.isUndefined(overwrite) ? '' : (' ' + overwrite));
			return this.createPacket(cmdStr);
		}
	}

	module.exports = Command;
})();<commit_msg>Renamed getCaptureC3D -> getCaptureC3d.<commit_after>'use strict';

(function() {
	var _           = require('lodash')
	  , jsonxml     = require('jsontoxml')
	  , qtmrt       = require('./qtmrt')
	  , Packet      = require('./packet')
	  , Component   = require('./component')
	  , writeUInt32 = require('./buffer-io').writeUInt32
	  , byteOrder   = qtmrt.LITTLE_ENDIAN
	;

	class Command {
		static get _byteOrder() { return byteOrder; }
		static set _byteOrder(value) { byteOrder = value; }

		static createPacket(cmdStr) {
			var buf = new Buffer(qtmrt.HEADER_SIZE + cmdStr.length);

			writeUInt32(buf, buf.length, 0, Command._byteOrder);
			writeUInt32(buf, qtmrt.COMMAND, qtmrt.UINT32_SIZE, Command._byteOrder);
			buf.write(cmdStr, qtmrt.HEADER_SIZE, cmdStr.length, 'utf8');

			return new Packet(buf, Command._byteOrder);
		}

		static qtmVersion()             { return this.createPacket('QTMVersion'); }
		static byteOrder()              { return this.createPacket('ByteOrder'); }
		static getState()               { return this.createPacket('GetState'); }
		static releaseControl()         { return this.createPacket('ReleaseControl'); }
		static newMeasurement()         { return this.createPacket('New'); }
		static close()                  { return this.createPacket('Close'); }
		static start()                  { return this.createPacket('Start'); }
		static stop()                   { return this.createPacket('Stop'); }
		static getCaptureC3d()          { return this.createPacket('GetCaptureC3D'); }
		static getCaptureQtm()          { return this.createPacket('GetCaptureQtm'); }
		static trig()                   { return this.createPacket('Trig'); }
		static stopStreaming()          { return this.createPacket('StreamFrames Stop'); }
		static setQtmEvent(label)       { return this.createPacket('SetQTMEvent ' + label); }
		static takeControl(pass)        { return this.createPacket('TakeControl ' + (_.isUndefined(pass) ? '' : pass)); }
		static load(filename)           { return this.createPacket('Load ' + filename); }
		static loadProject(projectPath) { return this.createPacket('LoadProject ' + projectPath); }
		static version(major, minor)    { return this.createPacket('Version ' + major + '.' + minor); }

		static getParameters() {
			var predicate = (component) => {
					return _.includes(['All', 'General', '3D', '6D', 'Analog', 'Force', 'Image'], component);
				}
			   , components = _.filter(arguments, predicate)
			;

			if (_.includes(components, 'All'))
				components = ['All'];

			return this.createPacket('GetParameters ' + components.join(' '));
		}

		static setParameters(params, byteOrder) {
			var xml = jsonxml({ 'QTM_Settings': params }) + '\0'
			  , buf = new Buffer(qtmrt.HEADER_SIZE + xml.length + 1)
			;

			writeUInt32(buf, buf.length, 0);
			writeUInt32(buf, qtmrt.XML, qtmrt.UINT32_SIZE);
			buf.write(xml, qtmrt.HEADER_SIZE);

			return Packet.create(buf, byteOrder);
		}

		static getCurrentFrame() {
			var predicate  = function(component) { return _.includes(_.union(['All'], Object.keys(qtmrt.COMPONENTS)), component); }
			  , components = arguments.length === 0 ? ['All'] : _.filter(arguments, predicate);
			;

			if (_.isEmpty(components))
				throw new TypeError('No valid components specified');

			if (_.includes(components, 'All'))
				components = ['All'];

			return this.createPacket('GetCurrentFrame ' + components.join(' '));
		}

		static streamFrames(options) {
			if (arguments.length === 0)
				options = {};

			options = _.defaults(options, {
				frequency: 100,
				components: ['All'],
			});

			var udp        = _.isUndefined(options.udpPort) ? '' : ' UDP:' + (_.isUndefined(options.udpAddress) ? '' : options.udpAddress + ':') + options.udpPort
			  , frequency  = ''
			  , predicate  = function(component) { return _.includes(_.union(['All'], Object.keys(qtmrt.COMPONENTS)), component); }
			  , components = _.filter(options.components, predicate)
			;

			if (options.frequency < 1)
				frequency = 'FrequencyDivisor:' + (1 / options.frequency);
			else if (isNaN(options.frequency))
				frequency = 'AllFrames';
			else
				frequency = 'Frequency:' + options.frequency;

			if (_.isEmpty(components))
				throw new TypeError('No valid components specified');

			if (_.includes(components, 'All'))
				components = ['All'];

			var cmdStr = 'StreamFrames ' + frequency + udp + ' ' + components.join(' ');
			return this.createPacket(cmdStr);
		}

		static save(filename, overwrite) {
			var cmdStr = 'Save ' + filename + (_.isUndefined(overwrite) ? '' : (' ' + overwrite));
			return this.createPacket(cmdStr);
		}
	}

	module.exports = Command;
})();<|endoftext|>


<commit_before>/* global window: true, document: true */
define(function(require) {
    'use strict';

    var Ember = require('ember'),
        Slider = require('slider/object'),
        generateRandom;

    generateRandom = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    return Ember.Route.extend(require('helpers/update-title'), {
        title: 'music',
        previous: function() {
            var history = this.get('fileSystem.history'),
                queue,
                currentIndex,
                previousIndex,
                snippetId,
                previousSnippet;

            if (history.get('length') > 1) {
                snippetId = history.objectAt(history.get('length') - 2);
            } else {
                queue = this.get('fileSystem.queue');
                currentIndex = queue.indexOf(this.get('audio.snippet.id'));

                if (currentIndex > 0) {
                    previousIndex = currentIndex - 1;
                } else {
                    previousIndex = queue.get('length');
                }

                snippetId = queue.objectAt(previousIndex);
            }

            previousSnippet = this.get('fileSystem.snippets').findBy('id', snippetId);

            this.play(previousSnippet);
        },
        next: function() {
            var queue = this.get('fileSystem.queue'),
                snippetId,
                nextSnippet;

            unplayedSnippetIds = queue.filter(function(snippetId) {
                return !this.get('cache.playedSnippetIds').contains(snippetId);
            }.bind(this));

            if (!unplayedSnippetIds.get('length')) {
                this.set('cache.playedSnippetIds', []);

                unplayedSnippetIds.pushObjects(queue);

                unplayedSnippetIds.removeObject(this.get('audio.snippet.id'));
            }

            snippetId = unplayedSnippetIds.objectAt(generateRandom(0, unplayedSnippetIds.get('length') - 1));

            nextSnippet = this.get('fileSystem.snippets').findBy('id', snippetId);

            this.play(nextSnippet);
        },
        play: function(snippet) {
            var offlineSnippets = this.get('fileSystem.snippets'),
                history,
                queue,
                playedSnippetIds,
                id;

            if (!Ember.isEmpty(snippet)) {
                id = snippet.get('id');
                history = this.get('fileSystem.history');
                queue = this.get('fileSystem.queue');
                playedSnippetIds = this.get('cache.playedSnippetIds');

                if (!offlineSnippets.isAny('id', id)) {
                    offlineSnippets.pushObject(snippet);
                }

                if (history.contains(id)) {
                    history.removeObject(id);
                }

                if (history.get('length') === 50) {
                    history.removeAt(0);
                }

                history.pushObject(id);

                if (!queue.contains(id)) {
                    if (Ember.isEmpty(this.get('audio.snippet.id'))) {
                        queue.pushObject(id);
                    } else {
                        queue.insertAt(queue.indexOf(this.get('audio.snippet.id')) + 1, id);
                    }
                }

                if (!playedSnippetIds.contains(id)) {
                    playedSnippetIds.pushObject(id);
                }

                this.set('fileSystem.playingSnippetId', id);
            }

            this.get('audio').play(snippet);
        },
        actions: {
            loading: function() {
                if (this.get('controller')) {
                    this.set('controller.isLoading', true);

                    this.router.one('didTransition', function() {
                        this.set('controller.isLoading', false);
                    }.bind(this));
                }
            },
            error: function(error) {
                if (this.get('controller')) {
                    this.set('controller.error', error);
                }
            },
            updateTitle: function(tokens) {
                this._super(tokens);

                tokens.reverse();
                document.title = tokens.join(' - ');
            },
            play: function(snippet) {
                this.play(snippet);
            },
            pause: function() {
                this.get('audio').pause();
            },
            scrollToTop: function() {
                if (Ember.$(window).scrollTop()) {
                    window.scrollTo(0, 0);
                } else {
                    this.get('cache').showMessage('Already scrolled to top');
                }
            },
            previous: function() {
                this.previous();
            },
            next: function() {
                this.next();
            },
            didTransition: function() {
                var audio = this.get('audio'),
                    slider;

                slider = Slider.create({
                    onSlideStop: function(value) {
                        audio.setCurrentTime(value);
                    }
                });

                audio.addObserver('currentTime', audio, function() {
                    slider.setValue(this.get('currentTime'));
                });

                audio.addObserver('duration', audio, function() {
                    slider.set('max', this.get('duration'));
                });

                this.set('cache.slider', slider);

                audio.set('didEnd', this.next.bind(this));

                this.set('fileSystem.didParseJSON', function() {
                    audio.load(this.get('snippets').findBy('id', this.get('playingSnippetId')));
                });
            }
        }
    });
});
<commit_msg>Changed logic previous audio.<commit_after>/* global window: true, document: true */
define(function(require) {
    'use strict';

    var Ember = require('ember'),
        Slider = require('slider/object'),
        generateRandom;

    generateRandom = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    return Ember.Route.extend(require('helpers/update-title'), {
        title: 'music',
        previous: function() {
            var history = this.get('fileSystem.history'),
                audio = this.get('audio'),
                currentIndex = history.indexOf(audio.get('snippet.id')),
                snippetId,
                previousSnippet;

            if (currentIndex > 0) {
                snippetId = history.objectAt(currentIndex - 1);

                previousSnippet = this.get('fileSystem.snippets').findBy('id', snippetId);

                audio.play(previousSnippet);
            } else {
                this.get('cache').showMessage('No previous audio');
            }
        },
        next: function() {
            var queue = this.get('fileSystem.queue'),
                snippetId,
                nextSnippet;

            unplayedSnippetIds = queue.filter(function(snippetId) {
                return !this.get('cache.playedSnippetIds').contains(snippetId);
            }.bind(this));

            if (!unplayedSnippetIds.get('length')) {
                this.set('cache.playedSnippetIds', []);

                unplayedSnippetIds.pushObjects(queue);

                unplayedSnippetIds.removeObject(this.get('audio.snippet.id'));
            }

            snippetId = unplayedSnippetIds.objectAt(generateRandom(0, unplayedSnippetIds.get('length') - 1));

            nextSnippet = this.get('fileSystem.snippets').findBy('id', snippetId);

            this.play(nextSnippet);
        },
        play: function(snippet) {
            var offlineSnippets = this.get('fileSystem.snippets'),
                history,
                queue,
                playedSnippetIds,
                id;

            if (!Ember.isEmpty(snippet)) {
                id = snippet.get('id');
                history = this.get('fileSystem.history');
                queue = this.get('fileSystem.queue');
                playedSnippetIds = this.get('cache.playedSnippetIds');

                if (!offlineSnippets.isAny('id', id)) {
                    offlineSnippets.pushObject(snippet);
                }

                if (history.contains(id)) {
                    history.removeObject(id);
                }

                if (history.get('length') === 50) {
                    history.removeAt(0);
                }

                history.pushObject(id);

                if (!queue.contains(id)) {
                    if (Ember.isEmpty(this.get('audio.snippet.id'))) {
                        queue.pushObject(id);
                    } else {
                        queue.insertAt(queue.indexOf(this.get('audio.snippet.id')) + 1, id);
                    }
                }

                if (!playedSnippetIds.contains(id)) {
                    playedSnippetIds.pushObject(id);
                }

                this.set('fileSystem.playingSnippetId', id);
            }

            this.get('audio').play(snippet);
        },
        actions: {
            loading: function() {
                if (this.get('controller')) {
                    this.set('controller.isLoading', true);

                    this.router.one('didTransition', function() {
                        this.set('controller.isLoading', false);
                    }.bind(this));
                }
            },
            error: function(error) {
                if (this.get('controller')) {
                    this.set('controller.error', error);
                }
            },
            updateTitle: function(tokens) {
                this._super(tokens);

                tokens.reverse();
                document.title = tokens.join(' - ');
            },
            play: function(snippet) {
                this.play(snippet);
            },
            pause: function() {
                this.get('audio').pause();
            },
            scrollToTop: function() {
                if (Ember.$(window).scrollTop()) {
                    window.scrollTo(0, 0);
                } else {
                    this.get('cache').showMessage('Already scrolled to top');
                }
            },
            previous: function() {
                this.previous();
            },
            next: function() {
                this.next();
            },
            didTransition: function() {
                var audio = this.get('audio'),
                    slider;

                slider = Slider.create({
                    onSlideStop: function(value) {
                        audio.setCurrentTime(value);
                    }
                });

                audio.addObserver('currentTime', audio, function() {
                    slider.setValue(this.get('currentTime'));
                });

                audio.addObserver('duration', audio, function() {
                    slider.set('max', this.get('duration'));
                });

                this.set('cache.slider', slider);

                audio.set('didEnd', this.next.bind(this));

                this.set('fileSystem.didParseJSON', function() {
                    audio.load(this.get('snippets').findBy('id', this.get('playingSnippetId')));
                });
            }
        }
    });
});
<|endoftext|>


<commit_before>module.exports = function (flags, argv) {
  if (!argv) {
    argv = process.argv;
  }
  var args = [argv[1]];
  argv.slice(2).forEach(function (arg) {
    var flag = arg.split('=')[0];
    if (flags.indexOf(flag) !== -1) {
      args.unshift(flag);
    } else {
      args.push(arg);
    }
  });
  args.unshift(argv[0]);
  return args;
};
<commit_msg>Fix: Ensure that flag values are preserved<commit_after>module.exports = function (flags, argv) {
  if (!argv) {
    argv = process.argv;
  }
  var args = [argv[1]];
  argv.slice(2).forEach(function (arg) {
    var flag = arg.split('=')[0];
    if (flags.indexOf(flag) !== -1) {
      args.unshift(arg);
    } else {
      args.push(arg);
    }
  });
  args.unshift(argv[0]);
  return args;
};
<|endoftext|>


<commit_before>/**
 * fastly-lib
 * Node.js client to interface with the API fastly
 * @author luisan00
 * @copyright (c) 2017 luisan00
 */

const https = require('https');
const querystring = require('querystring');

/**
 * request
 * @param  {String} api_key
 */
var request = function(api_key) {
    this.options = {};
    this.options.method = 'GET';
    this.options.hostname = 'api.fastly.com';
    this.options.path = '/';
    this.options.timeout = 6000;
    this.options.headers = {
        'Fastly-Key': api_key,
        'Accept': 'application/json'
    };
}

/**
 * send is the base method for all requests.
 * @return {Object}
 */
request.prototype.send = function() {
    var self = this;
    return new Promise(function(resolve, reject) {
        var data = '';
        const req = https.request(self.options, (res) => {
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                if (
                    res.headers['content-type'] === 'application/json;charset=utf-8' ||
                    res.headers['content-type'] === 'application/json'
                ) {
                    resolve(JSON.parse(data));
                } else {
                    resolve(data);
                }
            });
        });
        req.on('error', (err) => {
            reject(err);
        });
        if (self.body) {
            req.write(self.body, 'utf8', () => {
                req.end();
            });
        } else {
            req.end();
        }

    });
};

/**
 * request by GET method
 * @param  {String} path
 * @return {function}
 */
request.prototype.get = function(path) {
    this.options.method = 'GET';
    this.options.path = path;
    return this.send();
};

/**
 * request by POST method
 * @param  {[type]} path
 * @param  {Object} body
 * @return {function}
 */
request.prototype.post = function(path, body) {
    this.body = body || '';
    this.options.method = 'POST';
    this.options.path = path || '/';
    this.options.headers['Content-Type'] = 'application/json';
    this.options.headers['Content-Length'] = Buffer.byteLength(this.body);
    return this.send();
};

/**
 * request by PURGE method
 * @param  {String} path
 * @param  {Object} body
 * @return {function}
 */
request.prototype.purge = function(path, body) {
    this.body = body || '';
    this.options.method = 'PURGE';
    this.options.path = path || '/';
    this.options.headers['Content-Type'] = 'application/json';
    this.options.headers['Content-Length'] = Buffer.byteLength(this.body);
    //this.send();
    return this.send();
};

/**
 * request by DELETE method
 * @param  {String} path
 * @return {function}
 */
request.prototype.delete = function(path) {
  this.options.method = 'DELETE';
  this.options.path = path || '/';
  this.options.headers['Content-Type'] = 'application/json';
  return this.send();
};

module.exports = request;
<commit_msg>Update request.js<commit_after>/**
 * fastly-lib
 * Node.js client to interface with the API fastly
 * @author luisan00
 * @copyright (c) 2017-2019 luisan00
 */

const https = require('https');
const querystring = require('querystring');

/**
 * request
 * @param  {String} api_key
 */
var request = function(api_key) {
    this.options = {};
    this.options.method = 'GET';
    this.options.hostname = 'api.fastly.com';
    this.options.path = '/';
    this.options.timeout = 6000;
    this.options.headers = {
        'Fastly-Key': api_key,
        'Accept': 'application/json'
    };
}

/**
 * send is the base method for all requests.
 * @return {Object}
 */
request.prototype.send = function() {
    var self = this;
    return new Promise(function(resolve, reject) {
        var data = '';
        const req = https.request(self.options, (res) => {
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                if (
                    res.headers['content-type'] === 'application/json;charset=utf-8' ||
                    res.headers['content-type'] === 'application/json'
                ) {
                    resolve(JSON.parse(data));
                } else {
                    resolve(data);
                }
            });
        });
        req.on('error', (err) => {
            reject(err);
        });
        if (self.body) {
            req.write(self.body, 'utf8', () => {
                req.end();
            });
        } else {
            req.end();
        }

    });
};

/**
 * request by GET method
 * @param  {String} path
 * @return {function}
 */
request.prototype.get = function(path) {
    this.options.method = 'GET';
    this.options.path = path;
    return this.send();
};

/**
 * request by POST method
 * @param  {[type]} path
 * @param  {Object} body
 * @return {function}
 */
request.prototype.post = function(path, body) {
    this.body = body || '';
    this.options.method = 'POST';
    this.options.path = path || '/';
    this.options.headers['Content-Type'] = 'application/json';
    this.options.headers['Content-Length'] = Buffer.byteLength(this.body);
    return this.send();
};

/**
 * request by PURGE method
 * @param  {String} path
 * @param  {Object} body
 * @return {function}
 */
request.prototype.purge = function(path, body) {
    this.body = body || '';
    this.options.method = 'PURGE';
    this.options.path = path || '/';
    this.options.headers['Content-Type'] = 'application/json';
    this.options.headers['Content-Length'] = Buffer.byteLength(this.body);
    //this.send();
    return this.send();
};

/**
 * request by DELETE method
 * @param  {String} path
 * @return {function}
 */
request.prototype.delete = function(path) {
  this.options.method = 'DELETE';
  this.options.path = path || '/';
  this.options.headers['Content-Type'] = 'application/json';
  return this.send();
};

module.exports = request;
<|endoftext|>


<commit_before>/**
 * AdSense utility functions.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import each from 'lodash/each';

export * from './parsing';
export * from './status';
export * from './validation';
export * from './url';

export function reduceAdSenseData( rows ) {
	const dataMap = [
		[
			{ type: 'date', label: 'Day' },
			{ type: 'number', label: 'RPM' },
			{ type: 'number', label: 'Earnings' },
			{ type: 'number', label: 'Impressions' },
		],
	];

	each( rows, ( row ) => {
		const date = new Date( row[ 0 ] );
		dataMap.push( [
			date,
			row[ 2 ],
			row[ 1 ],
			row[ 3 ],
		] );
	} );

	return {
		dataMap,
	};
}

/**
 * Checks for any value higher than 0 in values from AdSense data.
 *
 * @since 1.0.0
 *
 * @param {Array}  adSenseData Data returned from the AdSense.
 * @param {string} datapoint   Datapoint requested.
 * @param {Object} dataRequest Request data object.
 * @return {boolean} Whether or not AdSense data is considered zero data.
 */
export const isDataZeroAdSense = ( adSenseData, datapoint, dataRequest ) => {
	// We only check the last 28 days of earnings because it is the most reliable data point to identify new setups:
	// only new accounts or accounts not showing ads would have zero earnings in the last 28 days.
	if ( ! dataRequest.data || ! dataRequest.data.dateRange || 'last-28-days' !== dataRequest.data.dateRange ) {
		return false;
	}

	let totals = [];
	if ( adSenseData.totals ) {
		totals = adSenseData.totals;
	}

	// Look for any value > 0.
	totals = totals.filter( ( total ) => {
		return 0 < total;
	} );
	return 0 === totals.length;
};
<commit_msg>Add placeholder to function.<commit_after>/**
 * AdSense utility functions.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import each from 'lodash/each';

export * from './parsing';
export * from './status';
export * from './validation';
export * from './url';

export function reduceAdSenseData( rows ) {
	const dataMap = [
		[
			{ type: 'date', label: 'Day' },
			{ type: 'number', label: 'RPM' },
			{ type: 'number', label: 'Earnings' },
			{ type: 'number', label: 'Impressions' },
		],
	];

	each( rows, ( row ) => {
		const date = new Date( row[ 0 ] );
		dataMap.push( [
			date,
			row[ 2 ],
			row[ 1 ],
			row[ 3 ],
		] );
	} );

	return {
		dataMap,
	};
}

/**
 * Checks for any value higher than 0 in values from AdSense data.
 *
 * @since 1.0.0
 *
 * @param {Array}  adSenseData Data returned from the AdSense.
 * @param {string} datapoint   Datapoint requested.
 * @param {Object} dataRequest Request data object.
 * @return {boolean} Whether or not AdSense data is considered zero data.
 */
export const isDataZeroAdSense = ( adSenseData, datapoint, dataRequest ) => {
	// We only check the last 28 days of earnings because it is the most reliable data point to identify new setups:
	// only new accounts or accounts not showing ads would have zero earnings in the last 28 days.

	// The 'prev-date-range-placeholder' is dynamically replaced with the previous date range based on the current date range so we need allow it here.
	if ( ! dataRequest.data || ! dataRequest.data.dateRange || ( 'last-28-days' !== dataRequest.data.dateRange && 'prev-date-range-placeholder' !== dataRequest.data.dateRange ) ) {
		return false;
	}

	let totals = [];
	if ( adSenseData.totals ) {
		totals = adSenseData.totals;
	}

	// Look for any value > 0.
	totals = totals.filter( ( total ) => {
		return 0 < total;
	} );
	return 0 === totals.length;
};
<|endoftext|>


<commit_before>"use strict";

let https = require("https");

module.exports = makeRequest;

/**
 * Make a request to an external service and return the results.
 *
 * @param {Object} options - the request options
 * @param {String} bodyData - the optional body data
 * @returns {Promise} - resolved with an Object with "data", "statusCode" and "headers" keys
 */
function makeRequest(options, bodyData) {
  return new Promise((resolve, reject) => {
    let req = https.request(options, res => {
      let content = "";

      res.setEncoding("utf8");

      res.on("data", chunk => {
        content += chunk;
      });

      res.on("end", () => {
        if (res.statusCode >= 400) {
          reject(new Error(`Invalid status code: ${res.statusCode}, path: ${options.path}, content: ${content}`));
          return;
        }

        try {
          let data = JSON.parse(content);
          resolve({
            data: data,
            statusCode: res.statusCode,
            headers: res.headers
          });
        } catch (err) {
          reject(new Error(`Data received has incorrect JSON format: ${err}`));
        }
      });
    });

    req.on("error", err => {
      reject(new Error(`Error during request: ${err}`));
    });

    if (bodyData) {
      req.write(bodyData);
    }

    req.end();
  });
}
<commit_msg>Reject the request promise only when an unexpected error occurred, not on invalid data.<commit_after>"use strict";

let https = require("https");

module.exports = makeRequest;

/**
 * Make a request to an external service and return the results.
 *
 * @param {Object} options - the request options
 * @param {String} bodyData - the optional body data
 * @returns {Promise} - resolved with an Object with "data", "statusCode" and "headers" keys
 */
function makeRequest(options, bodyData) {
  return new Promise((resolve, reject) => {
    let req = https.request(options, res => {
      let content = "";

      res.setEncoding("utf8");

      res.on("data", chunk => {
        content += chunk;
      });

      res.on("end", () => {
        try {
          let data = JSON.parse(content);
          resolve({
            data: data,
            statusCode: res.statusCode,
            headers: res.headers
          });
        } catch (err) {
          reject(new Error(`Data received has incorrect JSON format: ${err}`));
        }
      });
    });

    req.on("error", err => {
      reject(new Error(`Error during request: ${err}`));
    });

    if (bodyData) {
      req.write(bodyData);
    }

    req.end();
  });
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2018 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */

// version of docker images
const DOCKER_JHIPSTER_REGISTRY = 'jhipster/jhipster-registry:v4.0.6';
const DOCKER_JAVA_JRE = 'openjdk:8-jre-alpine';
const DOCKER_MYSQL = 'mysql:8.0.13';
const DOCKER_MARIADB = 'mariadb:10.3.7';
const DOCKER_POSTGRESQL = 'postgres:11.1';
const DOCKER_MONGODB = 'mongo:4.0.2';
const DOCKER_COUCHBASE = 'couchbase/server:5.5.1';
const DOCKER_CASSANDRA = 'cassandra:3.9';
const DOCKER_MSSQL = 'microsoft/mssql-server-linux:latest';
const DOCKER_ORACLE = 'sath89/oracle-12c:latest';
const DOCKER_HAZELCAST_MANAGEMENT_CENTER = 'hazelcast/management-center:3.11';
const DOCKER_MEMCACHED = 'memcached:1.5.8-alpine';
const DOCKER_KEYCLOAK = 'jboss/keycloak:4.5.0.Final';
const DOCKER_ELASTICSEARCH = 'elasticsearch:6.4.2'; // docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.1
const DOCKER_KAFKA = 'wurstmeister/kafka:2.11-2.0.0';
const DOCKER_ZOOKEEPER = 'wurstmeister/zookeeper:3.4.6';
const DOCKER_SONAR = 'sonarqube:7.1';
const DOCKER_JHIPSTER_CONSOLE = 'jhipster/jhipster-console:v4.0.0';
const DOCKER_JHIPSTER_CURATOR = 'jhipster/jhipster-curator:v4.0.0';
const DOCKER_JHIPSTER_ELASTICSEARCH = 'jhipster/jhipster-elasticsearch:v4.0.0';
const DOCKER_JHIPSTER_LOGSTASH = 'jhipster/jhipster-logstash:v4.0.0';
const DOCKER_JHIPSTER_IMPORT_DASHBOARDS = 'jhipster/jhipster-import-dashboards:v4.0.0';
const DOCKER_JHIPSTER_ZIPKIN = 'jhipster/jhipster-zipkin:v4.0.0';
const DOCKER_TRAEFIK = 'traefik:1.7.4';
const DOCKER_CONSUL = 'consul:1.3.0';
const DOCKER_CONSUL_CONFIG_LOADER = 'jhipster/consul-config-loader:v0.3.0';
const DOCKER_PROMETHEUS = 'prom/prometheus:v2.4.3';
const DOCKER_PROMETHEUS_ALERTMANAGER = 'prom/alertmanager:v0.15.2';
const DOCKER_GRAFANA = 'grafana/grafana:5.3.0';
const DOCKER_JENKINS = 'jenkins:latest';
const DOCKER_SWAGGER_EDITOR = 'swaggerapi/swagger-editor:latest';
const DOCKER_COMPOSE_FORMAT_VERSION = '2';
const DOCKER_PROMETHEUS_OPERATOR = 'quay.io/coreos/prometheus-operator:v0.16.1';
const DOCKER_GRAFANA_WATCHER = 'quay.io/coreos/grafana-watcher:v0.0.8';

// Version of Java, Scala
const JAVA_VERSION = '1.8'; // Java version is forced to be 1.8. We keep the variable as it might be useful in the future.
const SCALA_VERSION = '2.12.6';

// version of Node, Yarn, NPM
const NODE_VERSION = '10.13.0';
const YARN_VERSION = '1.12.1';
const NPM_VERSION = '6.4.1';

// all constants used throughout all generators

const MAIN_DIR = 'src/main/';
const TEST_DIR = 'src/test/';

// Note: this will be prepended with 'target/' for Maven, or with 'build/' for Gradle.
const CLIENT_DIST_DIR = 'www/';

const SUPPORTED_VALIDATION_RULES = ['required', 'unique', 'max', 'min', 'maxlength', 'minlength', 'maxbytes', 'minbytes', 'pattern'];

// documentation constants
const JHIPSTER_DOCUMENTATION_URL = 'https://www.jhipster.tech';
const JHIPSTER_DOCUMENTATION_ARCHIVE_PATH = '/documentation-archive/';

const SQL_DB_OPTIONS = [
    {
        value: 'mysql',
        name: 'MySQL'
    },
    {
        value: 'mariadb',
        name: 'MariaDB'
    },
    {
        value: 'postgresql',
        name: 'PostgreSQL'
    },
    {
        value: 'oracle',
        name: 'Oracle (Please follow our documentation to use the Oracle proprietary driver)'
    },
    {
        value: 'mssql',
        name: 'Microsoft SQL Server'
    }
];

const LANGUAGES = [
    {
        name: 'Albanian',
        dispName: 'Shqip',
        value: 'al',
        momentLocaleId: 'sq'
    },
    {
        name: 'Arabic (Libya)',
        dispName: 'العربية',
        value: 'ar-ly',
        rtl: true,
        skipForLocale: true
    },
    {
        name: 'Armenian',
        dispName: 'Հայերեն',
        value: 'hy',
        momentLocaleId: 'hy-am'
    },
    {
        name: 'Belorussian',
        dispName: 'Беларускі',
        value: 'by',
        momentLocaleId: 'be-by'
    },
    {
        name: 'Bengali',
        dispName: 'বাংলা',
        value: 'bn',
        momentLocaleId: 'bn-bd'
    },
    {
        name: 'Catalan',
        dispName: 'Català',
        value: 'ca'
    },
    {
        name: 'Chinese (Simplified)',
        dispName: '中文（简体）',
        value: 'zh-cn',
        localeId: 'zh-Hans'
    },
    {
        name: 'Chinese (Traditional)',
        dispName: '繁體中文',
        value: 'zh-tw',
        localeId: 'zh-Hant'
    },
    { name: 'Czech', dispName: 'Český', value: 'cs' },
    { name: 'Danish', dispName: 'Dansk', value: 'da' },
    { name: 'Dutch', dispName: 'Nederlands', value: 'nl' },
    { name: 'English', dispName: 'English', value: 'en' },
    { name: 'Estonian', dispName: 'Eesti', value: 'et' },
    {
        name: 'Farsi',
        dispName: 'فارسی',
        value: 'fa',
        rtl: true
    },
    { name: 'French', dispName: 'Français', value: 'fr' },
    { name: 'Galician', dispName: 'Galego', value: 'gl' },
    { name: 'German', dispName: 'Deutsch', value: 'de' },
    { name: 'Greek', dispName: 'Ελληνικά', value: 'el' },
    { name: 'Hindi', dispName: 'हिंदी', value: 'hi' },
    { name: 'Hungarian', dispName: 'Magyar', value: 'hu' },
    { name: 'Indonesian', dispName: 'Bahasa Indonesia', value: 'id' },
    { name: 'Italian', dispName: 'Italiano', value: 'it' },
    { name: 'Japanese', dispName: '日本語', value: 'ja' },
    { name: 'Korean', dispName: '한국어', value: 'ko' },
    { name: 'Marathi', dispName: 'मराठी', value: 'mr' },
    { name: 'Myanmar', dispName: 'မြန်မာ', value: 'my' },
    { name: 'Polish', dispName: 'Polski', value: 'pl' },
    {
        name: 'Portuguese (Brazilian)',
        dispName: 'Português (Brasil)',
        value: 'pt-br',
        localeId: 'pt'
    },
    {
        name: 'Portuguese',
        dispName: 'Português',
        value: 'pt-pt',
        localeId: 'pt-PT'
    },
    { name: 'Romanian', dispName: 'Română', value: 'ro' },
    { name: 'Russian', dispName: 'Русский', value: 'ru' },
    { name: 'Slovak', dispName: 'Slovenský', value: 'sk' },
    { name: 'Serbian', dispName: 'Srpski', value: 'sr' },
    { name: 'Spanish', dispName: 'Español', value: 'es' },
    { name: 'Swedish', dispName: 'Svenska', value: 'sv' },
    { name: 'Turkish', dispName: 'Türkçe', value: 'tr' },
    { name: 'Tamil', dispName: 'தமிழ்', value: 'ta' },
    { name: 'Thai', dispName: 'ไทย', value: 'th' },
    {
        name: 'Ukrainian',
        dispName: 'Українська',
        value: 'ua',
        localeId: 'uk',
        momentLocaleId: 'uk'
    },
    {
        name: 'Uzbek (latin)',
        dispName: 'O`zbekcha',
        value: 'uz-lat',
        localeId: 'uz'
    },
    { name: 'Vietnamese', dispName: 'Tiếng Việt', value: 'vi' }
];

const constants = {
    INTERPOLATE_REGEX: /<%:([\s\S]+?)%>/g, // so that tags in templates do not get mistreated as _ templates
    DOCKER_DIR: `${MAIN_DIR}docker/`,
    LINE_LENGTH: 180,
    LANGUAGES,

    MAIN_DIR,
    TEST_DIR,

    CLIENT_MAIN_SRC_DIR: `${MAIN_DIR}webapp/`,
    CLIENT_TEST_SRC_DIR: `${TEST_DIR}javascript/`,
    CLIENT_WEBPACK_DIR: 'webpack/',
    CLIENT_DIST_DIR,
    ANGULAR_DIR: `${MAIN_DIR}webapp/app/`,
    REACT_DIR: `${MAIN_DIR}webapp/app/`,

    SERVER_MAIN_SRC_DIR: `${MAIN_DIR}java/`,
    SERVER_MAIN_RES_DIR: `${MAIN_DIR}resources/`,
    SERVER_TEST_SRC_DIR: `${TEST_DIR}java/`,
    SERVER_TEST_RES_DIR: `${TEST_DIR}resources/`,

    // entity related
    SUPPORTED_VALIDATION_RULES,

    JHIPSTER_DOCUMENTATION_URL,
    JHIPSTER_DOCUMENTATION_ARCHIVE_PATH,

    DOCKER_JHIPSTER_REGISTRY,
    DOCKER_JAVA_JRE,
    DOCKER_MYSQL,
    DOCKER_MARIADB,
    DOCKER_POSTGRESQL,
    DOCKER_MONGODB,
    DOCKER_COUCHBASE,
    DOCKER_CASSANDRA,
    DOCKER_MSSQL,
    DOCKER_ORACLE,
    DOCKER_HAZELCAST_MANAGEMENT_CENTER,
    DOCKER_MEMCACHED,
    DOCKER_ELASTICSEARCH,
    DOCKER_KEYCLOAK,
    DOCKER_KAFKA,
    DOCKER_ZOOKEEPER,
    DOCKER_SONAR,
    DOCKER_JHIPSTER_CONSOLE,
    DOCKER_JHIPSTER_CURATOR,
    DOCKER_JHIPSTER_ELASTICSEARCH,
    DOCKER_JHIPSTER_LOGSTASH,
    DOCKER_JHIPSTER_IMPORT_DASHBOARDS,
    DOCKER_JHIPSTER_ZIPKIN,
    DOCKER_TRAEFIK,
    DOCKER_CONSUL,
    DOCKER_CONSUL_CONFIG_LOADER,
    DOCKER_PROMETHEUS,
    DOCKER_PROMETHEUS_ALERTMANAGER,
    DOCKER_GRAFANA,
    JAVA_VERSION,
    SCALA_VERSION,
    NODE_VERSION,
    YARN_VERSION,
    NPM_VERSION,
    DOCKER_JENKINS,
    DOCKER_SWAGGER_EDITOR,
    SQL_DB_OPTIONS,
    DOCKER_COMPOSE_FORMAT_VERSION,
    DOCKER_PROMETHEUS_OPERATOR,
    DOCKER_GRAFANA_WATCHER
};

module.exports = constants;
<commit_msg>Upgrade mongo version to 4.0.4<commit_after>/**
 * Copyright 2013-2018 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */

// version of docker images
const DOCKER_JHIPSTER_REGISTRY = 'jhipster/jhipster-registry:v4.0.6';
const DOCKER_JAVA_JRE = 'openjdk:8-jre-alpine';
const DOCKER_MYSQL = 'mysql:8.0.13';
const DOCKER_MARIADB = 'mariadb:10.3.7';
const DOCKER_POSTGRESQL = 'postgres:11.1';
const DOCKER_MONGODB = 'mongo:4.0.4';
const DOCKER_COUCHBASE = 'couchbase/server:5.5.1';
const DOCKER_CASSANDRA = 'cassandra:3.9';
const DOCKER_MSSQL = 'microsoft/mssql-server-linux:latest';
const DOCKER_ORACLE = 'sath89/oracle-12c:latest';
const DOCKER_HAZELCAST_MANAGEMENT_CENTER = 'hazelcast/management-center:3.11';
const DOCKER_MEMCACHED = 'memcached:1.5.8-alpine';
const DOCKER_KEYCLOAK = 'jboss/keycloak:4.5.0.Final';
const DOCKER_ELASTICSEARCH = 'elasticsearch:6.4.2'; // docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.1
const DOCKER_KAFKA = 'wurstmeister/kafka:2.11-2.0.0';
const DOCKER_ZOOKEEPER = 'wurstmeister/zookeeper:3.4.6';
const DOCKER_SONAR = 'sonarqube:7.1';
const DOCKER_JHIPSTER_CONSOLE = 'jhipster/jhipster-console:v4.0.0';
const DOCKER_JHIPSTER_CURATOR = 'jhipster/jhipster-curator:v4.0.0';
const DOCKER_JHIPSTER_ELASTICSEARCH = 'jhipster/jhipster-elasticsearch:v4.0.0';
const DOCKER_JHIPSTER_LOGSTASH = 'jhipster/jhipster-logstash:v4.0.0';
const DOCKER_JHIPSTER_IMPORT_DASHBOARDS = 'jhipster/jhipster-import-dashboards:v4.0.0';
const DOCKER_JHIPSTER_ZIPKIN = 'jhipster/jhipster-zipkin:v4.0.0';
const DOCKER_TRAEFIK = 'traefik:1.7.4';
const DOCKER_CONSUL = 'consul:1.3.0';
const DOCKER_CONSUL_CONFIG_LOADER = 'jhipster/consul-config-loader:v0.3.0';
const DOCKER_PROMETHEUS = 'prom/prometheus:v2.4.3';
const DOCKER_PROMETHEUS_ALERTMANAGER = 'prom/alertmanager:v0.15.2';
const DOCKER_GRAFANA = 'grafana/grafana:5.3.0';
const DOCKER_JENKINS = 'jenkins:latest';
const DOCKER_SWAGGER_EDITOR = 'swaggerapi/swagger-editor:latest';
const DOCKER_COMPOSE_FORMAT_VERSION = '2';
const DOCKER_PROMETHEUS_OPERATOR = 'quay.io/coreos/prometheus-operator:v0.16.1';
const DOCKER_GRAFANA_WATCHER = 'quay.io/coreos/grafana-watcher:v0.0.8';

// Version of Java, Scala
const JAVA_VERSION = '1.8'; // Java version is forced to be 1.8. We keep the variable as it might be useful in the future.
const SCALA_VERSION = '2.12.6';

// version of Node, Yarn, NPM
const NODE_VERSION = '10.13.0';
const YARN_VERSION = '1.12.1';
const NPM_VERSION = '6.4.1';

// all constants used throughout all generators

const MAIN_DIR = 'src/main/';
const TEST_DIR = 'src/test/';

// Note: this will be prepended with 'target/' for Maven, or with 'build/' for Gradle.
const CLIENT_DIST_DIR = 'www/';

const SUPPORTED_VALIDATION_RULES = ['required', 'unique', 'max', 'min', 'maxlength', 'minlength', 'maxbytes', 'minbytes', 'pattern'];

// documentation constants
const JHIPSTER_DOCUMENTATION_URL = 'https://www.jhipster.tech';
const JHIPSTER_DOCUMENTATION_ARCHIVE_PATH = '/documentation-archive/';

const SQL_DB_OPTIONS = [
    {
        value: 'mysql',
        name: 'MySQL'
    },
    {
        value: 'mariadb',
        name: 'MariaDB'
    },
    {
        value: 'postgresql',
        name: 'PostgreSQL'
    },
    {
        value: 'oracle',
        name: 'Oracle (Please follow our documentation to use the Oracle proprietary driver)'
    },
    {
        value: 'mssql',
        name: 'Microsoft SQL Server'
    }
];

const LANGUAGES = [
    {
        name: 'Albanian',
        dispName: 'Shqip',
        value: 'al',
        momentLocaleId: 'sq'
    },
    {
        name: 'Arabic (Libya)',
        dispName: 'العربية',
        value: 'ar-ly',
        rtl: true,
        skipForLocale: true
    },
    {
        name: 'Armenian',
        dispName: 'Հայերեն',
        value: 'hy',
        momentLocaleId: 'hy-am'
    },
    {
        name: 'Belorussian',
        dispName: 'Беларускі',
        value: 'by',
        momentLocaleId: 'be-by'
    },
    {
        name: 'Bengali',
        dispName: 'বাংলা',
        value: 'bn',
        momentLocaleId: 'bn-bd'
    },
    {
        name: 'Catalan',
        dispName: 'Català',
        value: 'ca'
    },
    {
        name: 'Chinese (Simplified)',
        dispName: '中文（简体）',
        value: 'zh-cn',
        localeId: 'zh-Hans'
    },
    {
        name: 'Chinese (Traditional)',
        dispName: '繁體中文',
        value: 'zh-tw',
        localeId: 'zh-Hant'
    },
    { name: 'Czech', dispName: 'Český', value: 'cs' },
    { name: 'Danish', dispName: 'Dansk', value: 'da' },
    { name: 'Dutch', dispName: 'Nederlands', value: 'nl' },
    { name: 'English', dispName: 'English', value: 'en' },
    { name: 'Estonian', dispName: 'Eesti', value: 'et' },
    {
        name: 'Farsi',
        dispName: 'فارسی',
        value: 'fa',
        rtl: true
    },
    { name: 'French', dispName: 'Français', value: 'fr' },
    { name: 'Galician', dispName: 'Galego', value: 'gl' },
    { name: 'German', dispName: 'Deutsch', value: 'de' },
    { name: 'Greek', dispName: 'Ελληνικά', value: 'el' },
    { name: 'Hindi', dispName: 'हिंदी', value: 'hi' },
    { name: 'Hungarian', dispName: 'Magyar', value: 'hu' },
    { name: 'Indonesian', dispName: 'Bahasa Indonesia', value: 'id' },
    { name: 'Italian', dispName: 'Italiano', value: 'it' },
    { name: 'Japanese', dispName: '日本語', value: 'ja' },
    { name: 'Korean', dispName: '한국어', value: 'ko' },
    { name: 'Marathi', dispName: 'मराठी', value: 'mr' },
    { name: 'Myanmar', dispName: 'မြန်မာ', value: 'my' },
    { name: 'Polish', dispName: 'Polski', value: 'pl' },
    {
        name: 'Portuguese (Brazilian)',
        dispName: 'Português (Brasil)',
        value: 'pt-br',
        localeId: 'pt'
    },
    {
        name: 'Portuguese',
        dispName: 'Português',
        value: 'pt-pt',
        localeId: 'pt-PT'
    },
    { name: 'Romanian', dispName: 'Română', value: 'ro' },
    { name: 'Russian', dispName: 'Русский', value: 'ru' },
    { name: 'Slovak', dispName: 'Slovenský', value: 'sk' },
    { name: 'Serbian', dispName: 'Srpski', value: 'sr' },
    { name: 'Spanish', dispName: 'Español', value: 'es' },
    { name: 'Swedish', dispName: 'Svenska', value: 'sv' },
    { name: 'Turkish', dispName: 'Türkçe', value: 'tr' },
    { name: 'Tamil', dispName: 'தமிழ்', value: 'ta' },
    { name: 'Thai', dispName: 'ไทย', value: 'th' },
    {
        name: 'Ukrainian',
        dispName: 'Українська',
        value: 'ua',
        localeId: 'uk',
        momentLocaleId: 'uk'
    },
    {
        name: 'Uzbek (latin)',
        dispName: 'O`zbekcha',
        value: 'uz-lat',
        localeId: 'uz'
    },
    { name: 'Vietnamese', dispName: 'Tiếng Việt', value: 'vi' }
];

const constants = {
    INTERPOLATE_REGEX: /<%:([\s\S]+?)%>/g, // so that tags in templates do not get mistreated as _ templates
    DOCKER_DIR: `${MAIN_DIR}docker/`,
    LINE_LENGTH: 180,
    LANGUAGES,

    MAIN_DIR,
    TEST_DIR,

    CLIENT_MAIN_SRC_DIR: `${MAIN_DIR}webapp/`,
    CLIENT_TEST_SRC_DIR: `${TEST_DIR}javascript/`,
    CLIENT_WEBPACK_DIR: 'webpack/',
    CLIENT_DIST_DIR,
    ANGULAR_DIR: `${MAIN_DIR}webapp/app/`,
    REACT_DIR: `${MAIN_DIR}webapp/app/`,

    SERVER_MAIN_SRC_DIR: `${MAIN_DIR}java/`,
    SERVER_MAIN_RES_DIR: `${MAIN_DIR}resources/`,
    SERVER_TEST_SRC_DIR: `${TEST_DIR}java/`,
    SERVER_TEST_RES_DIR: `${TEST_DIR}resources/`,

    // entity related
    SUPPORTED_VALIDATION_RULES,

    JHIPSTER_DOCUMENTATION_URL,
    JHIPSTER_DOCUMENTATION_ARCHIVE_PATH,

    DOCKER_JHIPSTER_REGISTRY,
    DOCKER_JAVA_JRE,
    DOCKER_MYSQL,
    DOCKER_MARIADB,
    DOCKER_POSTGRESQL,
    DOCKER_MONGODB,
    DOCKER_COUCHBASE,
    DOCKER_CASSANDRA,
    DOCKER_MSSQL,
    DOCKER_ORACLE,
    DOCKER_HAZELCAST_MANAGEMENT_CENTER,
    DOCKER_MEMCACHED,
    DOCKER_ELASTICSEARCH,
    DOCKER_KEYCLOAK,
    DOCKER_KAFKA,
    DOCKER_ZOOKEEPER,
    DOCKER_SONAR,
    DOCKER_JHIPSTER_CONSOLE,
    DOCKER_JHIPSTER_CURATOR,
    DOCKER_JHIPSTER_ELASTICSEARCH,
    DOCKER_JHIPSTER_LOGSTASH,
    DOCKER_JHIPSTER_IMPORT_DASHBOARDS,
    DOCKER_JHIPSTER_ZIPKIN,
    DOCKER_TRAEFIK,
    DOCKER_CONSUL,
    DOCKER_CONSUL_CONFIG_LOADER,
    DOCKER_PROMETHEUS,
    DOCKER_PROMETHEUS_ALERTMANAGER,
    DOCKER_GRAFANA,
    JAVA_VERSION,
    SCALA_VERSION,
    NODE_VERSION,
    YARN_VERSION,
    NPM_VERSION,
    DOCKER_JENKINS,
    DOCKER_SWAGGER_EDITOR,
    SQL_DB_OPTIONS,
    DOCKER_COMPOSE_FORMAT_VERSION,
    DOCKER_PROMETHEUS_OPERATOR,
    DOCKER_GRAFANA_WATCHER
};

module.exports = constants;
<|endoftext|>


<commit_before>/**
 * @fileoverview Generating sumorobot code for logic blocks.
 * @author info@robokoding.com (RoboKoding)
 */

'use strict';

goog.provide('Blockly.Sumorobot.sumorobot');

goog.require('Blockly.Generator');

Blockly.Sumorobot['controls_if'] = function(block) {
  // If/elseif/else condition.
  var n = 0;
  var argument = Blockly.Sumorobot.valueToCode(block, 'IF' + n,
      Blockly.Sumorobot.ORDER_NONE) || 'false';
  var branch = Blockly.Sumorobot.statementToCode(block, 'DO' + n);
  var code = 'if (' + argument + ') {\n' + branch + '}';
  for (n = 1; n <= block.elseifCount_; n++) {
    argument = Blockly.Sumorobot.valueToCode(block, 'IF' + n,
        Blockly.Sumorobot.ORDER_NONE) || 'false';
    branch = Blockly.Sumorobot.statementToCode(block, 'DO' + n);
    code += ' else if (' + argument + ') {\n' + branch + '}';
  }
  if (block.elseCount_) {
    branch = Blockly.Sumorobot.statementToCode(block, 'ELSE');
    code += ' else {\n' + branch + '}';
  }
  return code + '\n';
};

Blockly.Sumorobot['sumorobot_delay'] = function(block) {
  var code = "delay(" + parseFloat(block.getFieldValue('DELAY')) + ");\n";
  return code;
};

Blockly.Sumorobot['sumorobot_move'] = function(block) {
  var code = block.getFieldValue('MOVE') + "();\n";
  return code;
};

Blockly.Sumorobot['sumorobot_enemy'] = function(block) {
  var code = block.getFieldValue('ENEMY');
  return [code, Blockly.Sumorobot.ORDER_ATOMIC];
};

Blockly.Sumorobot['sumorobot_line'] = function(block) {
  var code = block.getFieldValue('LINE');
  return [code, Blockly.Sumorobot.ORDER_ATOMIC];
};
<commit_msg>Update sumorobot.js<commit_after>/**
 * @fileoverview Generating sumorobot code for logic blocks.
 * @author info@robokoding.com (RoboKoding)
 */

'use strict';

goog.provide('Blockly.Sumorobot.sumorobot');

goog.require('Blockly.Generator');

Blockly.Sumorobot['controls_if'] = function(block) {
  // If/elseif/else condition.
  var n = 0;
  var argument = Blockly.Sumorobot.valueToCode(block, 'IF' + n,
      Blockly.Sumorobot.ORDER_NONE) || 'false';
  var branch = Blockly.Sumorobot.statementToCode(block, 'DO' + n);
  var code = 'if (' + argument + ') {\n' + branch + '}';
  for (n = 1; n <= block.elseifCount_; n++) {
    argument = Blockly.Sumorobot.valueToCode(block, 'IF' + n,
        Blockly.Sumorobot.ORDER_NONE) || 'false';
    branch = Blockly.Sumorobot.statementToCode(block, 'DO' + n);
    code += ' else if (' + argument + ') {\n' + branch + '}';
  }
  if (block.elseCount_) {
    branch = Blockly.Sumorobot.statementToCode(block, 'ELSE');
    code += ' else {\n' + branch + '}';
  }
  return code + '\n';
};

Blockly.Sumorobot['sumorobot_delay'] = function(block) {
  var code = 'sumorobot.delay(' + parseFloat(block.getFieldValue('DELAY')) + ');\n';
  return code;
};

Blockly.Sumorobot['sumorobot_move'] = function(block) {
  var code = 'sumorobot.move(' + block.getFieldValue('MOVE') + ');\n';
  return code;
};

Blockly.Sumorobot['sumorobot_enemy'] = function(block) {
  var code = 'sumorobot.isEnemy()';
  return [code, Blockly.Sumorobot.ORDER_ATOMIC];
};

Blockly.Sumorobot['sumorobot_line'] = function(block) {
  var code = 'sumorobot.isLine(' + block.getFieldValue('LINE') + ')';
  return [code, Blockly.Sumorobot.ORDER_ATOMIC];
};
<|endoftext|>


<commit_before>/**
 * modul8 v__VERSION__
 */

var config    = __REQUIRECONFIG__
  , ns        = window[config.namespace]
  , domains   = config.domains
  , arbiters  = []
  , exports   = {}
  , DomReg    = /^([\w]*)::/;

/**
 * Initialize the exports container with domain names + move data to it
 */
exports.M8 = {};
exports.external = {};
exports.data = ns.data;
delete ns.data;

domains.forEach(function(e){
  exports[e] = {};
});

/**
 * Attach arbiters to the require system then delete them from the global scope
 */
Object.keys(config.arbiters).forEach(function(name){
  var arbAry = config.arbiters[name];
  arbiters.push(name);
  exports.M8[name] = window[arbAry[0]];
  arbAry.forEach(function(e){
    delete window[e];
  });
});

/**
 * Converts a relative path to an absolute one
 */
function toAbsPath(pathName, relReqStr) {
  var folders = pathName.split('/').slice(0, -1);
  while (relReqStr.slice(0, 3) === '../') {
    folders = folders.slice(0, -1);
    relReqStr = relReqStr.slice(3);
  }
  return folders.concat(relReqStr.split('/')).join('/');
}

/**
 * Require Factory for ns.define
 * Each (domain,path) gets a specialized require function from this
 */
function makeRequire(dom, pathName) {
  return function(reqStr) {
    var o, scannable, k, skipFolder;

    if (config.logging >= 4) {
      console.debug('modul8: '+dom+':'+pathName+" <- "+reqStr);
    }

    if (reqStr.slice(0, 2) === './') {
      scannable = [dom];
      reqStr = toAbsPath(pathName, reqStr.slice(2));
    }
    else if (reqStr.slice(0,3) === '../') {
      scannable = [dom];
      reqStr = toAbsPath(pathName, reqStr);
    }
    else if (DomReg.test(reqStr)) {
      scannable = [reqStr.match(DomReg)[1]];
      reqStr = reqStr.split('::')[1];
    }
    else if (arbiters.indexOf(reqStr) >= 0) {
      scannable = ['M8'];
    }
    else {
      scannable = [dom].concat(domains.filter(function(e) {return e !== dom;}));
    }

    reqStr = reqStr.split('.')[0];
    if (reqStr.slice(-1) === '/' || reqStr === '') {
      reqStr += 'index';
      skipFolder = true;
    }

    if (config.logging >= 3) {
      console.log('modul8: '+dom+':'+pathName+' <- '+reqStr);
    }
    if (config.logging >= 4) {
      console.debug('modul8: scanned '+JSON.stringify(scannable));
    }

    for (k = 0; k < scannable.length; k += 1) {
      o = scannable[k];
      if (exports[o][reqStr]) {
        return exports[o][reqStr];
      }
      if (!skipFolder && exports[o][reqStr + '/index']) {
        return exports[o][reqStr + '/index'];
      }
    }

    if (config.logging >= 1) {
      console.error("modul8: Unable to resolve require for: " + reqStr);
    }
  };
}

ns.define = function(name, domain, fn) {
  var module = {};
  fn(makeRequire(domain, name), module, exports[domain][name] = {});
  if (module.exports) {
    delete exports[domain][name];
    exports[domain][name] = module.exports;
  }
};

/**
 * Public Debug API
 */

ns.inspect = function(domain) {
  console.log(exports[domain]);
};

ns.domains = function() {
  return domains.concat(['external','data']);
};

ns.require = makeRequire('app', 'CONSOLE');

/**
 * Live Extension API
 */

ns.data = function(name, exported) {
  if (exports.data[name]) {
    delete exports.data[name];
  }
  if (exported) {
    exports.data[name] = exported;
  }
};

ns.external = function(name, exported) {
  if (exports.external[name]) {
    delete exports.external[name];
  }
  if (exported) {
    exports.external[name] = exported;
  }
};
<commit_msg>tweaking require.js to fix a less common CommonJS guard failing (fixes issue 7)<commit_after>/**
 * modul8 v__VERSION__
 */

var config    = __REQUIRECONFIG__
  , ns        = window[config.namespace]
  , domains   = config.domains
  , arbiters  = []
  , exports   = {}
  , DomReg    = /^([\w]*)::/;

/**
 * Initialize the exports container with domain names + move data to it
 */
exports.M8 = {};
exports.external = {};
exports.data = ns.data;
delete ns.data;

domains.forEach(function(e){
  exports[e] = {};
});

/**
 * Attach arbiters to the require system then delete them from the global scope
 */
Object.keys(config.arbiters).forEach(function(name){
  var arbAry = config.arbiters[name];
  arbiters.push(name);
  exports.M8[name] = window[arbAry[0]];
  arbAry.forEach(function(e){
    delete window[e];
  });
});

/**
 * Converts a relative path to an absolute one
 */
function toAbsPath(pathName, relReqStr) {
  var folders = pathName.split('/').slice(0, -1);
  while (relReqStr.slice(0, 3) === '../') {
    folders = folders.slice(0, -1);
    relReqStr = relReqStr.slice(3);
  }
  return folders.concat(relReqStr.split('/')).join('/');
}

/**
 * Require Factory for ns.define
 * Each (domain,path) gets a specialized require function from this
 */
function makeRequire(dom, pathName) {
  return function(reqStr) {
    var o, scannable, k, skipFolder;

    if (config.logging >= 4) {
      console.debug('modul8: '+dom+':'+pathName+" <- "+reqStr);
    }

    if (reqStr.slice(0, 2) === './') {
      scannable = [dom];
      reqStr = toAbsPath(pathName, reqStr.slice(2));
    }
    else if (reqStr.slice(0,3) === '../') {
      scannable = [dom];
      reqStr = toAbsPath(pathName, reqStr);
    }
    else if (DomReg.test(reqStr)) {
      scannable = [reqStr.match(DomReg)[1]];
      reqStr = reqStr.split('::')[1];
    }
    else if (arbiters.indexOf(reqStr) >= 0) {
      scannable = ['M8'];
    }
    else {
      scannable = [dom].concat(domains.filter(function(e) {return e !== dom;}));
    }

    reqStr = reqStr.split('.')[0];
    if (reqStr.slice(-1) === '/' || reqStr === '') {
      reqStr += 'index';
      skipFolder = true;
    }

    if (config.logging >= 3) {
      console.log('modul8: '+dom+':'+pathName+' <- '+reqStr);
    }
    if (config.logging >= 4) {
      console.debug('modul8: scanned '+JSON.stringify(scannable));
    }

    for (k = 0; k < scannable.length; k += 1) {
      o = scannable[k];
      if (exports[o][reqStr]) {
        return exports[o][reqStr];
      }
      if (!skipFolder && exports[o][reqStr + '/index']) {
        return exports[o][reqStr + '/index'];
      }
    }

    if (config.logging >= 1) {
      console.error("modul8: Unable to resolve require for: " + reqStr);
    }
  };
}

ns.define = function(name, domain, fn) {
  var mod = {exports:{}}
    , exp = {}
    , target;
  fn.call({}, makeRequire(domain, name), mod, exp);

  if (Object.prototype.toString.call(mod.exports) === '[object Object]') {
    target = (Object.keys(mod.exports).length) ? mod.exports : exp;
  }
  else {
    target = mod.exports;
  }
  exports[domain][name] = target;
};

/**
 * Public Debug API
 */

ns.inspect = function(domain) {
  console.log(exports[domain]);
};

ns.domains = function() {
  return domains.concat(['external','data']);
};

ns.require = makeRequire('app', 'CONSOLE');

/**
 * Live Extension API
 */

ns.data = function(name, exported) {
  if (exports.data[name]) {
    delete exports.data[name];
  }
  if (exported) {
    exports.data[name] = exported;
  }
};

ns.external = function(name, exported) {
  if (exports.external[name]) {
    delete exports.external[name];
  }
  if (exported) {
    exports.external[name] = exported;
  }
};
<|endoftext|>


<commit_before>import Morph from 'morphmorph'

let createHistory
let history
if (typeof window !== 'undefined') {
  createHistory = require('history').createBrowserHistory
  history = createHistory()
}

const mapper = new Morph({
  types: {
    bool: v => {
      if (v === 'false') return false
      return Boolean(v)
    }
  }
})

const mappings = [
  { field: 'bg:backgroundColor' },
  { field: 't:theme' },
  { field: 'l:language' },
  { field: 'ds:dropShadow', type: 'bool' },
  { field: 'wc:windowControls', type: 'bool' },
  { field: 'wa:widthAdjustment', type: 'bool' },
  { field: 'pv:paddingVertical' },
  { field: 'ph:paddingHorizontal' },
  { field: 'ln:lineNumbers', type: 'bool' },
  { field: 'code:code' }
]

const reverseMappings = mappings.map(mapping =>
  Object.assign({}, mapping, {
    field: mapping.field
      .split(':')
      .reverse()
      .join(':')
  })
)

const keysToQuery = keys =>
  `?${Object.keys(keys)
    .map(key => `${key}=${keys[key]}`)
    .join('&')}`

export const getQueryStringState = query => mapper.map(mappings, query)
export const updateQueryString = state =>
  history.replace({
    search: encodeURI(keysToQuery(mapper.map(reverseMappings, state)))
  })
<commit_msg>Fix localStorage<commit_after>import Morph from 'morphmorph'

let createHistory
let history
if (typeof window !== 'undefined') {
  createHistory = require('history').createBrowserHistory
  history = createHistory()
}

const mapper = new Morph({
  types: {
    bool: v => {
      if (v == null) return undefined
      if (v === 'false') return false
      return Boolean(v)
    }
  }
})

const mappings = [
  { field: 'bg:backgroundColor' },
  { field: 't:theme' },
  { field: 'l:language' },
  { field: 'ds:dropShadow', type: 'bool' },
  { field: 'wc:windowControls', type: 'bool' },
  { field: 'wa:widthAdjustment', type: 'bool' },
  { field: 'pv:paddingVertical' },
  { field: 'ph:paddingHorizontal' },
  { field: 'ln:lineNumbers', type: 'bool' },
  { field: 'code:code' }
]

const reverseMappings = mappings.map(mapping =>
  Object.assign({}, mapping, {
    field: mapping.field
      .split(':')
      .reverse()
      .join(':')
  })
)

const keysToQuery = keys =>
  `?${Object.keys(keys)
    .map(key => `${key}=${keys[key]}`)
    .join('&')}`

export const getQueryStringState = query => mapper.map(mappings, query)
export const updateQueryString = state =>
  history.replace({
    search: encodeURI(keysToQuery(mapper.map(reverseMappings, state)))
  })
<|endoftext|>


<commit_before>var typecheck = require('./typeinference').typecheck,
    nodes = require('./nodes').nodes,
    types = require('./types'),
    parser = require('./parser').parser,
    lexer = require('./lexer'),
    _ = require('underscore');

// Assigning the nodes to `parser.yy` allows the grammar to access the nodes from
// the `yy` namespace.
parser.yy = nodes;

parser.lexer =  {
    "lex": function() {
        var token = this.tokens[this.pos] ? this.tokens[this.pos++] : ['EOF'];
        this.yytext = token[1];
        this.yylineno = token[2];
        return token[0];
    },
    "setInput": function(tokens) {
        this.tokens = tokens;
        this.pos = 0;
    },
    "upcomingInput": function() {
        return "";
    }
};

// Compile an abstract syntax tree (AST) node to JavaScript.
var data = {};
var macros = {};
var indent = 0;
var getIndent = function(extra) {
    if(!extra) {
        extra = 0;
    }
    var spacing = "";
    var i;
    for(i = 0; i < indent + extra; i++) {
        spacing += "    ";
    }
    return spacing;
};
var joinIndent = function(args, extra) {
    var lineIndent = "\n" + getIndent(extra);
    var argIndent = args.join("\n" + getIndent(extra));
    if(argIndent) {
        return argIndent + lineIndent;
    }
    return "";
};
var pushIndent = function() {
    indent++;
    return getIndent();
};
var popIndent = function() {
    indent--;
    return getIndent();
};
var compileNode = function(n) {
    return n.accept({
        // Function definition to JavaScript function.
        visitFunction: function() {
            var getArgs = function(a) {
                return _.map(a, function(v) {
                    return v.name;
                }).join(", ");
            };
            pushIndent();
            var compiledNodeBody = _.map(n.body, compileNode);
            var init = [];
            if(compiledNodeBody.length > 1) {
                init.push(compiledNodeBody.slice(0, compiledNodeBody.length - 1).join(';\n' + getIndent()) + ';');
            }
            var lastString = compiledNodeBody[compiledNodeBody.length - 1];
            var varEquals = "";
            if(n.name) {
                varEquals = "var " + n.name + " = ";
            }
            return varEquals + "function(" + getArgs(n.args) + ") {\n" +
                getIndent() + joinIndent(init) + "return " + lastString +
                ";\n" + popIndent() + "}";
        },
        visitIfThenElse: function() {
            var compiledNodeCondition = compileNode(n.condition);

            var compileAppendSemicolon = function(n) {
                return compileNode(n) + ';';
            };

            pushIndent();
            pushIndent();
            var compiledNodeIfTrueInit = joinIndent(_.map(n.ifTrue.slice(0, n.ifTrue.length - 1), compileAppendSemicolon));
            var compiledNodeIfTrueLast = compileNode(n.ifTrue[n.ifTrue.length - 1]);
            var compiledNodeIfFalseInit = joinIndent(_.map(n.ifFalse.slice(0, n.ifFalse.length - 1), compileAppendSemicolon));
            var compiledNodeIfFalseLast = compileNode(n.ifFalse[n.ifFalse.length - 1]);
            popIndent();
            popIndent();

            return "(function() {\n" +
                getIndent(1) + "if(" + compiledNodeCondition + ") {\n" +
                getIndent(2) + compiledNodeIfTrueInit + "return " + compiledNodeIfTrueLast + ";\n" +
                getIndent(1) + "} else {\n" +
                getIndent(2) + compiledNodeIfFalseInit + "return " + compiledNodeIfFalseLast + ";\n" +
                getIndent(1) + "}\n" +
                getIndent() + "})()";
        },
        // Let binding to JavaScript variable.
        visitLet: function() {
            return "var " + n.name + " = " + compileNode(n.value) + ";";
        },
        visitData: function() {
            _.each(n.tags, function(tag) {
                data[tag.name] = n.name;
            });
            var defs = _.map(n.tags, compileNode);
            return defs.join("\n");
        },
        visitReplacement: function() {
            return n.value;
        },
        visitQuoted: function() {
            var serializeNode = {
                visitReplacement: function(v) {
                    return "new nodes.Replacement(" + compileNode(v.value) + ")";
                },
                visitIdentifier: function(v) {
                    return "new nodes.Identifier(" + JSON.stringify(v.value) + ")";
                },
                visitAccess: function(v) {
                    return "new nodes.Access(" + serialize(v.value) + ", " + JSON.stringify(v.property) + ")";
                },
                visitCall: function(v) {
                    return "new nodes.Call(" + serialize(v.func) + ", [" + _.map(v.args, serialize).join(', ') + "])";
                }
            };
            var serialize = function(v) {
                return v.accept(serializeNode);
            };
            return serialize(n.value);
        },
        visitMacro: function() {
            var init = n.body.slice(0, n.body.length - 1);
            var last = n.body[n.body.length - 1];
            var code = _.map(init, compileNode).join('\n') + '\nreturn ' + compileNode(last) + ';';
            macros[n.name] = 'var nodes = this.nodes; ' + code;
        },
        visitReturn: function() {
            return "return __monad__[\"return\"](" + compileNode(n.value) + ");";
        },
        visitBind: function() {
            return "return __monad__[\"bind\"](" + compileNode(n.value) +
                ", function(" + n.name + ") {\n" + pushIndent() +
                _.map(n.rest, compileNode).join("\n" + getIndent()) + "\n" +
                popIndent() + "});";
        },
        visitDo: function() {
            var compiledInit = [];
            var firstBind;
            var lastBind;
            var lastBindIndex = 0;
            _.each(n.body, function(node, i) {
                if(node instanceof nodes.Bind) {
                    if(!lastBind) {
                        firstBind = node;
                    } else {
                        lastBind.rest = n.body.slice(lastBindIndex + 1, i + 1);
                    }
                    lastBindIndex = i;
                    lastBind = node;
                } else {
                    if(!lastBind) {
                        compiledInit.push(compileNode(node));
                    }
                }
            });
            lastBind.rest = n.body.slice(lastBindIndex + 1);
            return "(function(){\n" + pushIndent() + "var __monad__ = " +
                compileNode(n.value) + ";\n" + getIndent() +
                compiledInit.join('\n' + getIndent()) +
                compileNode(firstBind) + "\n" + popIndent() + "})()";
        },
        visitTag: function() {
            var args = _.map(n.vars, function(v) {
                return v.value;
            });
            var setters = _.map(n.vars, function(v, i) {
                return "this._" + i + " = " + v.value;
            });
            return "var " + n.name + " = function(" + args.join(", ") + "){" + setters.join(";") + "};";
        },
        visitMatch: function() {
            var flatMap = function(a, f) {
                return _.flatten(_.map(a, f));
            };

            var pathConditions = _.map(n.cases, function(c) {
                var getVars = function(pattern, varPath) {
                    return flatMap(pattern.vars, function(a, i) {
                        var nextVarPath = varPath.slice();
                        nextVarPath.push(i);

                        return a.accept({
                            visitIdentifier: function() {
                                if(a.value in data) return [];

                                var accessors = _.map(nextVarPath, function(x) {
                                    return "._" + x;
                                }).join('');
                                return ["var " + a.value + " = " + compileNode(n.value) + accessors + ";"];
                            },
                            visitPattern: function() {
                                return getVars(a, nextVarPath);
                            }
                        });
                    });
                };
                var vars = getVars(c.pattern, []);

                var getTagPaths = function(pattern, patternPath) {
                    return flatMap(pattern.vars, function(a, i) {
                        var nextPatternPath = patternPath.slice();

                        nextPatternPath.push(i);
                        return a.accept({
                            visitIdentifier: function() {
                                if(a.value in data) {
                                    return [{path: nextPatternPath, tag: a}];
                                }
                                return [];
                            },
                            visitPattern: function() {
                                var inner = getTagPaths(a, nextPatternPath);
                                inner.unshift({path: nextPatternPath, tag: a.tag});
                                return inner;
                            }
                        });
                    });
                };
                var tagPaths = getTagPaths(c.pattern, []);
                var compiledValue = compileNode(n.value);
                var extraConditions = _.map(tagPaths, function(e) {
                    return ' && ' + compiledValue + '._' + e.path.join('._') + ' instanceof ' + e.tag.value;
                }).join('');

                // More specific patterns need to appear first
                // Need to sort by the length of the path
                var maxTagPath = _.max(tagPaths, function(t) {
                    return t.path.length;
                });
                var maxPath = maxTagPath ? maxTagPath.path : [];

                return {
                    path: maxPath,
                    condition: "if(" + compiledValue + " instanceof " + c.pattern.tag.value +
                        extraConditions + ") {\n" + getIndent(2) +
                        joinIndent(vars, 2) + "return " + compileNode(c.value) +
                        ";\n" + getIndent(1) + "}"
                };
            });

            var cases = _.map(_.sortBy(pathConditions, function(t) {
                return -t.path.length;
            }), function(e) {
                return e.condition;
            });

            return "(function() {\n" + getIndent(1) + cases.join(" else ") + "\n" + getIndent() + "})()";
        },
        // Call to JavaScript call.
        visitCall: function() {
            if(macros[n.func.value]) {
                // Is a macro
                var f = new Function(macros[n.func.value]);
                var tree = f.apply({nodes: nodes}, n.args);
                // TODO: Give an actual env
                typecheck([tree], {});
                return compileNode(tree);
            } else if(data[n.func.value]) {
                // Is a tag
                return 'new ' + n.func.value + "(" + _.map(n.args, compileNode).join(", ") + ")";
            }
            return compileNode(n.func) + "(" + _.map(n.args, compileNode).join(", ") + ")";
        },
        visitAccess: function() {
            return compileNode(n.value) + "." + n.property;
        },
        visitBinaryGenericOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitBinaryNumberOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitBinaryBooleanOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitBinaryStringOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitWith: function() {
            var args = compileNode(n.left) + ', ' + compileNode(n.right);
            var inner = _.map(['__l__', '__r__'], function(name) {
                return 'for(__n__ in ' + name + ') {\n' + getIndent(2) + '__o__[__n__] = ' + name + '[__n__];\n' + getIndent(1) + '}';
            });
            return joinIndent(['(function(__l__, __r__) {', 'var __o__ = {}, __n__;'], 1) + joinIndent(inner, 1) + 'return __o__;\n' + getIndent() + '})(' + args + ')';
        },
        // Print all other nodes directly.
        visitComment: function() {
            return n.value;
        },
        visitIdentifier: function() {
            var prefix = '';
            var suffix = '';
            if(data[n.value]) {
                prefix = 'new ';
                suffix = '()';
            }
            return prefix + n.value + suffix;
        },
        visitNumber: function() {
            return n.value;
        },
        visitString: function() {
            return n.value;
        },
        visitBoolean: function() {
            return n.value;
        },
        visitUnit: function() {
            return "null";
        },
        visitArray: function() {
            return '[' + _.map(n.values, compileNode).join(', ') + ']';
        },
        visitTuple: function() {
            return '[' + _.map(n.values, compileNode).join(', ') + ']';
        },
        visitObject: function() {
            var key;
            var pairs = [];
            pushIndent();
            for(key in n.values) {
                pairs.push("\"" + key + "\": " + compileNode(n.values[key]));
            }
            return "{\n" + getIndent() + pairs.join(",\n" + getIndent()) + "\n" + popIndent() + "}";
        }
    });
};

var compile = function(source, env, opts) {
    if(!env) env = {};
    if(!opts) opts = {};

    // Parse the file to an AST.
    var tokens = lexer.tokenise(source);
    var ast = parser.parse(tokens);

    // Typecheck the AST. Any type errors will throw an exception.
    var typeA = new types.Variable();
    var typeB = new types.Variable();
    var resultType = typecheck(ast, env);

    // Output strict JavaScript.
    var output = [];
    if(opts.strict) {
        output.push('"use strict";');
    }
    _.each(ast, function(v) {
        output.push(compileNode(v));
    });
    // Add a newline at the end
    output.push("");

    return {type: resultType, output: output.join('\n')};
};
exports.compile = compile;

var getSandbox = function() {
    var sandbox = {require: require};

    var name;
    for(name in global) {
        sandbox[name] = global[name];
    }

    return sandbox;
};

var nodeRepl = function() {
    var readline = require('readline');
    var fs = require('fs');
    var path = require('path');
    var vm = require('vm');
    var stdout = process.stdout;
    var stdin = process.openStdin();
    var repl = readline.createInterface(stdin, stdout);

    var env = {};
    var sandbox = getSandbox();

    // Include the standard library
    var stdlib = fs.readFileSync(path.dirname(__dirname) + '/lib/std.roy', 'utf8');
    vm.runInNewContext(compile(stdlib, env).output, sandbox, 'eval');

    repl.setPrompt('roy> ');
    repl.on('close', function() {
        stdin.destroy();
    });
    repl.on('line', function(line) {
        var compiled;
        var output;
        try {
            compiled = compile(line, env);
            output = vm.runInNewContext(compiled.output, sandbox, 'eval');
            if(typeof output != 'undefined') console.log(output + " : " + compiled.type);
        } catch(e) {
            console.log((e.stack || e.toString()) + '\n\n');
        }
        repl.prompt();
    });
    repl.prompt();
};

var main = function() {
    if(process.argv.length < 3) {
        nodeRepl();
        return;
    }

    var fs = require('fs');
    var path = require('path');
    var filenames = process.argv.slice(2);

    var vm;
    var run = false;
    if(filenames[0] == '-r') {
        vm = require('vm');
        run = true;
        filenames.shift();
    }

    // Include the standard library
    filenames.unshift(path.dirname(__dirname) + '/lib/std.roy');

    var env = {};
    var sandbox = getSandbox();
    _.each(filenames, function(filename) {
        // Read the file content.
        var source = fs.readFileSync(filename, 'utf8');

        // Write the JavaScript output.
        var extension = /\.roy$/;
        console.assert(filename.match(extension), 'Filename must end with ".roy"');
        var compiled = compile(source, env);
        if(run) {
            output = vm.runInNewContext(compiled.output, sandbox, 'eval');
        } else {
            fs.writeFile(filename.replace(extension, '.js'), compiled.output, 'utf8');
        }
    });
};
exports.main = main;

if(exports && !module.parent) {
    main();
}
<commit_msg>Add Repl Command to exit (':q')<commit_after>var typecheck = require('./typeinference').typecheck,
    nodes = require('./nodes').nodes,
    types = require('./types'),
    parser = require('./parser').parser,
    lexer = require('./lexer'),
    _ = require('underscore');

// Assigning the nodes to `parser.yy` allows the grammar to access the nodes from
// the `yy` namespace.
parser.yy = nodes;

parser.lexer =  {
    "lex": function() {
        var token = this.tokens[this.pos] ? this.tokens[this.pos++] : ['EOF'];
        this.yytext = token[1];
        this.yylineno = token[2];
        return token[0];
    },
    "setInput": function(tokens) {
        this.tokens = tokens;
        this.pos = 0;
    },
    "upcomingInput": function() {
        return "";
    }
};

// Compile an abstract syntax tree (AST) node to JavaScript.
var data = {};
var macros = {};
var indent = 0;
var getIndent = function(extra) {
    if(!extra) {
        extra = 0;
    }
    var spacing = "";
    var i;
    for(i = 0; i < indent + extra; i++) {
        spacing += "    ";
    }
    return spacing;
};
var joinIndent = function(args, extra) {
    var lineIndent = "\n" + getIndent(extra);
    var argIndent = args.join("\n" + getIndent(extra));
    if(argIndent) {
        return argIndent + lineIndent;
    }
    return "";
};
var pushIndent = function() {
    indent++;
    return getIndent();
};
var popIndent = function() {
    indent--;
    return getIndent();
};
var compileNode = function(n) {
    return n.accept({
        // Function definition to JavaScript function.
        visitFunction: function() {
            var getArgs = function(a) {
                return _.map(a, function(v) {
                    return v.name;
                }).join(", ");
            };
            pushIndent();
            var compiledNodeBody = _.map(n.body, compileNode);
            var init = [];
            if(compiledNodeBody.length > 1) {
                init.push(compiledNodeBody.slice(0, compiledNodeBody.length - 1).join(';\n' + getIndent()) + ';');
            }
            var lastString = compiledNodeBody[compiledNodeBody.length - 1];
            var varEquals = "";
            if(n.name) {
                varEquals = "var " + n.name + " = ";
            }
            return varEquals + "function(" + getArgs(n.args) + ") {\n" +
                getIndent() + joinIndent(init) + "return " + lastString +
                ";\n" + popIndent() + "}";
        },
        visitIfThenElse: function() {
            var compiledNodeCondition = compileNode(n.condition);

            var compileAppendSemicolon = function(n) {
                return compileNode(n) + ';';
            };

            pushIndent();
            pushIndent();
            var compiledNodeIfTrueInit = joinIndent(_.map(n.ifTrue.slice(0, n.ifTrue.length - 1), compileAppendSemicolon));
            var compiledNodeIfTrueLast = compileNode(n.ifTrue[n.ifTrue.length - 1]);
            var compiledNodeIfFalseInit = joinIndent(_.map(n.ifFalse.slice(0, n.ifFalse.length - 1), compileAppendSemicolon));
            var compiledNodeIfFalseLast = compileNode(n.ifFalse[n.ifFalse.length - 1]);
            popIndent();
            popIndent();

            return "(function() {\n" +
                getIndent(1) + "if(" + compiledNodeCondition + ") {\n" +
                getIndent(2) + compiledNodeIfTrueInit + "return " + compiledNodeIfTrueLast + ";\n" +
                getIndent(1) + "} else {\n" +
                getIndent(2) + compiledNodeIfFalseInit + "return " + compiledNodeIfFalseLast + ";\n" +
                getIndent(1) + "}\n" +
                getIndent() + "})()";
        },
        // Let binding to JavaScript variable.
        visitLet: function() {
            return "var " + n.name + " = " + compileNode(n.value) + ";";
        },
        visitData: function() {
            _.each(n.tags, function(tag) {
                data[tag.name] = n.name;
            });
            var defs = _.map(n.tags, compileNode);
            return defs.join("\n");
        },
        visitReplacement: function() {
            return n.value;
        },
        visitQuoted: function() {
            var serializeNode = {
                visitReplacement: function(v) {
                    return "new nodes.Replacement(" + compileNode(v.value) + ")";
                },
                visitIdentifier: function(v) {
                    return "new nodes.Identifier(" + JSON.stringify(v.value) + ")";
                },
                visitAccess: function(v) {
                    return "new nodes.Access(" + serialize(v.value) + ", " + JSON.stringify(v.property) + ")";
                },
                visitCall: function(v) {
                    return "new nodes.Call(" + serialize(v.func) + ", [" + _.map(v.args, serialize).join(', ') + "])";
                }
            };
            var serialize = function(v) {
                return v.accept(serializeNode);
            };
            return serialize(n.value);
        },
        visitMacro: function() {
            var init = n.body.slice(0, n.body.length - 1);
            var last = n.body[n.body.length - 1];
            var code = _.map(init, compileNode).join('\n') + '\nreturn ' + compileNode(last) + ';';
            macros[n.name] = 'var nodes = this.nodes; ' + code;
        },
        visitReturn: function() {
            return "return __monad__[\"return\"](" + compileNode(n.value) + ");";
        },
        visitBind: function() {
            return "return __monad__[\"bind\"](" + compileNode(n.value) +
                ", function(" + n.name + ") {\n" + pushIndent() +
                _.map(n.rest, compileNode).join("\n" + getIndent()) + "\n" +
                popIndent() + "});";
        },
        visitDo: function() {
            var compiledInit = [];
            var firstBind;
            var lastBind;
            var lastBindIndex = 0;
            _.each(n.body, function(node, i) {
                if(node instanceof nodes.Bind) {
                    if(!lastBind) {
                        firstBind = node;
                    } else {
                        lastBind.rest = n.body.slice(lastBindIndex + 1, i + 1);
                    }
                    lastBindIndex = i;
                    lastBind = node;
                } else {
                    if(!lastBind) {
                        compiledInit.push(compileNode(node));
                    }
                }
            });
            lastBind.rest = n.body.slice(lastBindIndex + 1);
            return "(function(){\n" + pushIndent() + "var __monad__ = " +
                compileNode(n.value) + ";\n" + getIndent() +
                compiledInit.join('\n' + getIndent()) +
                compileNode(firstBind) + "\n" + popIndent() + "})()";
        },
        visitTag: function() {
            var args = _.map(n.vars, function(v) {
                return v.value;
            });
            var setters = _.map(n.vars, function(v, i) {
                return "this._" + i + " = " + v.value;
            });
            return "var " + n.name + " = function(" + args.join(", ") + "){" + setters.join(";") + "};";
        },
        visitMatch: function() {
            var flatMap = function(a, f) {
                return _.flatten(_.map(a, f));
            };

            var pathConditions = _.map(n.cases, function(c) {
                var getVars = function(pattern, varPath) {
                    return flatMap(pattern.vars, function(a, i) {
                        var nextVarPath = varPath.slice();
                        nextVarPath.push(i);

                        return a.accept({
                            visitIdentifier: function() {
                                if(a.value in data) return [];

                                var accessors = _.map(nextVarPath, function(x) {
                                    return "._" + x;
                                }).join('');
                                return ["var " + a.value + " = " + compileNode(n.value) + accessors + ";"];
                            },
                            visitPattern: function() {
                                return getVars(a, nextVarPath);
                            }
                        });
                    });
                };
                var vars = getVars(c.pattern, []);

                var getTagPaths = function(pattern, patternPath) {
                    return flatMap(pattern.vars, function(a, i) {
                        var nextPatternPath = patternPath.slice();

                        nextPatternPath.push(i);
                        return a.accept({
                            visitIdentifier: function() {
                                if(a.value in data) {
                                    return [{path: nextPatternPath, tag: a}];
                                }
                                return [];
                            },
                            visitPattern: function() {
                                var inner = getTagPaths(a, nextPatternPath);
                                inner.unshift({path: nextPatternPath, tag: a.tag});
                                return inner;
                            }
                        });
                    });
                };
                var tagPaths = getTagPaths(c.pattern, []);
                var compiledValue = compileNode(n.value);
                var extraConditions = _.map(tagPaths, function(e) {
                    return ' && ' + compiledValue + '._' + e.path.join('._') + ' instanceof ' + e.tag.value;
                }).join('');

                // More specific patterns need to appear first
                // Need to sort by the length of the path
                var maxTagPath = _.max(tagPaths, function(t) {
                    return t.path.length;
                });
                var maxPath = maxTagPath ? maxTagPath.path : [];

                return {
                    path: maxPath,
                    condition: "if(" + compiledValue + " instanceof " + c.pattern.tag.value +
                        extraConditions + ") {\n" + getIndent(2) +
                        joinIndent(vars, 2) + "return " + compileNode(c.value) +
                        ";\n" + getIndent(1) + "}"
                };
            });

            var cases = _.map(_.sortBy(pathConditions, function(t) {
                return -t.path.length;
            }), function(e) {
                return e.condition;
            });

            return "(function() {\n" + getIndent(1) + cases.join(" else ") + "\n" + getIndent() + "})()";
        },
        // Call to JavaScript call.
        visitCall: function() {
            if(macros[n.func.value]) {
                // Is a macro
                var f = new Function(macros[n.func.value]);
                var tree = f.apply({nodes: nodes}, n.args);
                // TODO: Give an actual env
                typecheck([tree], {});
                return compileNode(tree);
            } else if(data[n.func.value]) {
                // Is a tag
                return 'new ' + n.func.value + "(" + _.map(n.args, compileNode).join(", ") + ")";
            }
            return compileNode(n.func) + "(" + _.map(n.args, compileNode).join(", ") + ")";
        },
        visitAccess: function() {
            return compileNode(n.value) + "." + n.property;
        },
        visitBinaryGenericOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitBinaryNumberOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitBinaryBooleanOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitBinaryStringOperator: function() {
            return [compileNode(n.left), n.name, compileNode(n.right)].join(" ");
        },
        visitWith: function() {
            var args = compileNode(n.left) + ', ' + compileNode(n.right);
            var inner = _.map(['__l__', '__r__'], function(name) {
                return 'for(__n__ in ' + name + ') {\n' + getIndent(2) + '__o__[__n__] = ' + name + '[__n__];\n' + getIndent(1) + '}';
            });
            return joinIndent(['(function(__l__, __r__) {', 'var __o__ = {}, __n__;'], 1) + joinIndent(inner, 1) + 'return __o__;\n' + getIndent() + '})(' + args + ')';
        },
        // Print all other nodes directly.
        visitComment: function() {
            return n.value;
        },
        visitIdentifier: function() {
            var prefix = '';
            var suffix = '';
            if(data[n.value]) {
                prefix = 'new ';
                suffix = '()';
            }
            return prefix + n.value + suffix;
        },
        visitNumber: function() {
            return n.value;
        },
        visitString: function() {
            return n.value;
        },
        visitBoolean: function() {
            return n.value;
        },
        visitUnit: function() {
            return "null";
        },
        visitArray: function() {
            return '[' + _.map(n.values, compileNode).join(', ') + ']';
        },
        visitTuple: function() {
            return '[' + _.map(n.values, compileNode).join(', ') + ']';
        },
        visitObject: function() {
            var key;
            var pairs = [];
            pushIndent();
            for(key in n.values) {
                pairs.push("\"" + key + "\": " + compileNode(n.values[key]));
            }
            return "{\n" + getIndent() + pairs.join(",\n" + getIndent()) + "\n" + popIndent() + "}";
        }
    });
};

var compile = function(source, env, opts) {
    if(!env) env = {};
    if(!opts) opts = {};

    // Parse the file to an AST.
    var tokens = lexer.tokenise(source);
    var ast = parser.parse(tokens);

    // Typecheck the AST. Any type errors will throw an exception.
    var typeA = new types.Variable();
    var typeB = new types.Variable();
    var resultType = typecheck(ast, env);

    // Output strict JavaScript.
    var output = [];
    if(opts.strict) {
        output.push('"use strict";');
    }
    _.each(ast, function(v) {
        output.push(compileNode(v));
    });
    // Add a newline at the end
    output.push("");

    return {type: resultType, output: output.join('\n')};
};
exports.compile = compile;

var getSandbox = function() {
    var sandbox = {require: require};

    var name;
    for(name in global) {
        sandbox[name] = global[name];
    }

    return sandbox;
};

var nodeRepl = function() {
    var readline = require('readline');
    var fs = require('fs');
    var path = require('path');
    var vm = require('vm');
    var stdout = process.stdout;
    var stdin = process.openStdin();
    var repl = readline.createInterface(stdin, stdout);

    var env = {};
    var sandbox = getSandbox();

    // Include the standard library
    var stdlib = fs.readFileSync(path.dirname(__dirname) + '/lib/std.roy', 'utf8');
    vm.runInNewContext(compile(stdlib, env).output, sandbox, 'eval');

    repl.setPrompt('roy> ');
    repl.on('close', function() {
        stdin.destroy();
    });
    repl.on('line', function(line) {
        var compiled;
        var output;
        try {
            if (line.replace(/^\s+/g,"").replace(/\s+$/g,"") == ":q"){
                process.exit();
            }
            compiled = compile(line, env);
            output = vm.runInNewContext(compiled.output, sandbox, 'eval');
            if(typeof output != 'undefined') console.log(output + " : " + compiled.type);
        } catch(e) {
            console.log((e.stack || e.toString()) + '\n\n');
        }
        repl.prompt();
    });
    repl.prompt();
};

var main = function() {
    if(process.argv.length < 3) {
        nodeRepl();
        return;
    }

    var fs = require('fs');
    var path = require('path');
    var filenames = process.argv.slice(2);

    var vm;
    var run = false;
    if(filenames[0] == '-r') {
        vm = require('vm');
        run = true;
        filenames.shift();
    }

    // Include the standard library
    filenames.unshift(path.dirname(__dirname) + '/lib/std.roy');

    var env = {};
    var sandbox = getSandbox();
    _.each(filenames, function(filename) {
        // Read the file content.
        var source = fs.readFileSync(filename, 'utf8');

        // Write the JavaScript output.
        var extension = /\.roy$/;
        console.assert(filename.match(extension), 'Filename must end with ".roy"');
        var compiled = compile(source, env);
        if(run) {
            output = vm.runInNewContext(compiled.output, sandbox, 'eval');
        } else {
            fs.writeFile(filename.replace(extension, '.js'), compiled.output, 'utf8');
        }
    });
};
exports.main = main;

if(exports && !module.parent) {
    main();
}
<|endoftext|>