<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const webpack = require("webpack");

let og_image_url = process.env.RIOT_OG_IMAGE_URL;
if (!og_image_url) og_image_url = 'https://app.element.io/themes/element/img/logos/opengraph.png';

module.exports = (env, argv) => {
    if (process.env.CI_PACKAGE) {
        // Don't run minification for CI builds (this is only set for runs on develop)
        argv.mode = "development";
    }

    const development = {};
    if (argv.mode !== "production") {
        // This makes the sourcemaps human readable for developers. We use eval-source-map
        // because the plain source-map devtool ruins the alignment.
        development['devtool'] = 'eval-source-map';
    } else {
        development['devtool'] = 'nosources-source-map';
    }

    // Resolve the directories for the react-sdk and js-sdk for later use. We resolve these early so we
    // don't have to call them over and over. We also resolve to the package.json instead of the src
    // directory so we don't have to rely on a index.js or similar file existing.
    const reactSdkSrcDir = path.resolve(require.resolve("matrix-react-sdk/package.json"), '..', 'src');
    const jsSdkSrcDir = path.resolve(require.resolve("matrix-js-sdk/package.json"), '..', 'src');

    return {
        ...development,

        entry: {
            "bundle": "./src/vector/index.ts",
            "indexeddb-worker": "./src/vector/indexeddb-worker.js",
            "mobileguide": "./src/vector/mobile_guide/index.js",
            "jitsi": "./src/vector/jitsi/index.ts",
            "usercontent": "./node_modules/matrix-react-sdk/src/usercontent/index.js",

            // CSS themes
            "theme-element": "./node_modules/matrix-react-sdk/res/themes/element/css/element.scss",
            "theme-element-dark": "./node_modules/matrix-react-sdk/res/themes/element-dark/css/element-dark.scss",
            "theme-light": "./node_modules/matrix-react-sdk/res/themes/light/css/light.scss",
            "theme-dark": "./node_modules/matrix-react-sdk/res/themes/dark/css/dark.scss",
            "theme-light-custom": "./node_modules/matrix-react-sdk/res/themes/light-custom/css/light-custom.scss",
            "theme-dark-custom": "./node_modules/matrix-react-sdk/res/themes/dark-custom/css/dark-custom.scss",
        },

        optimization: {
            // Put all of our CSS into one useful place - this is needed for MiniCssExtractPlugin.
            // Previously we used a different extraction plugin that did this magic for us, but
            // now we need to consider that the CSS needs to be bundled up together.
            splitChunks: {
                cacheGroups: {
                    styles: {
                        name: 'styles',
                        test: /\.css$/,
                        enforce: true,
                        // Do not add `chunks: 'all'` here because you'll break the app entry point.
                    },
                    default: {
                        reuseExistingChunk: true,
                    },
                },
            },

            // This fixes duplicate files showing up in chrome with sourcemaps enabled.
            // See https://github.com/webpack/webpack/issues/7128 for more info.
            namedModules: false,

            // Minification is normally enabled by default for webpack in production mode, but
            // we use a CSS optimizer too and need to manage it ourselves.
            minimize: argv.mode === 'production',
            minimizer: argv.mode === 'production' ? [new TerserPlugin({}), new OptimizeCSSAssetsPlugin({})] : [],
        },

        resolve: {
            // We define an alternative import path so we can safely use src/ across the react-sdk
            // and js-sdk. We already import from src/ where possible to ensure our source maps are
            // extremely accurate (and because we're capable of compiling the layers manually rather
            // than relying on partially-mangled output from babel), though we do need to fix the
            // package level import (stuff like `import {Thing} from "matrix-js-sdk"` for example).
            // We can't use the aliasing down below to point at src/ because that'll fail to resolve
            // the package.json for the dependency. Instead, we rely on the package.json of each
            // layer to have our custom alternate fields to load things in the right order. These are
            // the defaults of webpack prepended with `matrix_src_`.
            mainFields: ['matrix_src_browser', 'matrix_src_main', 'browser', 'main'],
            aliasFields: ['matrix_src_browser', 'browser'],

            // We need to specify that TS can be resolved without an extension
            extensions: ['.js', '.json', '.ts', '.tsx'],
            alias: {
                // alias any requires to the react module to the one in our path,
                // otherwise we tend to get the react source included twice when
                // using `npm link` / `yarn link`.
                "react": path.resolve(__dirname, 'node_modules/react'),
                "react-dom": path.resolve(__dirname, 'node_modules/react-dom'),

                // same goes for js-sdk - we don't need two copies.
                "matrix-js-sdk": path.resolve(__dirname, 'node_modules/matrix-js-sdk'),
                // and prop-types and sanitize-html
                "prop-types": path.resolve(__dirname, 'node_modules/prop-types'),
                "sanitize-html": path.resolve(__dirname, 'node_modules/sanitize-html'),

                // Define a variable so the i18n stuff can load
                "$webapp": path.resolve(__dirname, 'webapp'),
            },
        },

        module: {
            noParse: [
                // for cross platform compatibility use [\\\/] as the path separator
                // this ensures that the regex trips on both Windows and *nix

                // don't parse the languages within highlight.js. They cause stack
                // overflows (https://github.com/webpack/webpack/issues/1721), and
                // there is no need for webpack to parse them - they can just be
                // included as-is.
                /highlight\.js[\\\/]lib[\\\/]languages/,

                // olm takes ages for webpack to process, and it's already heavily
                // optimised, so there is little to gain by us uglifying it.
                /olm[\\\/](javascript[\\\/])?olm\.js$/,
            ],
            rules: [
                {
                    test: /\.(ts|js)x?$/,
                    include: (f) => {
                        // our own source needs babel-ing
                        if (f.startsWith(path.resolve(__dirname, 'src'))) return true;

                        // we use the original source files of react-sdk and js-sdk, so we need to
                        // run them through babel. Because the path tested is the resolved, absolute
                        // path, these could be anywhere thanks to yarn link. We must also not
                        // include node modules inside these modules, so we add 'src'.
                        if (f.startsWith(reactSdkSrcDir)) return true;
                        if (f.startsWith(jsSdkSrcDir)) return true;

                        // but we can't run all of our dependencies through babel (many of them still
                        // use module.exports which breaks if babel injects an 'include' for its
                        // polyfills: probably fixable but babeling all our dependencies is probably
                        // not necessary anyway). So, for anything else, don't babel.
                        return false;
                    },
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true
                    }
                },
                {
                    test: /\.css$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 1,
                                sourceMap: true,
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            ident: 'postcss',
                            options: {
                                sourceMap: true,
                                plugins: () => [
                                    // Note that we use significantly fewer plugins on the plain
                                    // CSS parser. If we start to parse plain CSS, we end with all
                                    // kinds of nasty problems (like stylesheets not loading).
                                    //
                                    // You might have noticed that we're also sending regular CSS
                                    // through PostCSS. This looks weird, and in fact is probably
                                    // not what you'd expect, however in order for our CSS build
                                    // to work nicely we have to do this. Because down the line
                                    // our SCSS stylesheets reference plain CSS we have to load
                                    // the plain CSS through PostCSS so it can find it safely. This
                                    // also acts like a babel-for-css by transpiling our (S)CSS
                                    // down/up to the right browser support (prefixes, etc).
                                    // Further, if we don't do this then PostCSS assumes that our
                                    // plain CSS is SCSS and it really doesn't like that, even
                                    // though plain CSS should be compatible. The chunking options
                                    // at the top of this webpack config help group the SCSS and
                                    // plain CSS together for the bundler.

                                    require("postcss-simple-vars")(),
                                    require("postcss-strip-inline-comments")(),
                                    require("postcss-hexrgba")(),

                                    // It's important that this plugin is last otherwise we end
                                    // up with broken CSS.
                                    require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}),
                                ],
                                parser: "postcss-scss",
                                "local-plugins": true,
                            },
                        },
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 1,
                                sourceMap: true,
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            ident: 'postcss',
                            options: {
                                sourceMap: true,
                                plugins: () => [
                                    // Note that we use slightly different plugins for SCSS.

                                    require('postcss-import')(),
                                    require("postcss-mixins")(),
                                    require("postcss-simple-vars")(),
                                    require("postcss-extend")(),
                                    require("postcss-nested")(),
                                    require("postcss-easings")(),
                                    require("postcss-strip-inline-comments")(),
                                    require("postcss-hexrgba")(),

                                    // It's important that this plugin is last otherwise we end
                                    // up with broken CSS.
                                    require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}),
                                ],
                                parser: "postcss-scss",
                                "local-plugins": true,
                            },
                        },
                    ]
                },
                {
                    test: /\.wasm$/,
                    loader: "file-loader",
                    type: "javascript/auto", // https://github.com/webpack/webpack/issues/6725
                    options: {
                        name: '[name].[hash:7].[ext]',
                        outputPath: '.',
                    },
                },
                {
                    // cache-bust languages.json file placed in
                    // riot-web/webapp/i18n during build by copy-res.js
                    test: /\.*languages.json$/,
                    type: "javascript/auto",
                    loader: 'file-loader',
                    options: {
                        name: 'i18n/[name].[hash:7].[ext]',
                    },
                },
                {
                    test: /\.(gif|png|svg|ttf|woff|woff2|xml|ico)$/,
                    // Use a content-based hash in the name so that we can set a long cache
                    // lifetime for assets while still delivering changes quickly.
                    oneOf: [
                        {
                            // Assets referenced in CSS files
                            issuer: /\.(scss|css)$/,
                            loader: 'file-loader',
                            options: {
                                esModule: false,
                                name: '[name].[hash:7].[ext]',
                                outputPath: getImgOutputPath,
                                publicPath: function(url, resourcePath) {
                                    // CSS image usages end up in the `bundles/[hash]` output
                                    // directory, so we adjust the final path to navigate up
                                    // twice.
                                    const outputPath = getImgOutputPath(url, resourcePath);
                                    return toPublicPath(path.join("../..", outputPath));
                                },
                            },
                        },
                        {
                            // Assets referenced in HTML and JS files
                            loader: 'file-loader',
                            options: {
                                esModule: false,
                                name: '[name].[hash:7].[ext]',
                                outputPath: getImgOutputPath,
                                publicPath: function(url, resourcePath) {
                                    const outputPath = getImgOutputPath(url, resourcePath);
                                    return toPublicPath(outputPath);
                                },
                            },
                        },
                    ],
                },
            ]
        },

        plugins: [
            new webpack.DefinePlugin({
                'process.env': {
                    NODE_ENV: JSON.stringify(process.env.NODE_ENV),
                },
            }),

            // This exports our CSS using the splitChunks and loaders above.
            new MiniCssExtractPlugin({
                filename: 'bundles/[hash]/[name].css',
                ignoreOrder: false, // Enable to remove warnings about conflicting order
            }),

            // This is the app's main entry point.
            new HtmlWebpackPlugin({
                template: './src/vector/index.html',

                // we inject the links ourselves via the template, because
                // HtmlWebpackPlugin will screw up our formatting like the names
                // of the themes and which chunks we actually care about.
                inject: false,
                excludeChunks: ['mobileguide', 'usercontent', 'jitsi'],
                minify: argv.mode === 'production',
                vars: {
                    og_image_url: og_image_url,
                },
            }),

            // This is the jitsi widget wrapper (embedded, so isolated stack)
            new HtmlWebpackPlugin({
                template: './src/vector/jitsi/index.html',
                filename: 'jitsi.html',
                minify: argv.mode === 'production',
                chunks: ['jitsi'],
            }),

            // This is the mobile guide's entry point (separate for faster mobile loading)
            new HtmlWebpackPlugin({
                template: './src/vector/mobile_guide/index.html',
                filename: 'mobile_guide/index.html',
                minify: argv.mode === 'production',
                chunks: ['mobileguide'],
            }),

            // These are the static error pages for when the javascript env is *really unsupported*
            new HtmlWebpackPlugin({
                template: './src/vector/static/unable-to-load.html',
                filename: 'static/unable-to-load.html',
                minify: argv.mode === 'production',
                chunks: [],
            }),
            new HtmlWebpackPlugin({
                template: './src/vector/static/incompatible-browser.html',
                filename: 'static/incompatible-browser.html',
                minify: argv.mode === 'production',
                chunks: [],
            }),

            // This is the usercontent sandbox's entry point (separate for iframing)
            new HtmlWebpackPlugin({
                template: './node_modules/matrix-react-sdk/src/usercontent/index.html',
                filename: 'usercontent/index.html',
                minify: argv.mode === 'production',
                chunks: ['usercontent'],
            }),
        ],

        output: {
            path: path.join(__dirname, "webapp"),

            // The generated JS (and CSS, from the extraction plugin) are put in a
            // unique subdirectory for the build. There will only be one such
            // 'bundle' directory in the generated tarball; however, hosting
            // servers can collect 'bundles' from multiple versions into one
            // directory and symlink it into place - this allows users who loaded
            // an older version of the application to continue to access webpack
            // chunks even after the app is redeployed.
            filename: "bundles/[hash]/[name].js",
            chunkFilename: "bundles/[hash]/[name].js",
        },

        // configuration for the webpack-dev-server
        devServer: {
            // serve unwebpacked assets from webapp.
            contentBase: './webapp',

            // Only output errors, warnings, or new compilations.
            // This hides the massive list of modules.
            stats: 'minimal',

            // hot module replacement doesn't work (I think we'd need react-hot-reload?)
            // so webpack-dev-server reloads the page on every update which is quite
            // tedious in Riot since that can take a while.
            hot: false,
            inline: false,
        },
    };
};

/**
 * Merge assets found via CSS and imports into a single tree, while also preserving
 * directories under `res`.
 *
 * @param {string} url The adjusted name of the file, such as `warning.1234567.svg`.
 * @param {string} resourcePath The absolute path to the source file with unmodified name.
 * @return {string} The returned paths will look like `img/warning.1234567.svg`.
 */
function getImgOutputPath(url, resourcePath) {
    const prefix = /^.*[/\\]res[/\\]/;
    const outputDir = path.dirname(resourcePath).replace(prefix, "");
    return path.join(outputDir, path.basename(url));
}

/**
 * Convert path to public path format, which always uses forward slashes, since it will
 * be placed directly into things like CSS files.
 *
 * @param {string} path Some path to a file.
 */
function toPublicPath(path) {
    return path.replace(/\\/g, '/');
}
<commit_msg>rename element theme to light/dark to apply old prefs<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const webpack = require("webpack");

let og_image_url = process.env.RIOT_OG_IMAGE_URL;
if (!og_image_url) og_image_url = 'https://app.element.io/themes/element/img/logos/opengraph.png';

module.exports = (env, argv) => {
    if (process.env.CI_PACKAGE) {
        // Don't run minification for CI builds (this is only set for runs on develop)
        argv.mode = "development";
    }

    const development = {};
    if (argv.mode !== "production") {
        // This makes the sourcemaps human readable for developers. We use eval-source-map
        // because the plain source-map devtool ruins the alignment.
        development['devtool'] = 'eval-source-map';
    } else {
        development['devtool'] = 'nosources-source-map';
    }

    // Resolve the directories for the react-sdk and js-sdk for later use. We resolve these early so we
    // don't have to call them over and over. We also resolve to the package.json instead of the src
    // directory so we don't have to rely on a index.js or similar file existing.
    const reactSdkSrcDir = path.resolve(require.resolve("matrix-react-sdk/package.json"), '..', 'src');
    const jsSdkSrcDir = path.resolve(require.resolve("matrix-js-sdk/package.json"), '..', 'src');

    return {
        ...development,

        entry: {
            "bundle": "./src/vector/index.ts",
            "indexeddb-worker": "./src/vector/indexeddb-worker.js",
            "mobileguide": "./src/vector/mobile_guide/index.js",
            "jitsi": "./src/vector/jitsi/index.ts",
            "usercontent": "./node_modules/matrix-react-sdk/src/usercontent/index.js",

            // CSS themes
            "theme-legacy": "./node_modules/matrix-react-sdk/res/themes/legacy-light/css/legacy-light.scss",
            "theme-legacy-dark": "./node_modules/matrix-react-sdk/res/themes/legacy-dark/css/legacy-dark.scss",
            "theme-light": "./node_modules/matrix-react-sdk/res/themes/light/css/light.scss",
            "theme-dark": "./node_modules/matrix-react-sdk/res/themes/dark/css/dark.scss",
            "theme-light-custom": "./node_modules/matrix-react-sdk/res/themes/light-custom/css/light-custom.scss",
            "theme-dark-custom": "./node_modules/matrix-react-sdk/res/themes/dark-custom/css/dark-custom.scss",
        },

        optimization: {
            // Put all of our CSS into one useful place - this is needed for MiniCssExtractPlugin.
            // Previously we used a different extraction plugin that did this magic for us, but
            // now we need to consider that the CSS needs to be bundled up together.
            splitChunks: {
                cacheGroups: {
                    styles: {
                        name: 'styles',
                        test: /\.css$/,
                        enforce: true,
                        // Do not add `chunks: 'all'` here because you'll break the app entry point.
                    },
                    default: {
                        reuseExistingChunk: true,
                    },
                },
            },

            // This fixes duplicate files showing up in chrome with sourcemaps enabled.
            // See https://github.com/webpack/webpack/issues/7128 for more info.
            namedModules: false,

            // Minification is normally enabled by default for webpack in production mode, but
            // we use a CSS optimizer too and need to manage it ourselves.
            minimize: argv.mode === 'production',
            minimizer: argv.mode === 'production' ? [new TerserPlugin({}), new OptimizeCSSAssetsPlugin({})] : [],
        },

        resolve: {
            // We define an alternative import path so we can safely use src/ across the react-sdk
            // and js-sdk. We already import from src/ where possible to ensure our source maps are
            // extremely accurate (and because we're capable of compiling the layers manually rather
            // than relying on partially-mangled output from babel), though we do need to fix the
            // package level import (stuff like `import {Thing} from "matrix-js-sdk"` for example).
            // We can't use the aliasing down below to point at src/ because that'll fail to resolve
            // the package.json for the dependency. Instead, we rely on the package.json of each
            // layer to have our custom alternate fields to load things in the right order. These are
            // the defaults of webpack prepended with `matrix_src_`.
            mainFields: ['matrix_src_browser', 'matrix_src_main', 'browser', 'main'],
            aliasFields: ['matrix_src_browser', 'browser'],

            // We need to specify that TS can be resolved without an extension
            extensions: ['.js', '.json', '.ts', '.tsx'],
            alias: {
                // alias any requires to the react module to the one in our path,
                // otherwise we tend to get the react source included twice when
                // using `npm link` / `yarn link`.
                "react": path.resolve(__dirname, 'node_modules/react'),
                "react-dom": path.resolve(__dirname, 'node_modules/react-dom'),

                // same goes for js-sdk - we don't need two copies.
                "matrix-js-sdk": path.resolve(__dirname, 'node_modules/matrix-js-sdk'),
                // and prop-types and sanitize-html
                "prop-types": path.resolve(__dirname, 'node_modules/prop-types'),
                "sanitize-html": path.resolve(__dirname, 'node_modules/sanitize-html'),

                // Define a variable so the i18n stuff can load
                "$webapp": path.resolve(__dirname, 'webapp'),
            },
        },

        module: {
            noParse: [
                // for cross platform compatibility use [\\\/] as the path separator
                // this ensures that the regex trips on both Windows and *nix

                // don't parse the languages within highlight.js. They cause stack
                // overflows (https://github.com/webpack/webpack/issues/1721), and
                // there is no need for webpack to parse them - they can just be
                // included as-is.
                /highlight\.js[\\\/]lib[\\\/]languages/,

                // olm takes ages for webpack to process, and it's already heavily
                // optimised, so there is little to gain by us uglifying it.
                /olm[\\\/](javascript[\\\/])?olm\.js$/,
            ],
            rules: [
                {
                    test: /\.(ts|js)x?$/,
                    include: (f) => {
                        // our own source needs babel-ing
                        if (f.startsWith(path.resolve(__dirname, 'src'))) return true;

                        // we use the original source files of react-sdk and js-sdk, so we need to
                        // run them through babel. Because the path tested is the resolved, absolute
                        // path, these could be anywhere thanks to yarn link. We must also not
                        // include node modules inside these modules, so we add 'src'.
                        if (f.startsWith(reactSdkSrcDir)) return true;
                        if (f.startsWith(jsSdkSrcDir)) return true;

                        // but we can't run all of our dependencies through babel (many of them still
                        // use module.exports which breaks if babel injects an 'include' for its
                        // polyfills: probably fixable but babeling all our dependencies is probably
                        // not necessary anyway). So, for anything else, don't babel.
                        return false;
                    },
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true
                    }
                },
                {
                    test: /\.css$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 1,
                                sourceMap: true,
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            ident: 'postcss',
                            options: {
                                sourceMap: true,
                                plugins: () => [
                                    // Note that we use significantly fewer plugins on the plain
                                    // CSS parser. If we start to parse plain CSS, we end with all
                                    // kinds of nasty problems (like stylesheets not loading).
                                    //
                                    // You might have noticed that we're also sending regular CSS
                                    // through PostCSS. This looks weird, and in fact is probably
                                    // not what you'd expect, however in order for our CSS build
                                    // to work nicely we have to do this. Because down the line
                                    // our SCSS stylesheets reference plain CSS we have to load
                                    // the plain CSS through PostCSS so it can find it safely. This
                                    // also acts like a babel-for-css by transpiling our (S)CSS
                                    // down/up to the right browser support (prefixes, etc).
                                    // Further, if we don't do this then PostCSS assumes that our
                                    // plain CSS is SCSS and it really doesn't like that, even
                                    // though plain CSS should be compatible. The chunking options
                                    // at the top of this webpack config help group the SCSS and
                                    // plain CSS together for the bundler.

                                    require("postcss-simple-vars")(),
                                    require("postcss-strip-inline-comments")(),
                                    require("postcss-hexrgba")(),

                                    // It's important that this plugin is last otherwise we end
                                    // up with broken CSS.
                                    require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}),
                                ],
                                parser: "postcss-scss",
                                "local-plugins": true,
                            },
                        },
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 1,
                                sourceMap: true,
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            ident: 'postcss',
                            options: {
                                sourceMap: true,
                                plugins: () => [
                                    // Note that we use slightly different plugins for SCSS.

                                    require('postcss-import')(),
                                    require("postcss-mixins")(),
                                    require("postcss-simple-vars")(),
                                    require("postcss-extend")(),
                                    require("postcss-nested")(),
                                    require("postcss-easings")(),
                                    require("postcss-strip-inline-comments")(),
                                    require("postcss-hexrgba")(),

                                    // It's important that this plugin is last otherwise we end
                                    // up with broken CSS.
                                    require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}),
                                ],
                                parser: "postcss-scss",
                                "local-plugins": true,
                            },
                        },
                    ]
                },
                {
                    test: /\.wasm$/,
                    loader: "file-loader",
                    type: "javascript/auto", // https://github.com/webpack/webpack/issues/6725
                    options: {
                        name: '[name].[hash:7].[ext]',
                        outputPath: '.',
                    },
                },
                {
                    // cache-bust languages.json file placed in
                    // riot-web/webapp/i18n during build by copy-res.js
                    test: /\.*languages.json$/,
                    type: "javascript/auto",
                    loader: 'file-loader',
                    options: {
                        name: 'i18n/[name].[hash:7].[ext]',
                    },
                },
                {
                    test: /\.(gif|png|svg|ttf|woff|woff2|xml|ico)$/,
                    // Use a content-based hash in the name so that we can set a long cache
                    // lifetime for assets while still delivering changes quickly.
                    oneOf: [
                        {
                            // Assets referenced in CSS files
                            issuer: /\.(scss|css)$/,
                            loader: 'file-loader',
                            options: {
                                esModule: false,
                                name: '[name].[hash:7].[ext]',
                                outputPath: getImgOutputPath,
                                publicPath: function(url, resourcePath) {
                                    // CSS image usages end up in the `bundles/[hash]` output
                                    // directory, so we adjust the final path to navigate up
                                    // twice.
                                    const outputPath = getImgOutputPath(url, resourcePath);
                                    return toPublicPath(path.join("../..", outputPath));
                                },
                            },
                        },
                        {
                            // Assets referenced in HTML and JS files
                            loader: 'file-loader',
                            options: {
                                esModule: false,
                                name: '[name].[hash:7].[ext]',
                                outputPath: getImgOutputPath,
                                publicPath: function(url, resourcePath) {
                                    const outputPath = getImgOutputPath(url, resourcePath);
                                    return toPublicPath(outputPath);
                                },
                            },
                        },
                    ],
                },
            ]
        },

        plugins: [
            new webpack.DefinePlugin({
                'process.env': {
                    NODE_ENV: JSON.stringify(process.env.NODE_ENV),
                },
            }),

            // This exports our CSS using the splitChunks and loaders above.
            new MiniCssExtractPlugin({
                filename: 'bundles/[hash]/[name].css',
                ignoreOrder: false, // Enable to remove warnings about conflicting order
            }),

            // This is the app's main entry point.
            new HtmlWebpackPlugin({
                template: './src/vector/index.html',

                // we inject the links ourselves via the template, because
                // HtmlWebpackPlugin will screw up our formatting like the names
                // of the themes and which chunks we actually care about.
                inject: false,
                excludeChunks: ['mobileguide', 'usercontent', 'jitsi'],
                minify: argv.mode === 'production',
                vars: {
                    og_image_url: og_image_url,
                },
            }),

            // This is the jitsi widget wrapper (embedded, so isolated stack)
            new HtmlWebpackPlugin({
                template: './src/vector/jitsi/index.html',
                filename: 'jitsi.html',
                minify: argv.mode === 'production',
                chunks: ['jitsi'],
            }),

            // This is the mobile guide's entry point (separate for faster mobile loading)
            new HtmlWebpackPlugin({
                template: './src/vector/mobile_guide/index.html',
                filename: 'mobile_guide/index.html',
                minify: argv.mode === 'production',
                chunks: ['mobileguide'],
            }),

            // These are the static error pages for when the javascript env is *really unsupported*
            new HtmlWebpackPlugin({
                template: './src/vector/static/unable-to-load.html',
                filename: 'static/unable-to-load.html',
                minify: argv.mode === 'production',
                chunks: [],
            }),
            new HtmlWebpackPlugin({
                template: './src/vector/static/incompatible-browser.html',
                filename: 'static/incompatible-browser.html',
                minify: argv.mode === 'production',
                chunks: [],
            }),

            // This is the usercontent sandbox's entry point (separate for iframing)
            new HtmlWebpackPlugin({
                template: './node_modules/matrix-react-sdk/src/usercontent/index.html',
                filename: 'usercontent/index.html',
                minify: argv.mode === 'production',
                chunks: ['usercontent'],
            }),
        ],

        output: {
            path: path.join(__dirname, "webapp"),

            // The generated JS (and CSS, from the extraction plugin) are put in a
            // unique subdirectory for the build. There will only be one such
            // 'bundle' directory in the generated tarball; however, hosting
            // servers can collect 'bundles' from multiple versions into one
            // directory and symlink it into place - this allows users who loaded
            // an older version of the application to continue to access webpack
            // chunks even after the app is redeployed.
            filename: "bundles/[hash]/[name].js",
            chunkFilename: "bundles/[hash]/[name].js",
        },

        // configuration for the webpack-dev-server
        devServer: {
            // serve unwebpacked assets from webapp.
            contentBase: './webapp',

            // Only output errors, warnings, or new compilations.
            // This hides the massive list of modules.
            stats: 'minimal',

            // hot module replacement doesn't work (I think we'd need react-hot-reload?)
            // so webpack-dev-server reloads the page on every update which is quite
            // tedious in Riot since that can take a while.
            hot: false,
            inline: false,
        },
    };
};

/**
 * Merge assets found via CSS and imports into a single tree, while also preserving
 * directories under `res`.
 *
 * @param {string} url The adjusted name of the file, such as `warning.1234567.svg`.
 * @param {string} resourcePath The absolute path to the source file with unmodified name.
 * @return {string} The returned paths will look like `img/warning.1234567.svg`.
 */
function getImgOutputPath(url, resourcePath) {
    const prefix = /^.*[/\\]res[/\\]/;
    const outputDir = path.dirname(resourcePath).replace(prefix, "");
    return path.join(outputDir, path.basename(url));
}

/**
 * Convert path to public path format, which always uses forward slashes, since it will
 * be placed directly into things like CSS files.
 *
 * @param {string} path Some path to a file.
 */
function toPublicPath(path) {
    return path.replace(/\\/g, '/');
}
<|endoftext|>


<commit_before>// @datatype_void

var webpack = require('webpack');
var helpers = require('./helpers');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var HMR = helpers.hasProcessFlag('hot');

var config = require('./config/config.json');

var metadata = {
  title: 'Angular 2 MEAN Webpack Starter Kit by @datatype_void',
  baseUrl: '/',
  host: 'localhost',
  port: 8080,
  ENV: ENV,
  HMR: HMR
};
/*
 * Config
 */
module.exports = helpers.defaults({
  // static data for index.html
  metadata: metadata,
  // devtool: 'eval' // for faster builds use 'eval'

  // our angular app
  entry: {
    'polyfills': './src/polyfills.ts',
    'main': './src/main.ts'
  },

  // Config for our build files
  output: {
    path: helpers.root('dist')
  },

  resolve: {
    extensions: ['', '.ts', '.async.ts', '.js']
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },
      // TODO(datatypevoid):
      //`exclude: [ helpers.root('node_modules/rxjs') ]`
      //fixed with rxjs 5 beta.3 release
      { test: /\.js$/, loader: "source-map-loader",
        exclude: [ helpers.root('node_modules/rxjs') ]
      }
    ],
    loaders: [
      // Support for .ts files.
      { test: /\.ts$/, loader: 'ts-loader', exclude: [ /\.(spec|e2e)\.ts$/ ] },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,
        loader: 'raw-loader',
        exclude: [ helpers.root('src/index.html') ]
      },

      // support for sass imports
      // add CSS rules to your document:
      // `require("!style!css!sass!./file.scss");`
      {
        test: /\.scss$/,
        loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass'
      }

      // if you add a loader include the resolve file extension above
    ]
  },

  plugins: [
    // TODO(datatypevoid): investigate the necessity of these two
    // following lines
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),

    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: 'polyfills', filename: 'polyfills.bundle.js', minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
    // generating html
    new HtmlWebpackPlugin({ template: 'src/index.html' }),
    // replace
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(metadata.ENV),
        'NODE_ENV': JSON.stringify(metadata.ENV),
        'HMR': HMR
      }
    })
  ],

  // Other module loader config

  // our Webpack Development Server config
  devServer: {
    // Proxy requests to our express server
    proxy: {
      '*': {
        target: 'http://localhost:' + config.PORT,
        secure: false
      },
    },
    port: metadata.port,
    host: metadata.host
  }
});<commit_msg>chore(webpack.config): remove unneeded code<commit_after>// @datatype_void

var webpack = require('webpack');
var helpers = require('./helpers');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var HMR = helpers.hasProcessFlag('hot');

var config = require('./config/config.json');

var metadata = {
  title: 'Angular 2 MEAN Webpack Starter Kit by @datatype_void',
  baseUrl: '/',
  host: 'localhost',
  port: 8080,
  ENV: ENV,
  HMR: HMR
};
/*
 * Config
 */
module.exports = helpers.defaults({
  // static data for index.html
  metadata: metadata,
  // devtool: 'eval' // for faster builds use 'eval'

  // our angular app
  entry: {
    'polyfills': './src/polyfills.ts',
    'main': './src/main.ts'
  },

  // Config for our build files
  output: {
    path: helpers.root('dist')
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },
      // TODO(datatypevoid):
      //`exclude: [ helpers.root('node_modules/rxjs') ]`
      //fixed with rxjs 5 beta.3 release
      { test: /\.js$/, loader: "source-map-loader",
        exclude: [ helpers.root('node_modules/rxjs') ]
      }
    ],
    loaders: [
      // Support for .ts files.
      { test: /\.ts$/, loader: 'ts-loader', exclude: [ /\.(spec|e2e)\.ts$/ ] },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,
        loader: 'raw-loader',
        exclude: [ helpers.root('src/index.html') ]
      },

      // support for sass imports
      // add CSS rules to your document:
      // `require("!style!css!sass!./file.scss");`
      {
        test: /\.scss$/,
        loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass'
      }

      // if you add a loader include the resolve file extension above
    ]
  },

  plugins: [
    // TODO(datatypevoid): investigate the necessity of these two
    // following lines
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),

    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: 'polyfills', filename: 'polyfills.bundle.js', minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
    // generating html
    new HtmlWebpackPlugin({ template: 'src/index.html' }),
    // replace
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(metadata.ENV),
        'NODE_ENV': JSON.stringify(metadata.ENV),
        'HMR': HMR
      }
    })
  ],

  // Other module loader config

  // our Webpack Development Server config
  devServer: {
    // Proxy requests to our express server
    proxy: {
      '*': {
        target: 'http://localhost:' + config.PORT,
        secure: false
      },
    },
    port: metadata.port,
    host: metadata.host
  }
});
<|endoftext|>


<commit_before>'use strict'
var resolve = require('path').resolve
var webpack = require('webpack')

module.exports = {
  entry: resolve(__dirname, 'src/index.js'),
  output: {
    path: __dirname,
    filename: 'arangojs.min.js',
    library: 'arangojs'
  },
  module: {
    loaders: [
      {test: /\.js$/, loader: 'babel-loader'},
      {test: /\.json$/, loader: 'json-loader'}
    ]
  },
  target: 'web',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {NODE_ENV: '"production"'},
      'Buffer': {byteLength: false}
    }),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.UglifyJsPlugin({output: {comments: false}})
  ]
}
<commit_msg>Use UMD<commit_after>'use strict'
var resolve = require('path').resolve
var webpack = require('webpack')

module.exports = {
  entry: resolve(__dirname, 'src/index.js'),
  output: {
    path: __dirname,
    filename: 'arangojs.min.js',
    libraryTarget: 'umd',
    library: 'arangojs'
  },
  module: {
    loaders: [
      {test: /\.js$/, loader: 'babel-loader'},
      {test: /\.json$/, loader: 'json-loader'}
    ]
  },
  target: 'web',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {NODE_ENV: '"production"'},
      'Buffer': {byteLength: false}
    }),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.UglifyJsPlugin({output: {comments: false}})
  ]
}
<|endoftext|>


<commit_before>var webpack = require("webpack");
var libraryName = require("./package.json").name;
var withLocalesSuffix = "-i18n";

module.exports = {
  mode: "production",
  entry: {
    [libraryName]: "./src/cronstrue.ts",
    [libraryName + ".min"]: "./src/cronstrue.ts",
    [libraryName + withLocalesSuffix]: "./src/cronstrue-i18n.ts",
    [libraryName + withLocalesSuffix + ".min"]: "./src/cronstrue-i18n.ts"
  },
  output: {
    path: __dirname + "/dist",
    filename: "[name].js",
    library: libraryName,
    libraryTarget: "umd",
    // Workaround for webpack 4 umd bug (Ref: https://github.com/webpack/webpack/issues/6522)
    globalObject: "typeof self !== 'undefined' ? self : this"
  },
  resolve: {
    extensions: [".js", ".ts"]
  },
  module: {
    /*
         * Each loader needs an associated Regex test that goes through each
         * of the files you've included (or in this case, all files but the
         * ones in the excluded directories) and finds all files that pass
         * the test. Then it will apply the loader to that file. I haven't
         * installed ts-loader yet, but will do that shortly.
         */
    rules: [
      {
        test: /\.ts$/,
        loader: "ts-loader"
      }
    ]
  }
};
<commit_msg>Set umdNamedDefine to true<commit_after>var webpack = require("webpack");
var libraryName = require("./package.json").name;
var withLocalesSuffix = "-i18n";

module.exports = {
  mode: "production",
  entry: {
    [libraryName]: "./src/cronstrue.ts",
    [libraryName + ".min"]: "./src/cronstrue.ts",
    [libraryName + withLocalesSuffix]: "./src/cronstrue-i18n.ts",
    [libraryName + withLocalesSuffix + ".min"]: "./src/cronstrue-i18n.ts"
  },
  output: {
    path: __dirname + "/dist",
    filename: "[name].js",
    library: libraryName,
    libraryTarget: "umd",
    umdNamedDefine: true,
    // Workaround for webpack 4 umd bug (Ref: https://github.com/webpack/webpack/issues/6522)
    globalObject: "typeof self !== 'undefined' ? self : this"
  },
  resolve: {
    extensions: [".js", ".ts"]
  },
  module: {
    /*
         * Each loader needs an associated Regex test that goes through each
         * of the files you've included (or in this case, all files but the
         * ones in the excluded directories) and finds all files that pass
         * the test. Then it will apply the loader to that file. I haven't
         * installed ts-loader yet, but will do that shortly.
         */
    rules: [
      {
        test: /\.ts$/,
        loader: "ts-loader"
      }
    ]
  }
};
<|endoftext|>


<commit_before>const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  mode: 'production',
  devtool: '#source-map',
  node: {
    fs: 'empty',
    net: 'empty',
    module: 'empty'
  },
  entry: './src/frontend/App.js',
  output: {
    path: path.resolve(__dirname + '/dist/'),
    publicPath: '/',
    filename: 'assets/bundle.js'
  },
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true
      }),
      new OptimizeCSSAssetsPlugin({})
    ]
  },
  module: {
    rules: [
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react'] } },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                localIdentName: '[name]_[local]_[hash:base64:5]'
              }
            }
          }
        ],
        exclude: /node_modules/
      },
      { test: /\.scss$/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'], exclude: /node_modules/ },
      {
        test: /\.(png|jp(e*)g)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000, // Convert images < 8kb to base64 strings
              name: 'assets/img/[hash]-[name].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        exclude: [path.resolve(__dirname, 'src/frontend/images')],
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'assets/fonts/[name].[ext]'
            }
          }
        ]
      },
      {
        test: /\.svg$/,
        include: [path.resolve(__dirname, 'src/frontend/images')],
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'assets/img/[name].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'assets/[name].css',
      chunkFilename: 'assets/[id].css'
    }),
    new HtmlWebpackPlugin({
      template: './src/index.template.html',
      inject: 'body',
      filename: 'index.html'
    })
  ],
  resolve: {
    modules: ['node_modules'],
    alias: {
      Components: path.resolve('./src/frontend/Components'),
      Containers: path.resolve('./src/frontend/Containers'),
      css: path.resolve('./src/frontend/css'),
      Images: path.resolve('./src/frontend/images'),
      Assets: path.resolve('./src/backend/assets'),
      Routes: path.resolve('./src/backend/routes')
    },
    extensions: ['.js', '.jsx', '.json', '.css', '.scss']
  },
  target: 'web'
};
<commit_msg>Prettify<commit_after>const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  mode: 'production',
  devtool: '#source-map',
  node: {
    fs: 'empty',
    net: 'empty',
    module: 'empty'
  },
  entry: './src/frontend/App.js',
  output: {
    path: path.resolve(__dirname + '/dist/'),
    publicPath: '/',
    filename: 'assets/bundle.js'
  },
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true
      }),
      new OptimizeCSSAssetsPlugin({})
    ]
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['react']
        }
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                localIdentName: '[name]_[local]_[hash:base64:5]'
              }
            }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(png|jp(e*)g)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000, // Convert images < 8kb to base64 strings
              name: 'assets/img/[hash]-[name].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        exclude: [path.resolve(__dirname, 'src/frontend/images')],
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'assets/fonts/[name].[ext]'
            }
          }
        ]
      },
      {
        test: /\.svg$/,
        include: [path.resolve(__dirname, 'src/frontend/images')],
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'assets/img/[name].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'assets/[name].css',
      chunkFilename: 'assets/[id].css'
    }),
    new HtmlWebpackPlugin({
      template: './src/index.template.html',
      inject: 'body',
      filename: 'index.html'
    })
  ],
  resolve: {
    modules: ['node_modules'],
    alias: {
      Components: path.resolve('./src/frontend/Components'),
      Containers: path.resolve('./src/frontend/Containers'),
      css: path.resolve('./src/frontend/css'),
      Images: path.resolve('./src/frontend/images'),
      Assets: path.resolve('./src/backend/assets'),
      Routes: path.resolve('./src/backend/routes')
    },
    extensions: ['.js', '.jsx', '.json', '.css', '.scss']
  },
  target: 'web'
};
<|endoftext|>


<commit_before>const Future = require("./Future");
const { assert, assertFunc, append, noop, ident, raise } = require("./utils");

const assertTask = arg => assert(arg instanceof Task, "argument is not a Task");

class Task {
  static resolve(value) {
    return Task.from(k => k(value));
  }

  static reject(err) {
    return Task.from((_, ke) => ke(err));
  }

  static cancel(reason) {
    return Task.from((_, __, kc) => kc(reason));
  }

  static from(cps) {
    assertFunc(cps);

    return new Task(() => new Future(cps));
  }

  constructor(fork) {
    this.fork = fork;
  }

  run(onSuccess = noop, onError = raise, onCancel = noop) {
    assertFunc(onSuccess);
    assertFunc(onError);
    assertFunc(onCancel);

    const fut = this.fork();
    fut.subscribe(onSuccess, onError, onCancel);
    return fut;
  }

  static empty() {
    return EMPTY_TASK;
  }

  orElse(c2) {
    assertTask(c2);

    if (this === EMPTY_TASK) return c2;
    if (c2 === EMPTY_TASK) return this;

    return new Task(() => {
      const f1 = this.fork();
      if (f1.status !== Future.PENDING) return f1;
      return f1.orElse(c2.fork());
    });
  }

  static of(a) {
    return Task.from(k => k(a));
  }

  static zipw(f, c1, c2) {
    assertFunc(f);
    assertTask(c1);
    assertTask(c2);

    if (c1 === EMPTY_TASK || c2 === EMPTY_TASK) return EMPTY_TASK;

    return new Task(() => {
      const f1 = c1.fork();
      if (f1.status === Future.CANCELLED || f1.status === Future.REJECTED)
        return f1;
      return Future.zipw(f, f1, c2.fork());
    });
  }

  then(f = Task.resolve, fe = Task.reject) {
    assertFunc(f);
    assertFunc(fe);

    if (this === EMPTY_TASK) return EMPTY_TASK;
    return new Task(() =>
      this.fork().then(v => f(v).fork(), e => fe(e).fork())
    );
  }

  static lift2(f) {
    assertFunc(f);

    return (c1, c2) => Task.zipw(f, c1, c2);
  }

  static lift(f) {
    assertFunc(f);

    return (...cs) => Task.apply(f, cs);
  }

  static race2(c1, c2) {
    assertTask(c1);
    assertTask(c2);

    return c1.orElse(c2);
  }

  static race(cs) {
    cs.forEach(assertTask);

    return cs.reduce(Task.race2, Task.empty);
  }

  static all(cs) {
    cs.forEach(assertTask);

    return cs.reduce(appendT, Task.of([]));
  }

  static traverse(f, cs) {
    assertFunc(f);

    return Task.all(cs.map(f));
  }

  static detect(p, cs) {
    assertFunc(p);

    return Task.race(
      cs.map(c => c.then(v => p(v).then(b => (b ? Task.of(v) : Task.empty))))
    );
  }

  static apply(f, cs, ctx) {
    assertFunc(f);

    return Task.all(cs).map(as => f.apply(ctx, as));
  }

  log(prefix) {
    return this.run(
      v => console.log(prefix, ": resolved with ", v),
      e => console.error(prefix, ": rejected with ", e),
      r => console.log(prefix, ": cancelled with ", r)
    );
  }

  static do(gf) {
    return new Task(() => {
      const g = gf();
      return next();

      function next(a, isErr) {
        try {
          const { value, done } = isErr ? g.throw(a) : g.next(a);
          if (done) {
            return Future.of(value);
          }
          return value.fork().then(
            v => {
              //console.log('next', a)
              return next(v);
            },
            e => {
              //console.log('next err', a)
              return next(e, true);
            },
            r => {
              g.return(r);
              return Future.cancel(r);
            }
          );
        } catch (e) {
          return Future.reject(e);
        }
      }
    });
  }
}

const appendT = Task.lift2(append);
const EMPTY_TASK = new Task(Future.empty);

module.exports = Task;
<commit_msg>Update Task.js<commit_after>const Future = require("./Future");
const { assert, assertFunc, append, noop, ident, raise } = require("./utils");

const assertTask = arg => assert(arg instanceof Task, "argument is not a Task");

class Task {
  static resolve(value) {
    return Task.from(k => k(value));
  }

  static reject(err) {
    return Task.from((_, ke) => ke(err));
  }

  static cancel(reason) {
    return Task.from((_, __, kc) => kc(reason));
  }

  static from(cps) {
    assertFunc(cps);

    return new Task(() => new Future(cps));
  }

  constructor(fork) {
    this.fork = fork;
  }

  run(onSuccess = noop, onError = raise, onCancel = noop) {
    assertFunc(onSuccess);
    assertFunc(onError);
    assertFunc(onCancel);

    const fut = this.fork();
    fut.subscribe(onSuccess, onError, onCancel);
    return fut;
  }

  static empty() {
    return EMPTY_TASK;
  }

  orElse(c2) {
    assertTask(c2);

    if (this === EMPTY_TASK) return c2;
    if (c2 === EMPTY_TASK) return this;

    return new Task(() => {
      const f1 = this.fork();
      if (f1.status !== Future.PENDING) return f1;
      return f1.orElse(c2.fork());
    });
  }

  static of(a) {
    return Task.from(k => k(a));
  }

  static zipw(f, c1, c2) {
    assertFunc(f);
    assertTask(c1);
    assertTask(c2);

    if (c1 === EMPTY_TASK || c2 === EMPTY_TASK) return EMPTY_TASK;

    return new Task(() => {
      const f1 = c1.fork();
      if (f1.status === Future.CANCELLED || f1.status === Future.REJECTED)
        return f1;
      return Future.zipw(f, f1, c2.fork());
    });
  }

  then(f = Task.resolve, fe = Task.reject) {
    assertFunc(f);
    assertFunc(fe);

    if (this === EMPTY_TASK) return EMPTY_TASK;
    return new Task(() =>
      this.fork().then(v => f(v).fork(), e => fe(e).fork())
    );
  }

  static lift2(f) {
    assertFunc(f);

    return (c1, c2) => Task.zipw(f, c1, c2);
  }

  static lift(f) {
    assertFunc(f);

    return (...cs) => Task.apply(f, cs);
  }

  static race2(c1, c2) {
    assertTask(c1);
    assertTask(c2);

    return c1.orElse(c2);
  }

  static race(cs) {
    cs.forEach(assertTask);

    return cs.reduce(Task.race2, EMPTY_TASK);
  }

  static all(cs) {
    cs.forEach(assertTask);

    return cs.reduce(appendT, Task.of([]));
  }

  static traverse(f, cs) {
    assertFunc(f);

    return Task.all(cs.map(f));
  }

  static detect(p, cs) {
    assertFunc(p);

    return Task.race(
      cs.map(c => c.then(v => p(v).then(b => (b ? Task.of(v) : EMPTY_TASK))))
    );
  }

  static apply(f, cs, ctx) {
    assertFunc(f);

    return Task.all(cs).map(as => f.apply(ctx, as));
  }

  log(prefix) {
    return this.run(
      v => console.log(prefix, ": resolved with ", v),
      e => console.error(prefix, ": rejected with ", e),
      r => console.log(prefix, ": cancelled with ", r)
    );
  }

  static do(gf) {
    return new Task(() => {
      const g = gf();
      return next();

      function next(a, isErr) {
        try {
          const { value, done } = isErr ? g.throw(a) : g.next(a);
          if (done) {
            return Future.of(value);
          }
          return value.fork().then(
            v => {
              //console.log('next', a)
              return next(v);
            },
            e => {
              //console.log('next err', a)
              return next(e, true);
            },
            r => {
              g.return(r);
              return Future.cancel(r);
            }
          );
        } catch (e) {
          return Future.reject(e);
        }
      }
    });
  }
}

const appendT = Task.lift2(append);
const EMPTY_TASK = new Task(Future.empty);

module.exports = Task;
<|endoftext|>


<commit_before>import AbstractStore from './AbstractStore'

/**
 * Wraps a node (data given by the user) so we can attach more info like
 * parent, open/closed state etc.
 */
class NodeWrapper {
  constructor(data, parent, model) {
    this.data = data
    this.parent = parent
    this.label = model.getLabel(data)
    this.isLeaf = model.isLeaf(data)
    this.key = model.getKey(data)
    this.open = false
    this.selected = false
  }
}

/**
 * Recursively builds the list of nodes that we need to display according
 * to their 'open' state (we need to scan only open nodes).
 */
function scan(node, list, showRoot) {

  if (showRoot || list.length > 0) {
    var index = list.length
    node.index = index
    list.push(node)
  }

  if (node.open) {
    node.children.forEach(n => scan(n, list, true))
  }
}

/**
 * Holds the state of the Explorer component.
 */
export default class Tree extends AbstractStore {
  constructor(model, opt) {
    super()
    this.opt = opt
    this.model = model
    this.wrap = this.wrap.bind(this)
    this.select = this.select.bind(this)
    this.root = this.wrap(model.getRoot())
    this.right = this.right.bind(this)
    if (!opt.showRoot) {
      this.__open0(this.root)
      this.root.hidden = true
    }
    this.__recompute('INIT')
  }

  __recompute(event) {
    this.list = []
    scan(this.root, this.list, this.opt.showRoot)
    if (!this.selected) {
      this.list[0].selected = true
      this.selected = this.list[0]
    }
    this.__emitChange(event)
  }

  wrap(node, parent) {
    return new NodeWrapper(node, parent, this.model)
  }

  getRoot() {
    return this.root
  }

  toggle(node) {
    if (node.open)
      this.close(node)
    else
      this.open(node)
  }

  open(node) {
    this.__open0(node)
    this.__recompute('OPEN')
  }

  __open0(node) {
    node.open = true
    node.children = this.model.getChildren(node.data).map(d => this.wrap(d, node, this.model))
  }

  close(node) {
    node.open = false
    this.__recompute('CLOSE')
  }

  select(node) {
    if (this.selected)
      this.selected.selected = false
    this.selected = node
    node.selected = true
    this.__emitChange('SELECTION')
  }

  edit() {
    if (this.selected && !this.selected.editing) {
      this.selected.editing = true
      this.__emitChange('EDIT_START')
    }
  }

  isEditing() {
    return this.selected && this.selected.editing
  }

  cancelEdition() {
    this.selected.editing = false;
    this.__emitChange('EDIT_CANCEL')
  }

  applyEdition(newLabel) {
    this.selected.editing = false;
    this.selected.label = newLabel
    this.__emitChange('EDIT_APPLY')
  }

  right() {
    if (this.selected) {
      if (!this.selected.isLeaf && !this.selected.open)
        this.open(this.selected)
      else {
        this.down()
      }
    } else this.select(this.root)
  }

  left() {
    if (this.selected) {
      if (this.selected.open)
        this.close(this.selected)
      else if (this.selected.index > 0 && this.selected.parent) {
        this.select(this.selected.parent)
      }
    } else this.select(this.root)
  }

  down() {
    if (this.selected) {
      if (this.list.length > this.selected.index + 1) {
        this.selected.selected = false
        this.selected = this.list[this.selected.index + 1]
        this.selected.selected = true
        this.__emitChange('SELECTION')
      }
    } else {
      this.select(this.root)
    }
  }

  up() {
    if (this.selected) {
      if (this.selected.index > 0) {
        this.selected.selected = false
        this.selected = this.list[this.selected.index - 1]
        this.selected.selected = true
        this.__emitChange('SELECTION')
      }
    } else {
      this.select(this.root)
    }
  }
}
<commit_msg>Fix minor bugs with \!showRoot<commit_after>import AbstractStore from './AbstractStore'

/**
 * Wraps a node (data given by the user) so we can attach more info like
 * parent, open/closed state etc.
 */
class NodeWrapper {
  constructor(data, parent, model) {
    this.data = data
    this.parent = parent
    this.label = model.getLabel(data)
    this.isLeaf = model.isLeaf(data)
    this.key = model.getKey(data)
    this.open = false
    this.selected = false
  }
}

/**
 * Recursively builds the list of nodes that we need to display according
 * to their 'open' state (we need to scan only open nodes).
 */
function scan(node, list, showRoot) {

  if (showRoot || list.length > 0) {
    var index = list.length
    node.index = index
    list.push(node)
  }

  if (node.open) {
    node.children.forEach(n => scan(n, list, true))
  }
}

/**
 * Holds the state of the Explorer component.
 */
export default class Tree extends AbstractStore {
  constructor(model, opt) {
    super()
    this.opt = opt
    this.model = model
    this.wrap = this.wrap.bind(this)
    this.select = this.select.bind(this)
    this.root = this.wrap(model.getRoot())
    this.right = this.right.bind(this)
    if (!opt.showRoot) {
      this.__open0(this.root)
      this.root.hidden = true
    }
    this.__recompute('INIT')
  }

  __recompute(event) {
    this.list = []
    scan(this.root, this.list, this.opt.showRoot)
    if (!this.selected) {
      this.list[0].selected = true
      this.selected = this.list[0]
    }
    this.__emitChange(event)
  }

  wrap(node, parent) {
    return new NodeWrapper(node, parent, this.model)
  }

  getRoot() {
    return this.root
  }

  toggle(node) {
    if (node.open)
      this.close(node)
    else
      this.open(node)
  }

  open(node) {
    this.__open0(node)
    this.__recompute('OPEN')
  }

  __open0(node) {
    node.open = true
    node.children = this.model.getChildren(node.data).map(d => this.wrap(d, node, this.model))
  }

  close(node) {
    node.open = false
    this.__recompute('CLOSE')
  }

  select(node) {
    if (this.selected)
      this.selected.selected = false
    this.selected = node
    node.selected = true
    this.__emitChange('SELECTION')
  }

  edit() {
    if (this.selected && !this.selected.editing) {
      this.selected.editing = true
      this.__emitChange('EDIT_START')
    }
  }

  isEditing() {
    return this.selected && this.selected.editing
  }

  cancelEdition() {
    this.selected.editing = false;
    this.__emitChange('EDIT_CANCEL')
  }

  applyEdition(newLabel) {
    this.selected.editing = false;
    this.selected.label = newLabel
    this.__emitChange('EDIT_APPLY')
  }

  right() {
    if (this.selected) {
      if (!this.selected.isLeaf && !this.selected.open)
        this.open(this.selected)
      else {
        this.down()
      }
    } else if (!this.root.hidden)
      this.select(this.root)
  }

  left() {
    if (this.selected) {
      if (this.selected.open)
        this.close(this.selected)
      else if (this.selected.index > 0 && this.selected.parent) {
        this.select(this.selected.parent)
      }
    } else if (!this.root.hidden)
      this.select(this.root)
  }

  down() {
    if (this.selected) {
      if (this.list.length > this.selected.index + 1) {
        this.selected.selected = false
        this.selected = this.list[this.selected.index + 1]
        this.selected.selected = true
        this.__emitChange('SELECTION')
      }
    } else if (!this.root.hidden) {
      this.select(this.root)
    }
  }

  up() {
    if (this.selected) {
      if (this.selected.index > 0) {
        this.selected.selected = false
        this.selected = this.list[this.selected.index - 1]
        this.selected.selected = true
        this.__emitChange('SELECTION')
      }
    } else if (!this.root.hidden) {
      this.select(this.root)
    }
  }
}
<|endoftext|>


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

module.exports = {
    entry: {
        main: './javascript/app.jsx',
        vendor: ['react', 'react-dom', 'react-intl']
    },
    output: {
        path: './assets/javascript',
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ['vendor', 'manifest']
        })
    ],
    module: {
        loaders: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            loader: "babel-loader",
            query: { presets: ["es2015", "react"] }
        }]
    },
    devtool: 'cheap-source-map',
    watch: false
};
<commit_msg>The latest version of Webpack wanted the full absolute path for the output path<commit_after>const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: {
        main: './javascript/app.jsx',
        vendor: ['react', 'react-dom', 'react-intl']
    },
    output: {
        path: path.resolve('assets/javascript'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ['vendor', 'manifest']
        })
    ],
    module: {
        loaders: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            loader: "babel-loader",
            query: { presets: ["es2015", "react"] }
        }]
    },
    devtool: 'cheap-source-map',
    watch: false
};
<|endoftext|>


<commit_before>const path = require("path");
const webpack = require("webpack");

const TerserPlugin = require('terser-webpack-plugin');
// const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
// let commitHash = require('child_process')
// 				.execSync('git rev-parse --short HEAD')
// 				.toString()
// 				.trim();

module.exports = {
	entry: {
        "moderndeck": "./src/Boot/Boot.ts",
	},
	output: {
		filename: "[name].js",
		path: path.resolve(__dirname, "common/assets"),
		// publicPath: "//dangeredwolf.com/",
		publicPath: '/',
		environment: {
			arrowFunction: true
		},
		assetModuleFilename: "common/assets/[name].[ext][query]"
	},
	devtool: "source-map",
    resolve: {
        extensions: [".js", ".jsx", ".ts", ".tsx", ".png", ".jpg", ".mp3", ".mp4", ".aac", ".webp"],
    },
	plugins: [
		// new webpack.DefinePlugin({
		// 	__BUILD_ID__: JSON.stringify(buildId)
		// }),
		new webpack.BannerPlugin({
			banner:
`ModernDeck ${require("./package.json").version}, built ${new Date().toISOString()}

(c) 2014-${new Date().toISOString().slice(0,4)} dangered wolf, released under MIT license.

Made with <3
`,
		})
	],
	mode: "production",
	module: {
		rules: [
		{
			test: /\.(png|svg|jpg|jpeg|gif|webp|mp3|woff|woff2|eot|ttf|otf|aac)$/i,
			type: "asset/resource"
		},
		{
			test: /\.(csv|tsv)$/i,
			use: ["csv-loader"],
		},
		{
			test: /\.tsx?$/,
			use: 'ts-loader',
			exclude: /node_modules/,
		},
		{
			test: /\.m?js$/,
			// ModernDeck only uses ES6 imports, `require` is only used to interface with Node in the Electron version
			parser: {
				amd: false, // disable AMD
				commonjs: false, // disable CommonJS
				system: false, // disable SystemJS
				requireInclude: false, // disable require.include
				requireEnsure: false, // disable require.ensure
				requireContext: false, // disable require.context
				browserify: false, // disable special handling of Browserify bundles
				requireJs: false, // disable requirejs.*
				node: false, // disable __dirname, __filename, module, require.extensions, require.main, etc.
				commonjsMagicComments: false // disable magic comments support for CommonJS
			},
			use: {
				loader: "babel-loader",
				options: {
					presets: [
						["@babel/preset-env", { targets: "firefox 52" }]
					],
					plugins: [
						"@babel/plugin-proposal-optional-chaining",
						"@babel/plugin-proposal-export-default-from",
						"@babel/plugin-proposal-class-properties",
						"@babel/plugin-transform-exponentiation-operator"
					]
				}
			}
		}
	]},
	optimization: {
		minimizer: [
			new TerserPlugin({
				extractComments: false,
				terserOptions: {
					mangle: false
				}
			})
		],
	},
}<commit_msg>Update webpack.config.js<commit_after>const path = require("path");
const webpack = require("webpack");

const TerserPlugin = require('terser-webpack-plugin');
// const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
// let commitHash = require('child_process')
// 				.execSync('git rev-parse --short HEAD')
// 				.toString()
// 				.trim();

module.exports = {
	entry: {
        "moderndeck": "./src/Boot/Boot.ts",
	},
	output: {
		filename: "[name].js",
		path: path.resolve(__dirname, "common/assets/js"),
		environment: {
			arrowFunction: true
		},
		assetModuleFilename: "common/assets/[name].[ext][query]"
	},
	devtool: "source-map",
    resolve: {
        extensions: [".js", ".jsx", ".ts", ".tsx", ".png", ".jpg", ".mp3", ".mp4", ".aac", ".webp"],
    },
	experiments: {
		topLevelAwait: true
	},
	plugins: [
		// new webpack.DefinePlugin({
		// 	__BUILD_ID__: JSON.stringify(buildId)
		// }),
		new webpack.BannerPlugin({
			banner:
`ModernDeck ${require("./package.json").version}, built ${new Date().toISOString()}

(c) 2014-${new Date().toISOString().slice(0,4)} dangered wolf, released under MIT license.

Made with <3
`,
		})
	],
	mode: "production",
	module: {
		rules: [
		{
			test: /\.(png|svg|jpg|jpeg|gif|webp|mp3|woff|woff2|eot|ttf|otf|aac)$/i,
			type: "asset/resource"
		},
		{
			test: /\.(csv|tsv)$/i,
			use: ["csv-loader"],
		},
		{
			test: /\.tsx?$/,
			use: 'ts-loader',
			exclude: /node_modules/,
		},
		{
			test: /\.m?js$/,
			// ModernDeck only uses ES6 imports, `require` is only used to interface with Node in the Electron version
			parser: {
				amd: false, // disable AMD
				commonjs: false, // disable CommonJS
				system: false, // disable SystemJS
				requireInclude: false, // disable require.include
				requireEnsure: false, // disable require.ensure
				requireContext: false, // disable require.context
				browserify: false, // disable special handling of Browserify bundles
				requireJs: false, // disable requirejs.*
				node: false, // disable __dirname, __filename, module, require.extensions, require.main, etc.
				commonjsMagicComments: false // disable magic comments support for CommonJS
			},
			use: {
				loader: "babel-loader",
				options: {
					presets: [
						["@babel/preset-env", { targets: "firefox 52" }]
					],
					plugins: [
						"@babel/plugin-proposal-optional-chaining",
						"@babel/plugin-proposal-export-default-from",
						"@babel/plugin-proposal-class-properties",
						"@babel/plugin-transform-exponentiation-operator"
					]
				}
			}
		}
	]},
	optimization: {
		minimizer: [
			new TerserPlugin({
				extractComments: false,
				terserOptions: {
					mangle: false
				}
			})
		],
	},
}<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const proxy = require('./server/webpack-dev-proxy');
const loaders = require('./webpack/loaders');
const plugins = require('./webpack/plugins');
const postcssInit = require('./webpack/postcss');

const baseAppEntries = ['./src/index.tsx'];
const devAppEntries = ['webpack-hot-middleware/client?reload=true'];
const appEntries = baseAppEntries
  .concat(process.env.NODE_ENV === 'development' ? devAppEntries : []);

// FIXME: change next line if you don't want publish to gh-pages
const publicPath = '/typescript-react-redux-starter'
const vendor = [
  'react',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux',
  'antd'
]
module.exports = {
  entry: {
    app: appEntries,
    vendor: vendor
  },

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[hash].js',
    publicPath: publicPath,
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: 'source-map',
  resolve: { extensions: ['', '.webpack.js', '.web.js', '.tsx', '.ts', '.js'] },
  plugins: plugins,

  devServer: {
    historyApiFallback: { index: '/' },
    proxy: Object.assign({}, proxy(), { '/api/*': 'http://localhost:3000' }),
  },

  module: {
    preLoaders: [
      loaders.tslint,
    ],
    loaders: [
      loaders.tsx,
      loaders.html,
      loaders.css,
      loaders.svg,
      loaders.image,
      loaders.eot,
      loaders.woff,
      loaders.woff2,
      loaders.ttf,
    ],
  },

  postcss: postcssInit,
};
<commit_msg>chore(webpack): fixes publicPath<commit_after>'use strict';

const path = require('path');
const proxy = require('./server/webpack-dev-proxy');
const loaders = require('./webpack/loaders');
const plugins = require('./webpack/plugins');
const postcssInit = require('./webpack/postcss');

const baseAppEntries = ['./src/index.tsx'];
const devAppEntries = ['webpack-hot-middleware/client?reload=true'];
const appEntries = baseAppEntries
  .concat(process.env.NODE_ENV === 'development' ? devAppEntries : []);

// FIXME: change next line if you don't want publish to gh-pages
const publicPath = '/typescript-react-redux-starter/'
const vendor = [
  'react',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux',
  'antd'
]
module.exports = {
  entry: {
    app: appEntries,
    vendor: vendor
  },

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[hash].js',
    publicPath: publicPath,
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: 'source-map',
  resolve: { extensions: ['', '.webpack.js', '.web.js', '.tsx', '.ts', '.js'] },
  plugins: plugins,

  devServer: {
    historyApiFallback: { index: '/' },
    proxy: Object.assign({}, proxy(), { '/api/*': 'http://localhost:3000' }),
  },

  module: {
    preLoaders: [
      loaders.tslint,
    ],
    loaders: [
      loaders.tsx,
      loaders.html,
      loaders.css,
      loaders.svg,
      loaders.image,
      loaders.eot,
      loaders.woff,
      loaders.woff2,
      loaders.ttf,
    ],
  },

  postcss: postcssInit,
};
<|endoftext|>


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

var TARGET = process.env.npm_lifecycle_event; // start (demo server) or build (production bundle)
process.env.BABEL_ENV = TARGET;

var config = {
  module: {
    rules: [
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        exclude: /node_modules/
      }
    ]
  }
};

// dev server
if (TARGET === 'start' || !TARGET) {
  module.exports = merge(config, {
    entry: './demo/index.js',
    devtool: 'inline-source-map',
    devServer: {
      contentBase: './demo',
      stats: 'errors-only'
    }
  });
}

// production build
if (TARGET === 'build') {
  module.exports = merge(config, {
    externals: {
      "react": "umd react",
      "react-dom": "umd react-dom",
      "create-react-class": "umd create-react-class",
      "prop-types": "umd prop-types",
      "mobiledoc-kit": "umd mobiledoc-kit"
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
      })
    ]
  });
}
<commit_msg>Restore UMD<commit_after>var webpack = require('webpack');
var merge = require('webpack-merge');

var TARGET = process.env.npm_lifecycle_event; // start (demo server) or build (production bundle)
process.env.BABEL_ENV = TARGET;

var config = {
  output: {
    library: 'ReactMobiledocEditor',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        exclude: /node_modules/
      }
    ]
  }
};

// dev server
if (TARGET === 'start' || !TARGET) {
  module.exports = merge(config, {
    entry: './demo/index.js',
    devtool: 'inline-source-map',
    devServer: {
      contentBase: './demo',
      stats: 'errors-only'
    }
  });
}

// production build
if (TARGET === 'build') {
  module.exports = merge(config, {
    externals: {
      "react": "umd react",
      "react-dom": "umd react-dom",
      "create-react-class": "umd create-react-class",
      "prop-types": "umd prop-types",
      "mobiledoc-kit": "umd mobiledoc-kit"
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
      })
    ]
  });
}
<|endoftext|>


<commit_before>'use strict';

const LiveReloadPlugin = require('webpack-livereload-plugin');
const devMode = process.env.NODE_ENV === 'development';

/**
 * Fast source maps rebuild quickly during development, but only give a link
 * to the line where the error occurred. The stack trace will show the bundled
 * code, not the original code. Keep this on `false` for slower builds but
 * usable stack traces. Set to `true` if you want to speed up development.
 */

const USE_FAST_SOURCE_MAPS = false;

module.exports = {
  entry: './app/main.jsx',
  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  context: __dirname,
  devtool: devMode && USE_FAST_SOURCE_MAPS ?
    'cheap-module-eval-source-map' :
    'source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.json', '*']
  },
  module: {
    rules: [{
      test: /jsx?$/,
      use: [{
        loader: 'babel-loader',
        options: {
          presets: ['react', 'es2015', 'stage-2']
        }
      }]
    }]
  },
  plugins: devMode ? [
    new LiveReloadPlugin({
      appendScriptTag: true
    })
  ] : []
};
<commit_msg>fix weird es2015 error<commit_after>'use strict';

const LiveReloadPlugin = require('webpack-livereload-plugin');
const devMode = process.env.NODE_ENV === 'development';

/**
 * Fast source maps rebuild quickly during development, but only give a link
 * to the line where the error occurred. The stack trace will show the bundled
 * code, not the original code. Keep this on `false` for slower builds but
 * usable stack traces. Set to `true` if you want to speed up development.
 */

const USE_FAST_SOURCE_MAPS = false;

module.exports = {
  entry: './app/main.jsx',
  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  context: __dirname,
  devtool: devMode && USE_FAST_SOURCE_MAPS ?
    'cheap-module-eval-source-map' :
    'source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.json', '*']
  },
  module: {
    rules: [{
      test: /jsx?$/,
      exclude: /node_modules/,
      use: [{
        loader: 'babel-loader',
        options: {
          presets: ['react', 'es2015', 'stage-2']
        }
      }]
    }]
  },
  plugins: devMode ? [
    new LiveReloadPlugin({
      appendScriptTag: true
    })
  ] : []
};
<|endoftext|>


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

const dist = 'dist/';

module.exports = {
  entry: [
    'webpack-dev-server/client?http://localhost:3000/',
    'webpack/hot/dev-server',
    './src/index',
  ],
  output: {
    path: path.join(__dirname, dist),
    publicPath: dist,
    contentBase: dist,
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.s(a|c)ss$/,
        loaders: ['style', 'css', 'sass'],
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
  sassLoader: {
    includePaths: [
      path.resolve('./node_modules/bulma/'),
    ],
  },
};
<commit_msg>Reconfigure webpack<commit_after>const webpack = require('webpack');
const path = require('path');

const dist = 'dist/';

module.exports = {
  entry: [
    'webpack-dev-server/client?http://localhost:3000/',
    'webpack/hot/only-dev-server',
    './src/index',
  ],
  output: {
    path: path.join(__dirname, dist),
    publicPath: 'http://localhost:3000/',
    contentBase: dist,
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.jsx$/,
        loaders: ['react-hot', 'babel-loader'],
        exclude: /node_modules/,
      },
      {
        test: /\.s(a|c)ss$/,
        loaders: ['style', 'css', 'sass'],
      },
      {
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
    modulesDirectories: ['node_modules'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
  sassLoader: {
    includePaths: [
      path.resolve('./node_modules/bulma/'),
    ],
  },
};
<|endoftext|>


<commit_before>"use strict"

const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const CopyWebpackPlugin = require("copy-webpack-plugin")
const WebpackNotifierPlugin = require("webpack-notifier")

module.exports = {
  cache: true,
  entry: [
    "./web/static/js/polyfills/array.find",
    "./web/static/js/polyfills/array.find_index",
    "./web/static/css/app.css",
    "./web/static/js/app.js"
  ],
  output: {
    path: "./priv/static",
    filename: "js/app.js"
  },
  resolve: {
    modules: ["node_modules", __dirname + "/web/static/js"],
    extensions: [".js", ".jsx"],
    alias: {
      "react": "react/dist/react.min.js",
      "redux": "redux/dist/redux.min.js",
      "react-dom": "react-dom/dist/react-dom.min.js",
      "react-redux": "react-redux/dist/react-redux.min.js",
    },
  },
  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      use: [{
        loader: "babel-loader",
        query: {
          cacheDirectory: true
        },
      }],
    }, {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: "style-loader",
        use: [
          {
            loader: 'css-loader',
            options: {
              camelCase: 'only', // remove dashed class names from style object
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]___[hash:base64:5]'
            }
         }
       ]
      }),
    }]
  },
  devtool: "cheap-module-eval-source-map",
  plugins: [
    new WebpackNotifierPlugin({ skipFirstNotification: true }),
    new ExtractTextPlugin({ filename: "css/app.css" }),
    new CopyWebpackPlugin([{ from: "./web/static/assets" }]),
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    }),
  ]
}
<commit_msg>Remove redundant DefinePlugin instantiation<commit_after>"use strict"

const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const CopyWebpackPlugin = require("copy-webpack-plugin")
const WebpackNotifierPlugin = require("webpack-notifier")

module.exports = {
  cache: true,
  entry: [
    "./web/static/js/polyfills/array.find",
    "./web/static/js/polyfills/array.find_index",
    "./web/static/css/app.css",
    "./web/static/js/app.js"
  ],
  output: {
    path: "./priv/static",
    filename: "js/app.js"
  },
  resolve: {
    modules: ["node_modules", __dirname + "/web/static/js"],
    extensions: [".js", ".jsx"],
    alias: {
      "react": "react/dist/react.min.js",
      "redux": "redux/dist/redux.min.js",
      "react-dom": "react-dom/dist/react-dom.min.js",
      "react-redux": "react-redux/dist/react-redux.min.js",
    },
  },
  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      use: [{
        loader: "babel-loader",
        query: {
          cacheDirectory: true
        },
      }],
    }, {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: "style-loader",
        use: [
          {
            loader: 'css-loader',
            options: {
              camelCase: 'only', // remove dashed class names from style object
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]___[hash:base64:5]'
            }
         }
       ]
      }),
    }]
  },
  devtool: "cheap-module-eval-source-map",
  plugins: [
    new WebpackNotifierPlugin({ skipFirstNotification: true }),
    new ExtractTextPlugin({ filename: "css/app.css" }),
    new CopyWebpackPlugin([{ from: "./web/static/assets" }]),
  ]
}
<|endoftext|>