<commit_before>/* global describe, beforeEach, it*/

const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');
const constants = require('../generators/generator-constants');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;

describe('JHipster generator languages', () => {
    const languages = [
        { name: 'Armenian', value: 'hy' },
        { name: 'Catalan', value: 'ca' },
        { name: 'Chinese (Simplified)', value: 'zh-cn' },
        { name: 'Chinese (Traditional)', value: 'zh-tw' },
        { name: 'Czech', value: 'cs' },
        { name: 'Danish', value: 'da' },
        { name: 'Dutch', value: 'nl' },
        { name: 'Estonian', value: 'et' },
        { name: 'Galician', value: 'gl' },
        { name: 'German', value: 'de' },
        { name: 'Greek', value: 'el' },
        { name: 'Hindi', value: 'hi' },
        { name: 'Hungarian', value: 'hu' },
        { name: 'Indonesia', value: 'id' },
        { name: 'Italian', value: 'it' },
        { name: 'Japanese', value: 'ja' },
        { name: 'Korean', value: 'ko' },
        { name: 'Marathi', value: 'mr' },
        { name: 'Polish', value: 'pl' },
        { name: 'Portuguese (Brazilian)', value: 'pt-br' },
        { name: 'Portuguese', value: 'pt-pt' },
        { name: 'Romanian', value: 'ro' },
        { name: 'Russian', value: 'ru' },
        { name: 'Slovak', value: 'sk' },
        { name: 'Serbian', value: 'sr' },
        { name: 'Spanish', value: 'es' },
        { name: 'Swedish', value: 'sv' },
        { name: 'Turkish', value: 'tr' },
        { name: 'Tamil', value: 'ta' },
        { name: 'Ukrainian', value: 'ua' },
        { name: 'Vietnamese', value: 'vi' }
    ];

    languages.forEach((language) => {
        describe(`no social - creates ${language.name}`, () => {
            beforeEach((done) => {
                helpers.run(require.resolve('../generators/languages'))
                    .inTmpDir((dir) => {
                        fse.copySync(path.join(__dirname, '../test/templates/default'), dir);
                    })
                    .withOptions({ 'skip-install': true })
                    .withPrompts({
                        languages: [language.value]
                    })
                    .on('end', done);
            });

            it('creates expected files', () => {
                assert.file([
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/activate.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/audits.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/configuration.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/error.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/gateway.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/login.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/logs.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/home.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/metrics.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/password.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/register.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/sessions.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/settings.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/reset.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/user-management.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/health.json`,
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${language.value.replace('-', '_')}.properties`
                ]);
            });
            it('doesnt create social.json', () => {
                assert.noFile([
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/social.json`
                ]);
            });
            it('contains 3 needles in global.json', () => {
                assert.fileContent(`${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    '"jhipster-needle-menu-add-element": "JHipster will add additional menu entries here (do not translate!)"');
                assert.fileContent(`${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    '"jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)"');
                assert.fileContent(`${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    '"jhipster-needle-menu-add-admin-element": "JHipster will add additional menu entries here (do not translate!)"');
            });
        });
    });

    languages.forEach((language) => {
        describe(`with social - creates ${language.name}`, () => {
            beforeEach((done) => {
                helpers.run(require.resolve('../generators/languages'))
                    .inTmpDir((dir) => {
                        fse.copySync(path.join(__dirname, '../test/templates/social'), dir);
                    })
                    .withOptions({ 'skip-install': true })
                    .withPrompts({
                        languages: [language.value]
                    })
                    .on('end', done);
            });

            it('creates expected files', () => {
                assert.file([
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/activate.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/audits.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/configuration.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/error.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/gateway.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/login.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/logs.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/home.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/metrics.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/password.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/register.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/sessions.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/settings.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/reset.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/user-management.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/health.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/social.json`,
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${language.value.replace('-', '_')}.properties`
                ]);
            });
        });
    });
});
<commit_msg>change the test-language Indonesia to Bahasa Indonesia<commit_after>/* global describe, beforeEach, it*/

const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');
const constants = require('../generators/generator-constants');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;

describe('JHipster generator languages', () => {
    const languages = [
        { name: 'Armenian', value: 'hy' },
        { name: 'Catalan', value: 'ca' },
        { name: 'Chinese (Simplified)', value: 'zh-cn' },
        { name: 'Chinese (Traditional)', value: 'zh-tw' },
        { name: 'Czech', value: 'cs' },
        { name: 'Danish', value: 'da' },
        { name: 'Dutch', value: 'nl' },
        { name: 'Estonian', value: 'et' },
        { name: 'Galician', value: 'gl' },
        { name: 'German', value: 'de' },
        { name: 'Greek', value: 'el' },
        { name: 'Hindi', value: 'hi' },
        { name: 'Hungarian', value: 'hu' },
        { name: 'Bahasa Indonesia', value: 'id' },
        { name: 'Italian', value: 'it' },
        { name: 'Japanese', value: 'ja' },
        { name: 'Korean', value: 'ko' },
        { name: 'Marathi', value: 'mr' },
        { name: 'Polish', value: 'pl' },
        { name: 'Portuguese (Brazilian)', value: 'pt-br' },
        { name: 'Portuguese', value: 'pt-pt' },
        { name: 'Romanian', value: 'ro' },
        { name: 'Russian', value: 'ru' },
        { name: 'Slovak', value: 'sk' },
        { name: 'Serbian', value: 'sr' },
        { name: 'Spanish', value: 'es' },
        { name: 'Swedish', value: 'sv' },
        { name: 'Turkish', value: 'tr' },
        { name: 'Tamil', value: 'ta' },
        { name: 'Ukrainian', value: 'ua' },
        { name: 'Vietnamese', value: 'vi' }
    ];

    languages.forEach((language) => {
        describe(`no social - creates ${language.name}`, () => {
            beforeEach((done) => {
                helpers.run(require.resolve('../generators/languages'))
                    .inTmpDir((dir) => {
                        fse.copySync(path.join(__dirname, '../test/templates/default'), dir);
                    })
                    .withOptions({ 'skip-install': true })
                    .withPrompts({
                        languages: [language.value]
                    })
                    .on('end', done);
            });

            it('creates expected files', () => {
                assert.file([
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/activate.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/audits.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/configuration.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/error.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/gateway.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/login.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/logs.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/home.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/metrics.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/password.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/register.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/sessions.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/settings.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/reset.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/user-management.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/health.json`,
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${language.value.replace('-', '_')}.properties`
                ]);
            });
            it('doesnt create social.json', () => {
                assert.noFile([
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/social.json`
                ]);
            });
            it('contains 3 needles in global.json', () => {
                assert.fileContent(`${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    '"jhipster-needle-menu-add-element": "JHipster will add additional menu entries here (do not translate!)"');
                assert.fileContent(`${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    '"jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)"');
                assert.fileContent(`${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    '"jhipster-needle-menu-add-admin-element": "JHipster will add additional menu entries here (do not translate!)"');
            });
        });
    });

    languages.forEach((language) => {
        describe(`with social - creates ${language.name}`, () => {
            beforeEach((done) => {
                helpers.run(require.resolve('../generators/languages'))
                    .inTmpDir((dir) => {
                        fse.copySync(path.join(__dirname, '../test/templates/social'), dir);
                    })
                    .withOptions({ 'skip-install': true })
                    .withPrompts({
                        languages: [language.value]
                    })
                    .on('end', done);
            });

            it('creates expected files', () => {
                assert.file([
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/activate.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/audits.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/configuration.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/error.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/gateway.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/login.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/logs.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/home.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/metrics.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/password.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/register.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/sessions.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/settings.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/reset.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/user-management.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/global.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/health.json`,
                    `${CLIENT_MAIN_SRC_DIR}i18n/${language.value}/social.json`,
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${language.value.replace('-', '_')}.properties`
                ]);
            });
        });
    });
});
<|endoftext|>


<commit_before>var rucksack = require('rucksack-css');
var cssnext = require('cssnext');
var path = require('path');

module.exports = {
    context: path.join(__dirname, './app'),
    entry: {
        jsx: './index.js',
        html: './index.html',
        vendor: ['react']
    },
    output: {
        path: path.join(__dirname, './build'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.html$/,
                loaders: [
                    'file?name=[name].[ext]'
                ]
            },
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                loaders: [
                    'react-hot',
                    'babel-loader'
                ]
            },
            {
                test: /\.css$/,
                loaders: [
                    'style-loader',
                    'css-loader?modules&importLoaders=1',
                    'postcss-loader'
                ]
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    postcss: function() {
        return [
            cssnext,
            rucksack({
                autoprefixer: true
            })
        ];
    }
};
<commit_msg>Remove vendor chunk configuration from webpack config<commit_after>var webpack = require('webpack');
var rucksack = require('rucksack-css');
var cssnext = require('cssnext');
var path = require('path');

module.exports = {
    context: path.join(__dirname, './app'),
    entry: {
        jsx: './index.js',
        html: './index.html'
    },
    output: {
        path: path.join(__dirname, './build'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.html$/,
                loaders: [
                    'file?name=[name].[ext]'
                ]
            },
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                loaders: [
                    'react-hot',
                    'babel-loader'
                ]
            },
            {
                test: /\.css$/,
                loaders: [
                    'style-loader',
                    'css-loader?modules&importLoaders=1',
                    'postcss-loader'
                ]
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    postcss: function() {
        return [
            cssnext,
            rucksack({
                autoprefixer: true
            })
        ];
    }
};
<|endoftext|>


<commit_before>var kanso = require('../lib/kanso'),
    dust = require('../deps/dustjs/lib/dust'),
    settings = require('../lib/settings'),
    fs = require('fs');

// integration test
exports['load'] = function (test) {
    var pdir = __dirname + '/fixtures/testproject';
    settings.load(pdir, function (err, settings) {
        test.ifError(err);
        kanso.load(pdir, settings, function (err, doc) {
            if (err) {
                throw err;
            }
            test.same(doc.settings, {
                'name': 'testproject',
                'load': 'lib/app',
                'modules': ['deps','lib'],
                'templates': 'templates',
                'attachments': 'static'
            });
            test.equals(doc.testproperty, 'test property');
            test.same(Object.keys(doc.lib).sort(), ['module1','app'].sort());
            test.equals(
                doc.lib.module1,
                fs.readFileSync(pdir + '/lib/module1.js').toString()
            );
            test.equals(
                doc.lib.app,
                fs.readFileSync(pdir + '/lib/app.js').toString()
            );
            test.same(doc.shows, {
                'testshow': 'function(){' +
                    'return require("lib/app")["shows"]["testshow"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.same(doc.lists, {
                'testlist': 'function(){' +
                    'return require("lib/app")["lists"]["testlist"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.same(doc.updates, {
                'testupdate': 'function(){' +
                    'return require("lib/app")["updates"]["testupdate"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.same(doc.filters, {
                'testfilter': 'function(){' +
                    'return require("lib/app")["filters"]["testfilter"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.equals(
                doc.validate_doc_update,
                'function(){' +
                    'return require("lib/app")["validate_doc_update"]' +
                        '.apply(this, arguments);' +
                '}'
            );
            test.same(doc.deps, {
                'module2': 'exports.name = "module two";\n'
            });
            test.equal(
                doc.no_proxy_function,
                'function (){return "test";}'
            );
            test.same(doc.no_proxy_obj, {
                fn1: 'function (){return "one";}',
                fn2: 'function (){return "two";}'
            });
            test.same(doc._attachments['static/test.txt'], {
                    'content_type': 'text/plain',
                    'data': 'dGVzdCBkYXRhCg=='
            });
            // TODO: test value of _attachments['kanso.js']
            test.same(doc.rewrites, [
                {from: '/kanso.js', to: 'kanso.js'},
                {from: '/_db/*', to: '../../*'},
                {from: '/', to: '_show/testshow'}
            ]);
            test.done();
        });
    });
};
<commit_msg>update unit tests for latest default rewrite rules<commit_after>var kanso = require('../lib/kanso'),
    dust = require('../deps/dustjs/lib/dust'),
    settings = require('../lib/settings'),
    fs = require('fs');

// integration test
exports['load'] = function (test) {
    var pdir = __dirname + '/fixtures/testproject';
    settings.load(pdir, function (err, settings) {
        test.ifError(err);
        kanso.load(pdir, settings, function (err, doc) {
            if (err) {
                throw err;
            }
            test.same(doc.settings, {
                'name': 'testproject',
                'load': 'lib/app',
                'modules': ['deps','lib'],
                'templates': 'templates',
                'attachments': 'static'
            });
            test.equals(doc.testproperty, 'test property');
            test.same(Object.keys(doc.lib).sort(), ['module1','app'].sort());
            test.equals(
                doc.lib.module1,
                fs.readFileSync(pdir + '/lib/module1.js').toString()
            );
            test.equals(
                doc.lib.app,
                fs.readFileSync(pdir + '/lib/app.js').toString()
            );
            test.same(doc.shows, {
                'testshow': 'function(){' +
                    'return require("lib/app")["shows"]["testshow"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.same(doc.lists, {
                'testlist': 'function(){' +
                    'return require("lib/app")["lists"]["testlist"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.same(doc.updates, {
                'testupdate': 'function(){' +
                    'return require("lib/app")["updates"]["testupdate"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.same(doc.filters, {
                'testfilter': 'function(){' +
                    'return require("lib/app")["filters"]["testfilter"]' +
                        '.apply(this, arguments);' +
                '}'
            });
            test.equals(
                doc.validate_doc_update,
                'function(){' +
                    'return require("lib/app")["validate_doc_update"]' +
                        '.apply(this, arguments);' +
                '}'
            );
            test.same(doc.deps, {
                'module2': 'exports.name = "module two";\n'
            });
            test.equal(
                doc.no_proxy_function,
                'function (){return "test";}'
            );
            test.same(doc.no_proxy_obj, {
                fn1: 'function (){return "one";}',
                fn2: 'function (){return "two";}'
            });
            test.same(doc._attachments['static/test.txt'], {
                    'content_type': 'text/plain',
                    'data': 'dGVzdCBkYXRhCg=='
            });
            // TODO: test value of _attachments['kanso.js']
            test.same(doc.rewrites, [
                {from: '/kanso.js', to: 'kanso.js'},
                {from: '/_db/*', to: '../../*'},
                {from: '/_db', to: '../..'},
                {from: '/', to: '_show/testshow'}
            ]);
            test.done();
        });
    });
};
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs');
const glob = require('glob')
const webpack = require('webpack')

// webpack plugins
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CompressionPlugin = require("compression-webpack-plugin")
const GenSourceCode = require('./webpack.gensrc')
const WebpackI18nPlugin = require("./webpack.i18n");

const date = new Date()
const DEV_MODE = process.env.NODE_ENV !== 'production' && process.argv.indexOf('-p') === -1,
    BUILD_NUMBER = `${date.getYear() - 100}${date.getMonth() + 1}${date.getDate()}.${Math.ceil((date - new Date().setHours(0, 0, 0, 0)) / 8641)}`

/*---------------------------------------------------
 Define which directories are included from the build based on the config file
 ---------------------------------------------------*/

const EXCLUDE_FROM_BUILD = [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, 'test'),
    path.resolve(__dirname, 'server'),
    path.resolve(__dirname, 'build'),
    path.resolve(__dirname, 'extensions'),
    path.resolve(__dirname, 'client/components/ui'),
    path.resolve(__dirname, './api')]

const INCLUDE_IN_BUILD = []

const APP_CONFIG = require('./buildconfig.json')
const PACKAGE_JSON = require('./package.json')

const APP_VALUES = {
    DEV_MODE,
    BUILD_NUMBER,
    APP_NAME: PACKAGE_JSON.name,
    APP_VERSION: PACKAGE_JSON.version,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_COLOR: '#2196f3',
    ...APP_CONFIG.options
}

if (APP_CONFIG.extensions) {
    for (const extensionName in APP_CONFIG.extensions) {
        if (APP_CONFIG.extensions[extensionName].active) {
            INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'extensions/' + extensionName))
        }
    }
}

if (APP_CONFIG.ui) {
    APP_CONFIG.ui.forEach(ui => {
        INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'client/components/ui/impl/' + ui.impl))
    })
}

const excludeFunction = (path) => {

    for (let i = 0; i < EXCLUDE_FROM_BUILD.length; i++) {
        if (path.indexOf(EXCLUDE_FROM_BUILD[i]) === 0) {
            // it belongs to the excluded files

            for (let j = 0; j < INCLUDE_IN_BUILD.length; j++) {
                if (path.indexOf(INCLUDE_IN_BUILD[j]) === 0) {
                    // it is an exception and should be included anyway
                    return false
                }
            }

            return true
        }
    }
    return false
}

const replacePlaceholders = (content, path) => {

    const result = new Function('const {' + Object.keys(APP_VALUES).join(',') + '} = this.APP_VALUES;return `' + content + '`').call({APP_VALUES})
    return result
}

const config = {
    entry: './client/index.js',
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].bundle.js?v=' + BUILD_NUMBER,
        chunkFilename: '[name].bundle.js?v=' + BUILD_NUMBER,
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: excludeFunction,
                loader: 'babel-loader'
            },
            {
                test: /\.global\.css$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.global\.less$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "less-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    },
    plugins: [
        new GenSourceCode(APP_VALUES), /* Generate some source code based on the buildconfig.json file */
        new MiniCssExtractPlugin({
            filename: 'style.css',
            allChunks: true
        }), /* Extract css from bundle */
        new WebpackI18nPlugin({
            src: './**/*.tr.json',
            dest: '[name].js'
        })
    ],
    optimization: {
        /*splitChunks: {
         cacheGroups: {
         style: {
         name: 'style',
         test: (c) => {
         if (c.type === 'css/mini-extract') {
         const path = c._identifier
         //console.log(path.substring(path.lastIndexOf('/')+1))
         return true
         }
         return false
         },
         chunks: 'all',
         enforce: true
         }
         }
         },*/
        minimizer: []
    }/*optimization: {
     // We no not want to minimize our code.
     minimize: false
     }*/
}

const CopyWebpackPlugin = require('copy-webpack-plugin')
config.plugins.push(
    new CopyWebpackPlugin([
        {
            from: 'index.html', to: 'index.html',
            transform: replacePlaceholders
        },
        {
            from: 'index.min.html', to: 'index.min.html',
            transform: replacePlaceholders
        },
        {
            from: 'serviceworker.js', to: 'serviceworker.js',
            transform: replacePlaceholders
        },
        {
            from: 'manifest.json', to: 'manifest.json',
            transform: replacePlaceholders
        },
        {from: 'favicon.ico', to: 'favicon.ico'},
        {from: 'favicon.svg', to: 'favicon.svg'},
        {from: 'favicon-192x192.png', to: 'favicon-192x192.png'},
        {from: 'favicon-512x512.png', to: 'favicon-512x512.png'}
    ])
)

/**
 *  Developer / Debug Config
 */
if (DEV_MODE) {
    console.log('Build for developing')
    config.mode = 'development'

    const PORT = (process.env.PORT || 8080)
    const API_PORT = (process.env.API_PORT || 3000)

    config.devServer = {
        contentBase: [path.join(__dirname, ''), path.join(__dirname, 'static')],
        historyApiFallback: true,
        inline: true,
        hot: true,
        stats: 'errors-only',
        port: PORT,
        host: '0.0.0.0',
        proxy: {
            '/graphql': {target: `http://0.0.0.0:${API_PORT}`},
            '/ws': {
                target: `ws://localhost:${API_PORT}`,
                ws: true
            }
        }
    }

    /* For Debugging porpuses */
    config.devtool = 'eval'

    config.plugins.push(new webpack.HotModuleReplacementPlugin())

} else {
    console.log('Build for production')
    config.mode = 'production'

    config.plugins.push(
        new CompressionPlugin({
            minRatio: 0.95
        })
    )

    config.optimization.minimizer.push(
        new UglifyJSPlugin({
            uglifyOptions: {
                mangle: { keep_fnames: true },
                compress: {
                    drop_console: true
                },
                output: {
                    comments: false,
                    semicolons: true,
                    shebang: true,
                    beautify: false
                }
            }
        }))

    /*const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
     config.plugins.push(new BundleAnalyzerPlugin())*/

    //config.devtool = 'source-map'
}

module.exports = config

/* --port 8080 --hot --host 0.0.0.0 --content-base . */
<commit_msg>Small improvements<commit_after>const path = require('path')
const fs = require('fs');
const glob = require('glob')
const webpack = require('webpack')

// webpack plugins
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CompressionPlugin = require("compression-webpack-plugin")
const GenSourceCode = require('./webpack.gensrc')
const WebpackI18nPlugin = require("./webpack.i18n");

const date = new Date()
const DEV_MODE = process.env.NODE_ENV !== 'production' && process.argv.indexOf('-p') === -1,
    BUILD_NUMBER = `${date.getYear() - 100}${date.getMonth() + 1}${date.getDate()}.${Math.ceil((date - new Date().setHours(0, 0, 0, 0)) / 8641)}`

/*---------------------------------------------------
 Define which directories are included from the build based on the config file
 ---------------------------------------------------*/

const EXCLUDE_FROM_BUILD = [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, 'test'),
    path.resolve(__dirname, 'server'),
    path.resolve(__dirname, 'build'),
    path.resolve(__dirname, 'extensions'),
    path.resolve(__dirname, 'client/components/ui'),
    path.resolve(__dirname, './api')]

const INCLUDE_IN_BUILD = []

const APP_CONFIG = require('./buildconfig.json')
const PACKAGE_JSON = require('./package.json')

const APP_VALUES = {
    DEV_MODE,
    BUILD_NUMBER,
    APP_NAME: PACKAGE_JSON.name,
    APP_VERSION: PACKAGE_JSON.version,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_DESCRIPTION: PACKAGE_JSON.description,
    APP_COLOR: '#2196f3',
    ...APP_CONFIG.options
}

if (APP_CONFIG.extensions) {
    for (const extensionName in APP_CONFIG.extensions) {
        if (APP_CONFIG.extensions[extensionName].active) {
            INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'extensions/' + extensionName))
        }
    }
}

if (APP_CONFIG.ui) {
    APP_CONFIG.ui.forEach(ui => {
        INCLUDE_IN_BUILD.push(path.resolve(__dirname, 'client/components/ui/impl/' + ui.impl))
    })
}

const excludeFunction = (path) => {

    for (let i = 0; i < EXCLUDE_FROM_BUILD.length; i++) {
        if (path.indexOf(EXCLUDE_FROM_BUILD[i]) === 0) {
            // it belongs to the excluded files

            for (let j = 0; j < INCLUDE_IN_BUILD.length; j++) {
                if (path.indexOf(INCLUDE_IN_BUILD[j]) === 0) {
                    // it is an exception and should be included anyway
                    return false
                }
            }

            return true
        }
    }
    return false
}

const replacePlaceholders = (content, path) => {

    const result = new Function('const {' + Object.keys(APP_VALUES).join(',') + '} = this.APP_VALUES;return `' + content + '`').call({APP_VALUES})
    return result
}

const config = {
    entry: './client/index.js',
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].bundle.js?v=' + BUILD_NUMBER,
        chunkFilename: '[name].bundle.js?v=' + BUILD_NUMBER,
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: excludeFunction,
                loader: 'babel-loader'
            },
            {
                test: /\.global\.css$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.global\.less$/,
                exclude: excludeFunction,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "less-loader"
                ]
            },
            {
                test: /^(?:(?!\.global).)*\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    },
    plugins: [
        new GenSourceCode(APP_VALUES), /* Generate some source code based on the buildconfig.json file */
        new MiniCssExtractPlugin({
            filename: 'style.css',
            allChunks: true
        }), /* Extract css from bundle */
        new WebpackI18nPlugin({
            src: './**/*.tr.json',
            dest: '[name].js'
        })
    ],
    optimization: {
        /*splitChunks: {
         cacheGroups: {
         style: {
         name: 'style',
         test: (c) => {
         if (c.type === 'css/mini-extract') {
         const path = c._identifier
         //console.log(path.substring(path.lastIndexOf('/')+1))
         return true
         }
         return false
         },
         chunks: 'all',
         enforce: true
         }
         }
         },*/
        minimizer: []
    }/*optimization: {
     // We no not want to minimize our code.
     minimize: false
     }*/
}

const CopyWebpackPlugin = require('copy-webpack-plugin')
config.plugins.push(
    new CopyWebpackPlugin([
        {
            from: 'index.html', to: 'index.html',
            transform: replacePlaceholders
        },
        {
            from: 'index.min.html', to: 'index.min.html',
            transform: replacePlaceholders
        },
        {
            from: 'serviceworker.js', to: 'serviceworker.js',
            transform: replacePlaceholders
        },
        {
            from: 'manifest.json', to: 'manifest.json',
            transform: replacePlaceholders
        },
        {from: 'favicon.ico', to: 'favicon.ico'},
        {from: 'favicon.svg', to: 'favicon.svg'},
        {from: 'favicon-192x192.png', to: 'favicon-192x192.png'},
        {from: 'favicon-512x512.png', to: 'favicon-512x512.png'}
    ])
)

/**
 *  Developer / Debug Config
 */
if (DEV_MODE) {
    console.log('Build for developing')
    config.mode = 'development'

    const PORT = (process.env.PORT || 8080)
    const API_PORT = (process.env.API_PORT || 3000)

    config.devServer = {
        contentBase: [path.join(__dirname, ''), path.join(__dirname, 'static')],
        historyApiFallback: true,
        inline: true,
        hot: true,
        stats: 'errors-only',
        port: PORT,
        host: '0.0.0.0',
        proxy: {
            '/graphql': {target: `http://0.0.0.0:${API_PORT}`},
            '/ws': {
                target: `ws://localhost:${API_PORT}`,
                ws: true
            }
        }
    }

    /* For Debugging porpuses */
    config.devtool = 'eval'

    config.plugins.push(new webpack.HotModuleReplacementPlugin())

} else {
    console.log('Build for production')
    config.mode = 'production'

    config.plugins.push(
        new CompressionPlugin({
            minRatio: 0.95
        })
    )

    /*config.optimization.minimizer.push(
        new UglifyJSPlugin({
            uglifyOptions: {
                mangle: { keep_fnames: true },
                compress: {
                    drop_console: true
                },
                output: {
                    comments: false,
                    semicolons: true,
                    shebang: true,
                    beautify: false
                }
            }
        }))*/

    /*const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
     config.plugins.push(new BundleAnalyzerPlugin())*/

    //config.devtool = 'source-map'
}

module.exports = config

/* --port 8080 --hot --host 0.0.0.0 --content-base . */
<|endoftext|>


<commit_before>const { toBeType } = require('jest-tobetype');
const dgram = require('dgram');
const sctp = require('sctp');
const mediasoup = require('../');
const { createWorker } = mediasoup;

expect.extend({ toBeType });

// Set node-sctp default PMTU to 1200.
sctp.defaults({ PMTU: 1200 });

let worker;
let router;
let transport;
let dataProducer;
let dataConsumer;
let udpSocket;
let sctpSocket;
let sctpSendStreamId;
let sctpSendStream;

beforeAll(async () =>
{
	worker = await createWorker();
	router = await worker.createRouter();
	transport = await router.createPlainTransport(
		{
			listenIp       : '0.0.0.0',
			announcedIp    : '127.0.0.1',
			comedia        : true, // So we don't need to call transport.connect().
			enableSctp     : true,
			numSctpStreams : { OS: 256, MIS: 256 }
		});

	// Node UDP socket for SCTP.
	udpSocket = dgram.createSocket({ type: 'udp4' });

	await new Promise((resolve) => udpSocket.bind(0, '127.0.0.1', resolve));

	const remoteUdpIp = transport.tuple.localIp;
	const remoteUdpPort = transport.tuple.localPort;
	const { OS, MIS } = transport.sctpParameters;

	// Use UDP connected socket if Node >= 12.
	if (typeof udpSocket.connect === 'function')
	{
		await new Promise((resolve, reject) =>
		{
			udpSocket.connect(remoteUdpPort, remoteUdpIp, (error) =>
			{
				if (error)
				{
					reject(error);

					return;
				}

				sctpSocket = sctp.connect(
					{
						localPort    : 5000, // Required for SCTP over UDP in mediasoup.
						port         : 5000, // Required for SCTP over UDP in mediasoup.
						OS           : OS,
						MIS          : MIS,
						udpTransport : udpSocket
					});

				resolve();
			});
		});
	}
	// Use UDP disconnected socket if Node < 12.
	else
	{
		sctpSocket = sctp.connect(
			{
				localPort    : 5000, // Required for SCTP over UDP in mediasoup.
				port         : 5000, // Required for SCTP over UDP in mediasoup.
				OS           : OS,
				MIS          : MIS,
				udpTransport : udpSocket,
				udpPeer      :
				{
					address : remoteUdpIp,
					port    : remoteUdpPort
				}
			});
	}

	// Wait for the SCTP association to be open.
	await Promise.race(
		[
			new Promise((resolve) => sctpSocket.on('connect', resolve)),
			new Promise((resolve, reject) => (
				setTimeout(() => reject(new Error('SCTP connection timeout')), 3000)
			))
		]);

	// Create an explicit SCTP outgoing stream with id 123 (id 0 is already used
	// by the implicit SCTP outgoing stream built-in the SCTP socket).
	sctpSendStreamId = 123;
	sctpSendStream = sctpSocket.createStream(sctpSendStreamId);

	// Create a DataProducer with the corresponding SCTP stream id.
	dataProducer = await transport.produceData(
		{
			sctpStreamParameters :
			{
				streamId : sctpSendStreamId,
				ordered  : true
			},
			label    : 'node-sctp',
			protocol : 'foo & bar 😀😀😀'
		});

	// Create a DataConsumer to receive messages from the DataProducer over the
	// same transport.
	dataConsumer = await transport.consumeData({ dataProducerId: dataProducer.id });
});

afterAll(() =>
{
	udpSocket.close();
	sctpSocket.end();
	worker.close();
});

test('ordered DataProducer delivers all SCTP messages to the DataConsumer', async () =>
{
	const onStream = jest.fn();
	const numMessages = 200;
	let sentMessageBytes = 0;
	let recvMessageBytes = 0;
	let lastSentMessageId = 0;
	let lastRecvMessageId = 0;

	// It must be zero because it's the first DataConsumer on the transport.
	expect(dataConsumer.sctpStreamParameters.streamId).toBe(0);

	await new Promise((resolve) =>
	{
		// Send SCTP messages over the sctpSendStream created above.
		const interval = setInterval(() =>
		{
			const id = ++lastSentMessageId;
			const data = Buffer.from(String(id));

			// Set ppid of type WebRTC DataChannel string.
			if (id < numMessages / 2)
			{
				data.ppid = sctp.PPID.WEBRTC_STRING;
			}
			// Set ppid of type WebRTC DataChannel binary.
			else
			{
				data.ppid = sctp.PPID.WEBRTC_BINARY;
			}

			sctpSendStream.write(data);
			sentMessageBytes += data.byteLength;

			if (id === numMessages)
				clearInterval(interval);
		}, 10);

		sctpSocket.on('stream', onStream);

		// Handle the generated SCTP incoming stream and SCTP messages receives on it.
		sctpSocket.on('stream', (stream, streamId) =>
		{
			// It must be zero because it's the first SCTP incoming stream (so first
			// DataConsumer).
			expect(streamId).toBe(0);

			stream.on('data', (data) =>
			{
				recvMessageBytes += data.byteLength;

				const id = Number(data.toString('utf8'));

				if (id === numMessages)
				{
					clearInterval(interval);
					resolve();
				}

				if (id < numMessages / 2)
					expect(data.ppid).toBe(sctp.PPID.WEBRTC_STRING);
				else
					expect(data.ppid).toBe(sctp.PPID.WEBRTC_BINARY);

				expect(id).toBe(++lastRecvMessageId);
			});
		});
	});

	expect(onStream).toHaveBeenCalledTimes(1);
	expect(lastSentMessageId).toBe(numMessages);
	expect(lastRecvMessageId).toBe(numMessages);
	expect(recvMessageBytes).toBe(sentMessageBytes);

	await expect(dataProducer.getStats())
		.resolves
		.toMatchObject(
			[
				{
					type             : 'data-producer',
					label            : dataProducer.label,
					protocol         : dataProducer.protocol,
					messagesReceived : numMessages,
					bytesReceived    : sentMessageBytes
				}
			]);

	await expect(dataConsumer.getStats())
		.resolves
		.toMatchObject(
			[
				{
					type         : 'data-consumer',
					label        : dataConsumer.label,
					protocol     : dataConsumer.protocol,
					messagesSent : numMessages,
					bytesSent    : recvMessageBytes
				}
			]);
}, 10000);
<commit_msg>Fix test-node-sctp connection timeout on Windows (#502)<commit_after>const { toBeType } = require('jest-tobetype');
const dgram = require('dgram');
const sctp = require('sctp');
const mediasoup = require('../');
const { createWorker } = mediasoup;

expect.extend({ toBeType });

// Set node-sctp default PMTU to 1200.
sctp.defaults({ PMTU: 1200 });

let worker;
let router;
let transport;
let dataProducer;
let dataConsumer;
let udpSocket;
let sctpSocket;
let sctpSendStreamId;
let sctpSendStream;

beforeAll(async () =>
{
	worker = await createWorker();
	router = await worker.createRouter();
	transport = await router.createPlainTransport(
		{
			listenIp       : '127.0.0.1', // https://github.com/nodejs/node/issues/14900
			comedia        : true, // So we don't need to call transport.connect().
			enableSctp     : true,
			numSctpStreams : { OS: 256, MIS: 256 }
		});

	// Node UDP socket for SCTP.
	udpSocket = dgram.createSocket({ type: 'udp4' });

	await new Promise((resolve) => udpSocket.bind(0, '127.0.0.1', resolve));

	const remoteUdpIp = transport.tuple.localIp;
	const remoteUdpPort = transport.tuple.localPort;
	const { OS, MIS } = transport.sctpParameters;

	// Use UDP connected socket if Node >= 12.
	if (typeof udpSocket.connect === 'function')
	{
		await new Promise((resolve, reject) =>
		{
			udpSocket.connect(remoteUdpPort, remoteUdpIp, (error) =>
			{
				if (error)
				{
					reject(error);

					return;
				}

				sctpSocket = sctp.connect(
					{
						localPort    : 5000, // Required for SCTP over UDP in mediasoup.
						port         : 5000, // Required for SCTP over UDP in mediasoup.
						OS           : OS,
						MIS          : MIS,
						udpTransport : udpSocket
					});

				resolve();
			});
		});
	}
	// Use UDP disconnected socket if Node < 12.
	else
	{
		sctpSocket = sctp.connect(
			{
				localPort    : 5000, // Required for SCTP over UDP in mediasoup.
				port         : 5000, // Required for SCTP over UDP in mediasoup.
				OS           : OS,
				MIS          : MIS,
				udpTransport : udpSocket,
				udpPeer      :
				{
					address : remoteUdpIp,
					port    : remoteUdpPort
				}
			});
	}

	// Wait for the SCTP association to be open.
	await Promise.race(
		[
			new Promise((resolve) => sctpSocket.on('connect', resolve)),
			new Promise((resolve, reject) => (
				setTimeout(() => reject(new Error('SCTP connection timeout')), 3000)
			))
		]);

	// Create an explicit SCTP outgoing stream with id 123 (id 0 is already used
	// by the implicit SCTP outgoing stream built-in the SCTP socket).
	sctpSendStreamId = 123;
	sctpSendStream = sctpSocket.createStream(sctpSendStreamId);

	// Create a DataProducer with the corresponding SCTP stream id.
	dataProducer = await transport.produceData(
		{
			sctpStreamParameters :
			{
				streamId : sctpSendStreamId,
				ordered  : true
			},
			label    : 'node-sctp',
			protocol : 'foo & bar 😀😀😀'
		});

	// Create a DataConsumer to receive messages from the DataProducer over the
	// same transport.
	dataConsumer = await transport.consumeData({ dataProducerId: dataProducer.id });
});

afterAll(() =>
{
	udpSocket.close();
	sctpSocket.end();
	worker.close();
});

test('ordered DataProducer delivers all SCTP messages to the DataConsumer', async () =>
{
	const onStream = jest.fn();
	const numMessages = 200;
	let sentMessageBytes = 0;
	let recvMessageBytes = 0;
	let lastSentMessageId = 0;
	let lastRecvMessageId = 0;

	// It must be zero because it's the first DataConsumer on the transport.
	expect(dataConsumer.sctpStreamParameters.streamId).toBe(0);

	await new Promise((resolve) =>
	{
		// Send SCTP messages over the sctpSendStream created above.
		const interval = setInterval(() =>
		{
			const id = ++lastSentMessageId;
			const data = Buffer.from(String(id));

			// Set ppid of type WebRTC DataChannel string.
			if (id < numMessages / 2)
			{
				data.ppid = sctp.PPID.WEBRTC_STRING;
			}
			// Set ppid of type WebRTC DataChannel binary.
			else
			{
				data.ppid = sctp.PPID.WEBRTC_BINARY;
			}

			sctpSendStream.write(data);
			sentMessageBytes += data.byteLength;

			if (id === numMessages)
				clearInterval(interval);
		}, 10);

		sctpSocket.on('stream', onStream);

		// Handle the generated SCTP incoming stream and SCTP messages receives on it.
		sctpSocket.on('stream', (stream, streamId) =>
		{
			// It must be zero because it's the first SCTP incoming stream (so first
			// DataConsumer).
			expect(streamId).toBe(0);

			stream.on('data', (data) =>
			{
				recvMessageBytes += data.byteLength;

				const id = Number(data.toString('utf8'));

				if (id === numMessages)
				{
					clearInterval(interval);
					resolve();
				}

				if (id < numMessages / 2)
					expect(data.ppid).toBe(sctp.PPID.WEBRTC_STRING);
				else
					expect(data.ppid).toBe(sctp.PPID.WEBRTC_BINARY);

				expect(id).toBe(++lastRecvMessageId);
			});
		});
	});

	expect(onStream).toHaveBeenCalledTimes(1);
	expect(lastSentMessageId).toBe(numMessages);
	expect(lastRecvMessageId).toBe(numMessages);
	expect(recvMessageBytes).toBe(sentMessageBytes);

	await expect(dataProducer.getStats())
		.resolves
		.toMatchObject(
			[
				{
					type             : 'data-producer',
					label            : dataProducer.label,
					protocol         : dataProducer.protocol,
					messagesReceived : numMessages,
					bytesReceived    : sentMessageBytes
				}
			]);

	await expect(dataConsumer.getStats())
		.resolves
		.toMatchObject(
			[
				{
					type         : 'data-consumer',
					label        : dataConsumer.label,
					protocol     : dataConsumer.protocol,
					messagesSent : numMessages,
					bytesSent    : recvMessageBytes
				}
			]);
}, 10000);
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    'react-hot-loader/patch',
    // activate HMR for React

    'webpack-dev-server/client?http://localhost:3000',
    // bundle the client for webpack-dev-server
    // and connect to the provided endpoint

    'webpack/hot/only-dev-server',
    // bundle the client for hot reloading
    // only- means to only hot reload for successful updates

    './src/index.js',
    // the entry point of our app
  ],

  output: {
    filename: 'bundle.js',
    // the output bundle

    path: path.resolve(__dirname, 'dist'),

    publicPath: '/static/'
    // necessary for HMR to know where to load the hot update chunks
  },

  devtool: 'inline-source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/,
      },
    ],
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // enable HMR globally

    new webpack.NamedModulesPlugin(),
    // prints more readable module names in the browser console on HMR updates

    new webpack.NoEmitOnErrorsPlugin(),
    // do not emit compiled assets that include errors
  ],

  devServer: {
    host: '0.0.0.0',
    port: 3000,

    historyApiFallback: true,
    // respond to 404s with index.html

    hot: true,
    // enable HMR on the server
  },
};
<commit_msg>Output only errors.<commit_after>var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    'react-hot-loader/patch',
    // activate HMR for React

    'webpack-dev-server/client?http://localhost:3000',
    // bundle the client for webpack-dev-server
    // and connect to the provided endpoint

    'webpack/hot/only-dev-server',
    // bundle the client for hot reloading
    // only- means to only hot reload for successful updates

    './src/index.js',
    // the entry point of our app
  ],

  output: {
    filename: 'bundle.js',
    // the output bundle

    path: path.resolve(__dirname, 'dist'),

    publicPath: '/static/'
    // necessary for HMR to know where to load the hot update chunks
  },

  devtool: 'inline-source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/,
      },
    ],
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // enable HMR globally

    new webpack.NamedModulesPlugin(),
    // prints more readable module names in the browser console on HMR updates

    new webpack.NoEmitOnErrorsPlugin(),
    // do not emit compiled assets that include errors
  ],

  devServer: {
    host: '0.0.0.0',
    port: 3000,

    historyApiFallback: true,
    // respond to 404s with index.html

    hot: true,
    // enable HMR on the server

	stats: 'errors-only',
  },
};
<|endoftext|>


<commit_before>const path = require('path');

const reactRule = {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: [ '@babel/preset-env', '@babel/preset-react' ]
        }
    }
};

const cssRule = {
    test: /\.s?css/,
    use: [
        'style-loader',
        'css-loader'
    ]
};

const webpackConfig = {
    entry: path.join(__dirname, 'src', 'index'),
    mode: 'development',
    module: {
        rules: [
            reactRule, cssRule
        ]
    },
    output: {
        path: path.resolve(__dirname, 'lib'),
        filename: 'index.js',
        library: '',
        libraryTarget: 'umd'
    }
};

module.exports = webpackConfig;
<commit_msg>Changes in Webpack config.<commit_after>const path = require('path');

const reactRule = {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: [ '@babel/preset-env', '@babel/preset-react' ]
        }
    }
};

const cssRule = {
    test: /\.s?css/,
    use: [
        'style-loader',
        'css-loader'
    ]
};

const webpackConfig = {
    entry: path.join(__dirname, 'src', 'index.js'),
    mode: 'development',
    module: {
        rules: [
            reactRule, cssRule
        ]
    },
    output: {
        path: path.resolve(__dirname, 'lib'),
        filename: 'index.js',
        libraryTarget: 'umd',
        library: 'ReactReflexGrid',
        umdNamedDefine: true
    }
};

module.exports = webpackConfig;
<|endoftext|>


<commit_before>var merge = require('merge-deep');
var path = require('path');

var common =  {
  // watch: true,
  // watchDelay: 500,
  devtool: 'source-map',

  cache: false,
  entry: {

  },
  output: {
    path: root("dist"),
    filename: "[name].js",
    library: "Reflect",
    libraryTarget: "umd"
  },

  resolve: {
    // ensure loader extensions match
    extensions: ['','.ts','.js','.json']
  },

  module: {
    loaders: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        query: {
          'ignoreDiagnostics': [
            2403, // 2403 -> Subsequent variable declarations
            2300, // 2300 Duplicate identifier
            2374, // 2374 -> Duplicate number index signature
            2375  // 2375 -> Duplicate string index signature
          ]
        },
        exclude: [  /\.(node|worker)\.ts$/, /node_modules/ ]
      }
    ],
  }

};

module.exports = [
  // common,
  merge(common, {
    target: "web",
    entry: {
      "browser": root("./src/global/browser")
    },
    output: {
      libraryTarget: "umd"
    },
    resolve: {
      packageAlias: "browser",
    },
    node: {
      crypto: false,
      console: false,
      process: false,
      global: false,
      buffer: false
    }
  }),
  merge(common, {
    target: "node",
    entry: {
      "node": root("./src/global/node"),
    },
    output: {
      libraryTarget: "commonjs"
    },
    resolve: {
      packageAlias: "server",
    }
  })
  // ,merge(common, {
  //   target: "webworker",
  //   entry: {
  //     "worker": root("./src/global/worker"),
  //   },
  //   output: {
  //     libraryTarget: "umd"
  //   },
  //   resolve: {
  //     packageAlias: "worker",
  //   }
  // })

]

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
<commit_msg>chore(webpack.config): remove ts ignores<commit_after>var merge = require('merge-deep');
var path = require('path');

var common =  {
  // watch: true,
  // watchDelay: 500,
  devtool: 'source-map',

  cache: false,
  entry: {

  },
  output: {
    path: root("dist"),
    filename: "[name].js",
    library: "Reflect",
    libraryTarget: "umd"
  },

  resolve: {
    // ensure loader extensions match
    extensions: ['','.ts','.js','.json']
  },

  module: {
    loaders: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        exclude: [  /\.(node|worker)\.ts$/, /node_modules/ ]
      }
    ],
  }

};

module.exports = [
  // common,
  merge(common, {
    target: "web",
    entry: {
      "browser": root("./src/global/browser")
    },
    output: {
      libraryTarget: "umd"
    },
    resolve: {
      packageAlias: "browser",
    },
    node: {
      crypto: false,
      console: false,
      process: false,
      global: false,
      buffer: false
    }
  }),
  merge(common, {
    target: "node",
    entry: {
      "node": root("./src/global/node"),
    },
    output: {
      libraryTarget: "commonjs"
    },
    resolve: {
      packageAlias: "server",
    }
  })
  // ,merge(common, {
  //   target: "webworker",
  //   entry: {
  //     "worker": root("./src/global/worker"),
  //   },
  //   output: {
  //     libraryTarget: "umd"
  //   },
  //   resolve: {
  //     packageAlias: "worker",
  //   }
  // })

]

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
<|endoftext|>


<commit_before>/*
 * ***** BEGIN LICENSE BLOCK *****
 * OpenPGP Zimbra Secure is the open source digital signature and encrypt for Zimbra Collaboration Open Source Edition software
 * Copyright (C) 2016-present OpenPGP Zimbra Secure

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 * ***** END LICENSE BLOCK *****
 *
 * OpenPGP MIME Secure Email Zimlet
 *
 * Written by nguyennv1981@gmail.com
 */

OpenPGPUtils = function() {};

OpenPGPUtils.BASE64_TABLE_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
OpenPGPUtils.BASE64_TABLE = OpenPGPUtils.BASE64_TABLE_STRING.split("");

OpenPGPUtils.SIGNED_MESSAGE_CONTENT_TYPE = 'multipart/signed';
OpenPGPUtils.ENCRYPTED_MESSAGE_CONTENT_TYPE = 'multipart/encrypted';

OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE = 'application/pgp-signature';
OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE = 'application/pgp-encrypted';
OpenPGPUtils.OPENPGP_KEYS_CONTENT_TYPE = 'application/pgp-keys';

OpenPGPUtils.OPENPGP_CONTENT_TYPES = [
    OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE,
    OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE,
    OpenPGPUtils.OPENPGP_KEYS_CONTENT_TYPE
];

OpenPGPUtils.isSignedMessage = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.SIGNED_MESSAGE_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.isEncryptedMessage = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.ENCRYPTED_MESSAGE_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.hasSignatureContentType = function(msg) {
    return msg.hasContentType(OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE);
};

OpenPGPUtils.hasEncryptedContentType = function(msg) {
    return msg.hasContentType(OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE);
};

OpenPGPUtils.hasOPENPGPContentType = function(msg) {
    var has = false;
    OpenPGPUtils.OPENPGP_CONTENT_TYPES.forEach(function(ct) {
        has = msg.hasContentType(ct);
        if (has) {
            return;
        }
    });
    return has;
};

OpenPGPUtils.isOPENPGPContentType = function(cType) {
    return AjxUtil.indexOf(OpenPGPUtils.OPENPGP_CONTENT_TYPES, cType) !== -1;
};

OpenPGPUtils.isSignatureContentType = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.isEncryptedContentType = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.localStorageSave = function(key, pwd, data) {
    var opts = {
        data: data,
        passwords: [pwd]
    };
    return openpgp.encrypt(opts).then(function(encrypted) {
        localStorage[key] = encrypted.data;
        return encrypted.data;
    });
}

OpenPGPUtils.localStorageRead = function(key, pwd) {
    var sequence = Promise.resolve();
    return sequence.then(function() {
        if (localStorage[key]) {
            var encrypted = localStorage[key];
            var opts = {
                message: openpgp.message.readArmored(encrypted),
                password: pwd
            };
            return openpgp.decrypt(opts).then(function(plaintext) {
                return plaintext.data;
            });
        }
        else {
            return false;
        }
    });
}

OpenPGPUtils.base64Encode = function(bin) {
    if (!window.btoa) {
        for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
          var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
          if ((a | b | c) > 255) throw new Error("String contains an invalid character");
          base64[base64.length] = OpenPGPUtils.BASE64_TABLE[a >> 2] + OpenPGPUtils.BASE64_TABLE[((a << 4) & 63) | (b >> 4)] +
                                  (isNaN(b) ? "=" : OpenPGPUtils.BASE64_TABLE[((b << 2) & 63) | (c >> 6)]) +
                                  (isNaN(b + c) ? "=" : OpenPGPUtils.BASE64_TABLE[c & 63]);
        }
        return base64.join("");
    }
    else {
        return window.btoa(bin);
    }
};

OpenPGPUtils.base64Decode = function(base64) {
    if (!window.atob) {
        if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character");
        base64 = base64.replace(/=/g, "");
        var n = base64.length & 3;
        if (n === 1) throw new Error("String contains an invalid character");
        for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) {
            var a = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A"), b = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A");
            var c = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A"), d = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A");
            if ((a | b | c | d) < 0) throw new Error("String contains an invalid character");
            bin[bin.length] = ((a << 2) | (b >> 4)) & 255;
            bin[bin.length] = ((b << 4) | (c >> 2)) & 255;
            bin[bin.length] = ((c << 6) | d) & 255;
        };
        return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4);
    }
    else {
        return window.atob(base64);
    }
};

OpenPGPUtils.hexToBase64 = function(hex) {
    return OpenPGPUtils.base64Encode(String.fromCharCode.apply(null,
        hex.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
    );
};

OpenPGPUtils.hexToBin = function(hex) {
    var bytes = [];

    for(var i = 0; i < hex.length - 1; i += 2) {
        bytes.push(parseInt(hex.substr(i, 2), 16));
    }
    return String.fromCharCode.apply(String, bytes);;
};

OpenPGPUtils.fetchPart = function(part, baseUrl) {
    var url, cType, cDisposition, iType;
    var addTimestamp = true;

    if (part.id) {
        url = [baseUrl, '&id=', part.id].join('');
    } else if (part.mid && part.part) {
        url = [baseUrl, '&id=', part.mid, '&part=', part.part].join('');
    } else if (part.path) {
        url = [baseUrl.replace(/\?.*/,''), part.path].join('');
        addTimestamp = false;
    } else {
        OpenPGPZimbraSecure.popupErrorDialog('attach-convert-error');
    }

    if (url) {
        var rpcReq = new AjxRpcRequest();

        if (addTimestamp) {
            //add a timestamp param so that browser will not cache the request
            url += "&timestamp=" + new Date().getTime();
        }
        var response = rpcReq.invoke('', url,
                                     { 'X-Zimbra-Encoding': 'x-base64' },
                                     null, true);
        cType = rpcReq.__httpReq.getResponseHeader('Content-Type');
        cDisposition = rpcReq.__httpReq.getResponseHeader('Content-Disposition');

        iType = rpcReq.__httpReq.getResponseHeader('X-Zimbra-ItemType');
        if (iType == 'message') {
            //this is a attached message
            cDisposition = 'attachment';
            //now set the file name for this attachment.
            var m =  appCtxt.cacheGet(part.id); //get the attached message from cache
            if (m && m.subject) {
                cDisposition = 'attachment; filename="' + m.subject + '"';
            }
        }
        if (iType == 'document' && !cDisposition) {
            var iName = rpcReq.__httpReq.getResponseHeader('X-Zimbra-ItemName');
            if (iName) {
                cDisposition = 'attachment; filename="' + iName + '"';
            }
        }

        if (response.success) {
            return { data: response.text, ct: cType, cd: cDisposition};
        }
    }
};

OpenPGPUtils.visitMessage = function(message, callback) {
    callback(message);
    if (Array.isArray(message._body)) {
        message._body.forEach(function(entity) {
            OpenPGPUtils.visitMessage(entity, callback);
        });
    }
};

OpenPGPUtils.mimeMessageToZmMimePart = function(message, withAttachment) {
    var deep = 0;
    var partIndexes = [];
    withAttachment = withAttachment | false;

    function buildZmMimePart(message) {
        deep++;
        var cd = message.header('Content-Disposition');
        if (!withAttachment && cd === 'attachment') {
            deep--;
            return false;
        }

        var part = {};
        var cType = message.contentType();
        part.ct = cType.fulltype;
        if (partIndexes.length == 0) {
            part.part = 'TEXT';
        }
        else {
            part.part = partIndexes.join('.');
        }
        if (typeof message._body === 'string') {
            var content = '';
            var encode = message.header('Content-Transfer-Encoding');
            if (encode === 'quoted-printable') {
                content = utf8.decode(quotedPrintable.decode(message._body));
            }
            else {
                content = message._body;
            }
            if (part.ct == 'text/html' || part.ct == 'text/plain') {
                part.content = content;
            }
            if (encode === 'base64') {
                part.s = OpenPGPUtils.base64Decode(message._body).length;
            }
            else {
                part.s = content.length;
            }
        }
        if (cType.params.name) {
            part.filename = cType.params.name;
        }
        if (cd) {
            part.cd = cd;
        }
        if (Array.isArray(message._body)) {
            part.mp = [];
            message._body.forEach(function(entity, index) {
                partIndexes[deep - 1] = index + 1;
                var mp = visitMessage(entity);
                if (mp) {
                    part.mp.push(mp);
                }
            });
        }
        deep--;
        partIndexes.pop();
        return part;
    }

    function findBody(cType, part) {
        var bodyFound = false;
        if (part.mp) {
            bodyFound = findBody(cType, part.mp);
        } else if (part.ct) {
            if (part.ct == cType) {
                part.body = bodyFound = true;
            } else if (part.cd == 'inline') {
                part.body = true;
            }
        } else {
            for (var i = 0; !bodyFound && i < part.length; i++) {
                bodyFound = findBody(cType, part[i]);
            }
        }
        return bodyFound;
    }

    var mimePart = buildZmMimePart(message);
    if (!findBody('text/html', mimePart))
        findBody('text/plain', mimePart);

    return mimePart;
};

OpenPGPUtils.getDefaultSenderAddress = function() {
    var account = (appCtxt.accountList.defaultAccount ||
                   appCtxt.accountList.activeAccount ||
                   appCtxt.accountList.mainAccount);
    var identity = appCtxt.getIdentityCollection(account).defaultIdentity;

    return new AjxEmailAddress(identity.sendFromAddress, AjxEmailAddress.FROM, identity.sendFromDisplay);
};

OpenPGPUtils.prop = function(key) {
    return openpgp_zimbra_secure[key];
};

/*
 * random-string
 * https://github.com/valiton/node-random-string
 *
 * Copyright (c) 2013 Valiton GmbH, Bastian 'hereandnow' Behrens
 * Licensed under the MIT license.
 */
OpenPGPUtils.randomString = function(opts) {
    var numbers = '0123456789',
        letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
        specials = '!$%^&*()_+|~-=`{}[]:;<>?,./';

    function _defaults(opts) {
        opts || (opts = {});
        return {
            length: opts.length || 32,
            numeric: typeof opts.numeric === 'boolean' ? opts.numeric : true,
            letters: typeof opts.letters === 'boolean' ? opts.letters : true,
            special: typeof opts.special === 'boolean' ? opts.special : false
        };
    }

    function _buildChars(opts) {
        var chars = '';
        if (opts.numeric) { chars += numbers; }
        if (opts.letters) { chars += letters; }
        if (opts.special) { chars += specials; }
        return chars;
    }

    opts = _defaults(opts);
    var i, rn,
        rnd = '',
        len = opts.length,
        randomChars = _buildChars(opts);
    for (i = 1; i <= len; i++) {
        rnd += randomChars.substring(rn = Math.floor(Math.random() * randomChars.length), rn + 1);
    }
    return rnd;
};
<commit_msg>Fix typo<commit_after>/*
 * ***** BEGIN LICENSE BLOCK *****
 * OpenPGP Zimbra Secure is the open source digital signature and encrypt for Zimbra Collaboration Open Source Edition software
 * Copyright (C) 2016-present OpenPGP Zimbra Secure

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 * ***** END LICENSE BLOCK *****
 *
 * OpenPGP MIME Secure Email Zimlet
 *
 * Written by nguyennv1981@gmail.com
 */

OpenPGPUtils = function() {};

OpenPGPUtils.BASE64_TABLE_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
OpenPGPUtils.BASE64_TABLE = OpenPGPUtils.BASE64_TABLE_STRING.split("");

OpenPGPUtils.SIGNED_MESSAGE_CONTENT_TYPE = 'multipart/signed';
OpenPGPUtils.ENCRYPTED_MESSAGE_CONTENT_TYPE = 'multipart/encrypted';

OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE = 'application/pgp-signature';
OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE = 'application/pgp-encrypted';
OpenPGPUtils.OPENPGP_KEYS_CONTENT_TYPE = 'application/pgp-keys';

OpenPGPUtils.OPENPGP_CONTENT_TYPES = [
    OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE,
    OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE,
    OpenPGPUtils.OPENPGP_KEYS_CONTENT_TYPE
];

OpenPGPUtils.isSignedMessage = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.SIGNED_MESSAGE_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.isEncryptedMessage = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.ENCRYPTED_MESSAGE_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.hasSignatureContentType = function(msg) {
    return msg.hasContentType(OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE);
};

OpenPGPUtils.hasEncryptedContentType = function(msg) {
    return msg.hasContentType(OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE);
};

OpenPGPUtils.hasOPENPGPContentType = function(msg) {
    var has = false;
    OpenPGPUtils.OPENPGP_CONTENT_TYPES.forEach(function(ct) {
        has = msg.hasContentType(ct);
        if (has) {
            return;
        }
    });
    return has;
};

OpenPGPUtils.isOPENPGPContentType = function(cType) {
    return AjxUtil.indexOf(OpenPGPUtils.OPENPGP_CONTENT_TYPES, cType) !== -1;
};

OpenPGPUtils.isSignatureContentType = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.OPENPGP_SIGNATURE_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.isEncryptedContentType = function(cType) {
    return AjxUtil.indexOf([OpenPGPUtils.OPENPGP_ENCRYPTED_CONTENT_TYPE], cType) !== -1;
};

OpenPGPUtils.localStorageSave = function(key, pwd, data) {
    var opts = {
        data: data,
        passwords: [pwd]
    };
    return openpgp.encrypt(opts).then(function(encrypted) {
        localStorage[key] = encrypted.data;
        return encrypted.data;
    });
}

OpenPGPUtils.localStorageRead = function(key, pwd) {
    var sequence = Promise.resolve();
    return sequence.then(function() {
        if (localStorage[key]) {
            var encrypted = localStorage[key];
            var opts = {
                message: openpgp.message.readArmored(encrypted),
                password: pwd
            };
            return openpgp.decrypt(opts).then(function(plaintext) {
                return plaintext.data;
            });
        }
        else {
            return false;
        }
    });
}

OpenPGPUtils.base64Encode = function(bin) {
    if (!window.btoa) {
        for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
          var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
          if ((a | b | c) > 255) throw new Error("String contains an invalid character");
          base64[base64.length] = OpenPGPUtils.BASE64_TABLE[a >> 2] + OpenPGPUtils.BASE64_TABLE[((a << 4) & 63) | (b >> 4)] +
                                  (isNaN(b) ? "=" : OpenPGPUtils.BASE64_TABLE[((b << 2) & 63) | (c >> 6)]) +
                                  (isNaN(b + c) ? "=" : OpenPGPUtils.BASE64_TABLE[c & 63]);
        }
        return base64.join("");
    }
    else {
        return window.btoa(bin);
    }
};

OpenPGPUtils.base64Decode = function(base64) {
    if (!window.atob) {
        if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character");
        base64 = base64.replace(/=/g, "");
        var n = base64.length & 3;
        if (n === 1) throw new Error("String contains an invalid character");
        for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) {
            var a = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A"), b = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A");
            var c = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A"), d = OpenPGPUtils.BASE64_TABLE_STRING.indexOf(base64[j++] || "A");
            if ((a | b | c | d) < 0) throw new Error("String contains an invalid character");
            bin[bin.length] = ((a << 2) | (b >> 4)) & 255;
            bin[bin.length] = ((b << 4) | (c >> 2)) & 255;
            bin[bin.length] = ((c << 6) | d) & 255;
        };
        return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4);
    }
    else {
        return window.atob(base64);
    }
};

OpenPGPUtils.hexToBase64 = function(hex) {
    return OpenPGPUtils.base64Encode(String.fromCharCode.apply(null,
        hex.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
    );
};

OpenPGPUtils.hexToBin = function(hex) {
    var bytes = [];

    for(var i = 0; i < hex.length - 1; i += 2) {
        bytes.push(parseInt(hex.substr(i, 2), 16));
    }
    return String.fromCharCode.apply(String, bytes);;
};

OpenPGPUtils.fetchPart = function(part, baseUrl) {
    var url, cType, cDisposition, iType;
    var addTimestamp = true;

    if (part.id) {
        url = [baseUrl, '&id=', part.id].join('');
    } else if (part.mid && part.part) {
        url = [baseUrl, '&id=', part.mid, '&part=', part.part].join('');
    } else if (part.path) {
        url = [baseUrl.replace(/\?.*/,''), part.path].join('');
        addTimestamp = false;
    } else {
        OpenPGPZimbraSecure.popupErrorDialog('attach-convert-error');
    }

    if (url) {
        var rpcReq = new AjxRpcRequest();

        if (addTimestamp) {
            //add a timestamp param so that browser will not cache the request
            url += "&timestamp=" + new Date().getTime();
        }
        var response = rpcReq.invoke('', url,
                                     { 'X-Zimbra-Encoding': 'x-base64' },
                                     null, true);
        cType = rpcReq.__httpReq.getResponseHeader('Content-Type');
        cDisposition = rpcReq.__httpReq.getResponseHeader('Content-Disposition');

        iType = rpcReq.__httpReq.getResponseHeader('X-Zimbra-ItemType');
        if (iType == 'message') {
            //this is a attached message
            cDisposition = 'attachment';
            //now set the file name for this attachment.
            var m =  appCtxt.cacheGet(part.id); //get the attached message from cache
            if (m && m.subject) {
                cDisposition = 'attachment; filename="' + m.subject + '"';
            }
        }
        if (iType == 'document' && !cDisposition) {
            var iName = rpcReq.__httpReq.getResponseHeader('X-Zimbra-ItemName');
            if (iName) {
                cDisposition = 'attachment; filename="' + iName + '"';
            }
        }

        if (response.success) {
            return { data: response.text, ct: cType, cd: cDisposition};
        }
    }
};

OpenPGPUtils.visitMessage = function(message, callback) {
    callback(message);
    if (Array.isArray(message._body)) {
        message._body.forEach(function(entity) {
            OpenPGPUtils.visitMessage(entity, callback);
        });
    }
};

OpenPGPUtils.mimeMessageToZmMimePart = function(message, withAttachment) {
    var deep = 0;
    var partIndexes = [];
    withAttachment = withAttachment | false;

    function buildZmMimePart(message) {
        deep++;
        var cd = message.header('Content-Disposition');
        if (!withAttachment && cd === 'attachment') {
            deep--;
            return false;
        }

        var part = {};
        var cType = message.contentType();
        part.ct = cType.fulltype;
        if (partIndexes.length == 0) {
            part.part = 'TEXT';
        }
        else {
            part.part = partIndexes.join('.');
        }
        if (typeof message._body === 'string') {
            var content = '';
            var encode = message.header('Content-Transfer-Encoding');
            if (encode === 'quoted-printable') {
                content = utf8.decode(quotedPrintable.decode(message._body));
            }
            else {
                content = message._body;
            }
            if (part.ct == 'text/html' || part.ct == 'text/plain') {
                part.content = content;
            }
            if (encode === 'base64') {
                part.s = OpenPGPUtils.base64Decode(message._body).length;
            }
            else {
                part.s = content.length;
            }
        }
        if (cType.params.name) {
            part.filename = cType.params.name;
        }
        if (cd) {
            part.cd = cd;
        }
        if (Array.isArray(message._body)) {
            part.mp = [];
            message._body.forEach(function(entity, index) {
                partIndexes[deep - 1] = index + 1;
                var mp = buildZmMimePart(entity);
                if (mp) {
                    part.mp.push(mp);
                }
            });
        }
        deep--;
        partIndexes.pop();
        return part;
    }

    function findBody(cType, part) {
        var bodyFound = false;
        if (part.mp) {
            bodyFound = findBody(cType, part.mp);
        } else if (part.ct) {
            if (part.ct == cType) {
                part.body = bodyFound = true;
            } else if (part.cd == 'inline') {
                part.body = true;
            }
        } else {
            for (var i = 0; !bodyFound && i < part.length; i++) {
                bodyFound = findBody(cType, part[i]);
            }
        }
        return bodyFound;
    }

    var mimePart = buildZmMimePart(message);
    if (!findBody('text/html', mimePart))
        findBody('text/plain', mimePart);

    return mimePart;
};

OpenPGPUtils.getDefaultSenderAddress = function() {
    var account = (appCtxt.accountList.defaultAccount ||
                   appCtxt.accountList.activeAccount ||
                   appCtxt.accountList.mainAccount);
    var identity = appCtxt.getIdentityCollection(account).defaultIdentity;

    return new AjxEmailAddress(identity.sendFromAddress, AjxEmailAddress.FROM, identity.sendFromDisplay);
};

OpenPGPUtils.prop = function(key) {
    return openpgp_zimbra_secure[key];
};

/*
 * random-string
 * https://github.com/valiton/node-random-string
 *
 * Copyright (c) 2013 Valiton GmbH, Bastian 'hereandnow' Behrens
 * Licensed under the MIT license.
 */
OpenPGPUtils.randomString = function(opts) {
    var numbers = '0123456789',
        letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
        specials = '!$%^&*()_+|~-=`{}[]:;<>?,./';

    function _defaults(opts) {
        opts || (opts = {});
        return {
            length: opts.length || 32,
            numeric: typeof opts.numeric === 'boolean' ? opts.numeric : true,
            letters: typeof opts.letters === 'boolean' ? opts.letters : true,
            special: typeof opts.special === 'boolean' ? opts.special : false
        };
    }

    function _buildChars(opts) {
        var chars = '';
        if (opts.numeric) { chars += numbers; }
        if (opts.letters) { chars += letters; }
        if (opts.special) { chars += specials; }
        return chars;
    }

    opts = _defaults(opts);
    var i, rn,
        rnd = '',
        len = opts.length,
        randomChars = _buildChars(opts);
    for (i = 1; i <= len; i++) {
        rnd += randomChars.substring(rn = Math.floor(Math.random() * randomChars.length), rn + 1);
    }
    return rnd;
};
<|endoftext|>


<commit_before>let webpack = require('webpack');
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
const { CheckerPlugin } = require('awesome-typescript-loader');

const DIST_PATH = path.resolve(__dirname, 'dist');
const dev_mode = process.env.NODE_ENV !== 'production';
/**
 * Entry
 */
let entry = {
  app: ['./src/index.tsx'],
}

/**
 * Output
 */
let output = {
  path: DIST_PATH,
  filename: 'app.min.js',
  sourceMapFilename: 'app_map.min.js.map'
}

let ts_rule = {
  test: /\.(ts|tsx)?$/,
  use: ['awesome-typescript-loader'],
  exclude: /node_modules/,
};

let plugins = [
  new CheckerPlugin(),
  new HtmlWebpackPlugin({
    filename: 'index.min.html',
    template: 'src/index.html'
  })
];

let devtool = 'hidden-source-map';

/**
 *Deal with dev_mode
 */
if (dev_mode) {
  entry.app.push(...[
    'webpack-hot-middleware/client?reload=true',
  ]);

  ts_rule.use.splice(0, 0, 'react-hot-loader');

  plugins.push(...[
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
  ]);

  devtool = 'cheap-eval-source-map';
}

/**
 * Assemble the config
 */
let webpack_config = {
  entry,
  output,
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(ts|tsx)?$/,
        use: "source-map-loader",
        exclude: /node_modules/,
      },
      ts_rule,
    ]
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  devtool,
  context: __dirname,
  plugins,
};

module.exports = webpack_config;
<commit_msg>Use eval source map for typescript.<commit_after>let webpack = require('webpack');
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
const { CheckerPlugin } = require('awesome-typescript-loader');

const DIST_PATH = path.resolve(__dirname, 'dist');
const dev_mode = process.env.NODE_ENV !== 'production';
/**
 * Entry
 */
let entry = {
  app: ['./src/index.tsx'],
}

/**
 * Output
 */
let output = {
  path: DIST_PATH,
  filename: 'app.min.js',
  sourceMapFilename: 'app_map.min.js.map'
}

let ts_rule = {
  test: /\.(ts|tsx)?$/,
  use: ['awesome-typescript-loader'],
  exclude: /node_modules/,
};

let plugins = [
  new CheckerPlugin(),
  new HtmlWebpackPlugin({
    filename: 'index.min.html',
    template: 'src/index.html'
  })
];

let devtool = 'hidden-source-map';

/**
 *Deal with dev_mode
 */
if (dev_mode) {
  entry.app.push(...[
    'webpack-hot-middleware/client?reload=true',
  ]);

  ts_rule.use.splice(0, 0, 'react-hot-loader');

  plugins.push(...[
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
  ]);

  devtool = 'eval-source-map';
}

/**
 * Assemble the config
 */
let webpack_config = {
  entry,
  output,
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(ts|tsx)?$/,
        use: "source-map-loader",
        exclude: /node_modules/,
      },
      ts_rule,
    ]
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  devtool,
  context: __dirname,
  plugins,
};

module.exports = webpack_config;
<|endoftext|>


<commit_before>var webpack = require("webpack");
var path = require('path');

module.exports =  {
   module: {
      loaders: [
         {
            test: /\.js$/,
            include: path.join(__dirname, 'source/js'),
            loaders: ['babel-loader']
         }
      ]
   },
   plugins: [
      new webpack.ProvidePlugin({
         $: 'jquery',
         jQuery: 'jquery',
         'window.jQuery': 'jquery',
         Popper: ['popper.js', 'default'],
         Util: 'exports-loader?Util!bootstrap/js/dist/util',
         Dropdown: 'exports-loader?Dropdown!bootstrap/js/dist/dropdown',
         Collapse: 'exports-loader?Collapse!bootstrap/js/dist/colapse',
         Carousel: 'exports-loader?Carousel!bootstrap/js/dist/carousel',
      }),
      new webpack.optimize.UglifyJsPlugin()
   ],
   entry: {
      app: ["./source/js/app"]
   },
   output: {
      path: path.join(__dirname, "/static/js"),
      publicPath: "/",
      filename: "[name].js"
   }
};
<commit_msg>Se agrega el plugin de Tab en webpack<commit_after>var webpack = require("webpack");
var path = require('path');

module.exports =  {
   module: {
      loaders: [
         {
            test: /\.js$/,
            include: path.join(__dirname, 'source/js'),
            loaders: ['babel-loader']
         }
      ]
   },
   plugins: [
      new webpack.ProvidePlugin({
         $: 'jquery',
         jQuery: 'jquery',
         'window.jQuery': 'jquery',
         Popper: ['popper.js', 'default'],
         Util: 'exports-loader?Util!bootstrap/js/dist/util',
         Dropdown: 'exports-loader?Dropdown!bootstrap/js/dist/dropdown',
         Collapse: 'exports-loader?Collapse!bootstrap/js/dist/collapse',
         Carousel: 'exports-loader?Carousel!bootstrap/js/dist/carousel',
         Tab: 'exports-loader?Carousel!bootstrap/js/dist/tab'
      }),
      new webpack.optimize.UglifyJsPlugin()
   ],
   entry: {
      app: ["./source/js/app"]
   },
   output: {
      path: path.join(__dirname, "/static/js"),
      publicPath: "/",
      filename: "[name].js"
   }
};
<|endoftext|>