<commit_before>'use strict';

var gulp = require('gulp');
var reactify = require('reactify');
var debowerify = require('debowerify');
var del = require('del');
var handleErrors = require('./util/handleErrors');

// Load plugins
var $ = require('gulp-load-plugins')();

//Styles
gulp.task('styles', function() {
    return gulp.src('app/styles/main.scss')
        .pipe($.rubySass({
            style: 'expanded',
            precision: 10,
            loadPath: ['app/bower_components', 'app/styles']
        }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('dist/styles'))
        .pipe($.size());
});

// Scripts
gulp.task('scripts', function () {
    return gulp.src('app/scripts/app.js')
        .pipe($.browserify({
            insertGlobals: true,
            transform: ['reactify']
        }))
        .on('error', handleErrors)
        .pipe(gulp.dest('dist/scripts'))
        .pipe($.size());
    });

// HTML
gulp.task('html', function () {
    return gulp.src('app/*.html')
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

// Fonts
gulp.task('fonts', function () {
    return gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

// Images
gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe($.size());
});

// Clean
gulp.task('clean', function (cb) {
    del(['dist/styles', 'dist/scripts', 'dist/images'], cb);
});

// Bundle
gulp.task('bundle', ['styles', 'fonts', 'scripts', 'bower'], function(){
    return gulp.src('./app/*.html')
               .pipe($.useref.assets())
               .pipe($.useref.restore())
               .pipe($.useref())
               .pipe(gulp.dest('dist'));
});

// Build
gulp.task('build', ['html', 'bundle']);

// Default task
gulp.task('default', ['clean', 'build']);

// Webserver
gulp.task('serve', function () {
    gulp.src('dist')
        .pipe($.webserver({
            livereload: true,
            port: 9000
        }));
});

// Bower helper
gulp.task('bower', function() {
    gulp.src('app/bower_components/**/*.js', {base: 'app/bower_components'})
        .pipe(gulp.dest('dist/bower_components/'));

});

gulp.task('json', function() {
    gulp.src('app/scripts/json/**/*.json', {base: 'app/scripts'})
        .pipe(gulp.dest('dist/scripts/'));
});

// Watch
gulp.task('watch', ['html', 'bundle', 'serve'], function () {

    // Watch .json files
    gulp.watch('app/scripts/**/*.json', ['json']);

    // Watch .html files
    gulp.watch('app/*.html', ['html']);

    // Watch .scss files
    gulp.watch('app/styles/*.scss', ['styles']);
    gulp.watch('app/styles/*.css', ['styles']);

    // Watch .js files
    gulp.watch('app/scripts/*.js', ['scripts']);

    // Watch image files
    gulp.watch('app/images/**/*', ['images']);
});
<commit_msg>Split style task in gulpfile<commit_after>'use strict';

var gulp = require('gulp');
var reactify = require('reactify');
var debowerify = require('debowerify');
var del = require('del');
var handleErrors = require('./util/handleErrors');

// Load plugins
var $ = require('gulp-load-plugins')();

// Styles
gulp.task('styles', ['sass', 'css']);

// Sass
gulp.task('sass', function() {
    return gulp.src('app/styles/main.scss')
        .pipe($.rubySass({
            style: 'expanded',
            precision: 10,
            loadPath: ['app/bower_components', 'app/styles']
        }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('dist/styles'))
        .pipe($.size());
});

// CSS
gulp.task('css', function() {
    return gulp.src('app/styles/*.css')
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('dist/styles'))
        .pipe($.size());
});

// Scripts
gulp.task('scripts', function () {
    return gulp.src('app/scripts/app.js')
        .pipe($.browserify({
            insertGlobals: true,
            transform: ['reactify']
        }))
        .on('error', handleErrors)
        .pipe(gulp.dest('dist/scripts'))
        .pipe($.size());
    });

// HTML
gulp.task('html', function () {
    return gulp.src('app/*.html')
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

// Fonts
gulp.task('fonts', function () {
    return gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

// Images
gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe($.size());
});

// Clean
gulp.task('clean', function (cb) {
    del(['dist/styles', 'dist/scripts', 'dist/images'], cb);
});

// Bundle
gulp.task('bundle', ['styles', 'fonts', 'scripts', 'bower'], function(){
    return gulp.src('./app/*.html')
               .pipe($.useref.assets())
               .pipe($.useref.restore())
               .pipe($.useref())
               .pipe(gulp.dest('dist'));
});

// Build
gulp.task('build', ['html', 'bundle']);

// Default task
gulp.task('default', ['clean', 'build']);

// Webserver
gulp.task('serve', function () {
    gulp.src('dist')
        .pipe($.webserver({
            livereload: true,
            port: 9000
        }));
});

// Bower helper
gulp.task('bower', function() {
    gulp.src('app/bower_components/**/*.js', {base: 'app/bower_components'})
        .pipe(gulp.dest('dist/bower_components/'));

});

gulp.task('json', function() {
    gulp.src('app/scripts/json/**/*.json', {base: 'app/scripts'})
        .pipe(gulp.dest('dist/scripts/'));
});

// Watch
gulp.task('watch', ['html', 'bundle', 'serve'], function () {

    // Watch .json files
    gulp.watch('app/scripts/**/*.json', ['json']);

    // Watch .html files
    gulp.watch('app/*.html', ['html']);

    // Watch .scss files
    gulp.watch('app/styles/*.scss', ['styles']);
    gulp.watch('app/styles/*.css', ['styles']);

    // Watch .js files
    gulp.watch('app/scripts/*.js', ['scripts']);

    // Watch image files
    gulp.watch('app/images/**/*', ['images']);
});
<|endoftext|>


<commit_before>/**
 * Sourced from: https://gist.github.com/parasyte/9712366
 * Extend a class prototype with the provided mixin descriptors.
 * Designed as a faster replacement for John Resig's Simple Inheritance.
 * @name extend
 * @memberOf external:Object#
 * @function
 * @param {Object[]} mixins... Each mixin is a dictionary of functions, or a
 * previously extended class whose methods will be applied to the target class
 * prototype.
 * @return {Object}
 * @example
 * var Person = Object.extend({
 *     "init" : function (isDancing) {
 *         this.dancing = isDancing;
 *     },
 *     "dance" : function () {
 *         return this.dancing;
 *     }
 * });
 *
 * var Ninja = Person.extend({
 *     "init" : function () {
 *         // Call the super constructor, passing a single argument
 *         this._super(Person, "init", [false]);
 *     },
 *     "dance" : function () {
 *         // Call the overridden dance() method
 *         return this._super(Person, "dance");
 *     },
 *     "swingSword" : function () {
 *         return true;
 *     }
 * });
 *
 * var Pirate = Person.extend(Ninja, {
 *     "init" : function () {
 *         // Call the super constructor, passing a single argument
 *         this._super(Person, "init", [true]);
 *     }
 * });
 *
 * var p = new Person(true);
 * console.log(p.dance()); // => true
 *
 * var n = new Ninja();
 * console.log(n.dance()); // => false
 * console.log(n.swingSword()); // => true
 *
 * var r = new Pirate();
 * console.log(r.dance()); // => true
 * console.log(r.swingSword()); // => true
 *
 * console.log(
 *     p instanceof Person &&
 *     n instanceof Ninja &&
 *     n instanceof Person &&
 *     r instanceof Pirate &&
 *     r instanceof Person
 * ); // => true
 *
 * console.log(r instanceof Ninja); // => false
 */
(function () {
    Object.defineProperty(Object.prototype, "extend", {
        "value" : function () {
            var methods = {};
            var mixins = Array.prototype.slice.call(arguments, 0);

            /**
             * The class constructor which calls the user `init` constructor.
             * @ignore
             */
            function Class() {
                // Call the user constructor
                this.init.apply(this, arguments);
                return this;
            }

            // Apply superClass
            Class.prototype = Object.create(this.prototype);

            // Apply all mixin methods to the class prototype
            mixins.forEach(function (mixin) {
                apply_methods(Class, methods, mixin.__methods__ || mixin);
            });

            // Verify constructor exists
            if (!("init" in Class.prototype)) {
                throw "Object.extend: Class is missing a constructor named `init`";
            }

            // Apply syntactic sugar for accessing methods on super classes
            Object.defineProperty(Class.prototype, "_super", {
                "value" : _super
            });

            // Create a hidden property on the class itself
            // List of methods, used for applying classes as mixins
            Object.defineProperty(Class, "__methods__", {
                "value" : methods
            });

            return Class;
        }
    });

    /**
     * Apply methods to the class prototype.
     * @ignore
     */
    function apply_methods(Class, methods, descriptor) {
        Object.keys(descriptor).forEach(function (method) {
            methods[method] = descriptor[method];

            if (typeof(descriptor[method]) !== "function") {
                throw "Object.extend: Method `" + method + "` is not a function!";
            }

            Object.defineProperty(Class.prototype, method, {
                "configurable" : true,
                "value" : descriptor[method]
            });
        });
    }

    /**
     * Special method that acts as a proxy to the super class.
     * @name _super
     * @ignore
     */
    function _super(superClass, method, args) {
        return superClass.prototype[method].apply(this, args);
    }
})();
<commit_msg>Make error strings more appropriate<commit_after>/**
 * Sourced from: https://gist.github.com/parasyte/9712366
 * Extend a class prototype with the provided mixin descriptors.
 * Designed as a faster replacement for John Resig's Simple Inheritance.
 * @name extend
 * @memberOf external:Object#
 * @function
 * @param {Object[]} mixins... Each mixin is a dictionary of functions, or a
 * previously extended class whose methods will be applied to the target class
 * prototype.
 * @return {Object}
 * @example
 * var Person = Object.extend({
 *     "init" : function (isDancing) {
 *         this.dancing = isDancing;
 *     },
 *     "dance" : function () {
 *         return this.dancing;
 *     }
 * });
 *
 * var Ninja = Person.extend({
 *     "init" : function () {
 *         // Call the super constructor, passing a single argument
 *         this._super(Person, "init", [false]);
 *     },
 *     "dance" : function () {
 *         // Call the overridden dance() method
 *         return this._super(Person, "dance");
 *     },
 *     "swingSword" : function () {
 *         return true;
 *     }
 * });
 *
 * var Pirate = Person.extend(Ninja, {
 *     "init" : function () {
 *         // Call the super constructor, passing a single argument
 *         this._super(Person, "init", [true]);
 *     }
 * });
 *
 * var p = new Person(true);
 * console.log(p.dance()); // => true
 *
 * var n = new Ninja();
 * console.log(n.dance()); // => false
 * console.log(n.swingSword()); // => true
 *
 * var r = new Pirate();
 * console.log(r.dance()); // => true
 * console.log(r.swingSword()); // => true
 *
 * console.log(
 *     p instanceof Person &&
 *     n instanceof Ninja &&
 *     n instanceof Person &&
 *     r instanceof Pirate &&
 *     r instanceof Person
 * ); // => true
 *
 * console.log(r instanceof Ninja); // => false
 */
(function () {
    Object.defineProperty(Object.prototype, "extend", {
        "value" : function () {
            var methods = {};
            var mixins = Array.prototype.slice.call(arguments, 0);

            /**
             * The class constructor which calls the user `init` constructor.
             * @ignore
             */
            function Class() {
                // Call the user constructor
                this.init.apply(this, arguments);
                return this;
            }

            // Apply superClass
            Class.prototype = Object.create(this.prototype);

            // Apply all mixin methods to the class prototype
            mixins.forEach(function (mixin) {
                apply_methods(Class, methods, mixin.__methods__ || mixin);
            });

            // Verify constructor exists
            if (!("init" in Class.prototype)) {
                throw "extend: Class is missing a constructor named `init`";
            }

            // Apply syntactic sugar for accessing methods on super classes
            Object.defineProperty(Class.prototype, "_super", {
                "value" : _super
            });

            // Create a hidden property on the class itself
            // List of methods, used for applying classes as mixins
            Object.defineProperty(Class, "__methods__", {
                "value" : methods
            });

            return Class;
        }
    });

    /**
     * Apply methods to the class prototype.
     * @ignore
     */
    function apply_methods(Class, methods, descriptor) {
        Object.keys(descriptor).forEach(function (method) {
            methods[method] = descriptor[method];

            if (typeof(descriptor[method]) !== "function") {
                throw "extend: Method `" + method + "` is not a function";
            }

            Object.defineProperty(Class.prototype, method, {
                "configurable" : true,
                "value" : descriptor[method]
            });
        });
    }

    /**
     * Special method that acts as a proxy to the super class.
     * @name _super
     * @ignore
     */
    function _super(superClass, method, args) {
        return superClass.prototype[method].apply(this, args);
    }
})();
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const WriteFilePlugin = require('write-file-webpack-plugin')
const AutoDllPlugin = require('autodll-webpack-plugin')
// const ExtractCssChunks = require('extract-css-chunks-webpack-plugin')
const ExtractCssChunks = require('../../extract-css-chunks-webpack-plugin')

module.exports = {
  name: 'client',
  target: 'web',
  // devtool: 'source-map',
  devtool: 'eval',
  entry: [
    'babel-polyfill',
    'fetch-everywhere',
    'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=false&quiet=false&noInfo=false',
    'react-hot-loader/patch',
    path.resolve(__dirname, '../src/index.js')
  ],
  output: {
    filename: '[name].js',
    chunkFilename: '[name].js',
    path: path.resolve(__dirname, '../buildClient'),
    publicPath: '/static/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ExtractCssChunks.extract({
          use: {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[name]__[local]--[hash:base64:5]'
            }
          }
        })
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.css']
  },
  plugins: [
    new WriteFilePlugin(),
    new ExtractCssChunks(),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['bootstrap'], // needed to put webpack bootstrap code before chunks
      filename: '[name].js',
      minChunks: Infinity
    }),

    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    }),
    new AutoDllPlugin({
      context: path.join(__dirname, '..'),
      filename: '[name].js',
      entry: {
        vendor: [
          'react',
          'react-dom',
          'react-redux',
          'redux',
          'history/createBrowserHistory',
          'animated-transition-group',
          'redux-first-router',
          'redux-first-router-link',
          'fetch-everywhere',
          'babel-polyfill',
          'react-hot-loader/lib/AppContainer',
          'redux-devtools-extension/logOnlyInProduction'
        ]
      }
    })
  ]
}
<commit_msg>Replace ExtractCssChunkWebpackPlugin relative path with module path<commit_after>const path = require('path')
const webpack = require('webpack')
const WriteFilePlugin = require('write-file-webpack-plugin')
const AutoDllPlugin = require('autodll-webpack-plugin')
const ExtractCssChunks = require('extract-css-chunks-webpack-plugin')

module.exports = {
  name: 'client',
  target: 'web',
  // devtool: 'source-map',
  devtool: 'eval',
  entry: [
    'babel-polyfill',
    'fetch-everywhere',
    'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=false&quiet=false&noInfo=false',
    'react-hot-loader/patch',
    path.resolve(__dirname, '../src/index.js')
  ],
  output: {
    filename: '[name].js',
    chunkFilename: '[name].js',
    path: path.resolve(__dirname, '../buildClient'),
    publicPath: '/static/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ExtractCssChunks.extract({
          use: {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[name]__[local]--[hash:base64:5]'
            }
          }
        })
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.css']
  },
  plugins: [
    new WriteFilePlugin(),
    new ExtractCssChunks(),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['bootstrap'], // needed to put webpack bootstrap code before chunks
      filename: '[name].js',
      minChunks: Infinity
    }),

    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    }),
    new AutoDllPlugin({
      context: path.join(__dirname, '..'),
      filename: '[name].js',
      entry: {
        vendor: [
          'react',
          'react-dom',
          'react-redux',
          'redux',
          'history/createBrowserHistory',
          'animated-transition-group',
          'redux-first-router',
          'redux-first-router-link',
          'fetch-everywhere',
          'babel-polyfill',
          'react-hot-loader/lib/AppContainer',
          'redux-devtools-extension/logOnlyInProduction'
        ]
      }
    })
  ]
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Turbulenz Limited

var print = function(m)
{
    WScript.Echo(m);
};

var sanitize = function(p)
{
    // print("p: " + p);
    var res = p.replace(/\\/g, "/").toLowerCase();
    // print("res: " + res);
    return res;
};

var relpath = function (path)
{
    var colonIdx = path.indexOf(":");
    if (-1 === colonIdx)
    {
        return path;
    }

    var objShell = WScript.CreateObject("WScript.Shell");
    var cwd = sanitize(objShell.CurrentDirectory);

    if (path.substr(0,1) !== cwd.substr(0,1))
    {
        return path;
    }

    var pathSplit = path.split("/");
    var cwdSplit = cwd.split("/");

    var same = 0;
    while (pathSplit[same] === cwdSplit[same])
    {
        same += 1;
    }

    var relpath = "";
    var dotDots = cwdSplit.length - same;
    while (dotDots)
    {
        relpath += "../";
        dotDots -= 1;
    }

    while (same < pathSplit.length)
    {
        relpath += pathSplit[same] + "/";
        same += 1;
    }

    // print("relpath: " + relpath);
    // print("relpath.substr(-1): " + relpath.substr(relpath.length-1));

    if (relpath.substr(relpath.length-1) === "/")
    {
        relpath = relpath.substr(0, relpath.length-1);
    }

    // print(relpath);
    return relpath;
};

var path = sanitize(WScript.Arguments(0));
print(relpath(path));
<commit_msg>Do some path normalization in relpath.js<commit_after>// Copyright (c) 2015 Turbulenz Limited

var print = function(m)
{
    WScript.Echo(m);
};

var sanitize = function(p)
{
    // print("p: " + p);
    var res = p.replace(/\\/g, "/").toLowerCase();
    res = res.replace(/\/[^\/]+\/\.\.\//g, "/");
    // print("res: " + res);
    return res;
};

var relpath = function (path)
{
    var colonIdx = path.indexOf(":");
    if (-1 === colonIdx)
    {
        return path;
    }

    var objShell = WScript.CreateObject("WScript.Shell");
    var cwd = sanitize(objShell.CurrentDirectory);

    if (path.substr(0,1) !== cwd.substr(0,1))
    {
        return path;
    }

    var pathSplit = path.split("/");
    var cwdSplit = cwd.split("/");

    var same = 0;
    while (pathSplit[same] === cwdSplit[same])
    {
        same += 1;
    }

    var relpath = "";
    var dotDots = cwdSplit.length - same;
    while (dotDots)
    {
        relpath += "../";
        dotDots -= 1;
    }

    while (same < pathSplit.length)
    {
        relpath += pathSplit[same] + "/";
        same += 1;
    }

    // print("relpath: " + relpath);
    // print("relpath.substr(-1): " + relpath.substr(relpath.length-1));

    if (relpath.substr(relpath.length-1) === "/")
    {
        relpath = relpath.substr(0, relpath.length-1);
    }

    // print(relpath);
    return relpath;
};

var path = sanitize(WScript.Arguments(0));
print(relpath(path));
<|endoftext|>


<commit_before>const fs = require("fs");
const path = require("path");
const l = require("lodash");

const CleanCSS = require("clean-css");
const gulp = require("gulp");
const gulpif = require("gulp-if");
const gzip = require("gulp-gzip");

const mustache = require("gulp-mustache");
const rename = require("gulp-rename");
const svgSprite = require("gulp-svg-sprite");

const mkdirp = require("mkdirp");
const rimraf = require("rimraf");
const sass = require("sass");
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')

const paths = {};
paths.resources = "./resources/";
paths.output = "./resources/public/";
paths.build = "./target/build/";
paths.dist = "./target/dist/";
paths.scss = "./resources/styles/**/*.scss";

/***********************************************
 * Helpers
 ***********************************************/

function isProduction() {
  return (process.env.NODE_ENV === 'production');
}

function scssPipeline(options) {
  const write = (_path, data) => {
    return new Promise((resolve, reject) => {
      fs.writeFile(_path, data, function(err) {
        if (err) { reject(err); }
        else { resolve(); }
      });
    });
  };

  const render = (input) => {
    return new Promise((resolve, reject) => {
      sass.render({file: input}, async function(err, result) {
        if (err) {
          console.log(err.formatted);
          reject(err);
        } else {
          resolve(result.css);
        }
      });
    });
  };

  const postprocess = (data, input, output) => {
    return postcss([autoprefixer])
      .process(data, {map: false, from: input, to: output})
  };

  return function(next) {
    const input = options.input;
    const output = options.output;

    return mkdirp(path.dirname(output))
      .then(() => render(input))
      .then((res) => postprocess(res, input, output))
      .then((res) => write(output, res))
      .catch((err) => null)
      .then(() => {
        next();
      });
  };
}

// Templates

function readLocales() {
  const path = __dirname + "/resources/locales.json";
  const content = JSON.parse(fs.readFileSync(path, {encoding: "utf8"}));

  let result = {};
  for (let key of Object.keys(content)) {
    const item = content[key];
    if (l.isString(item)) {
      result[key] = {"en": item};
    } else if (l.isPlainObject(item) && l.isPlainObject(item.translations)) {
      result[key] = item.translations;
    }
  }

  return JSON.stringify(result);
}

function readConfig() {
  const publicURL = process.env.UXBOX_PUBLIC_URL;
  const demoWarn = process.env.UXBOX_DEMO_WARNING;
  const deployDate = process.env.UXBOX_DEPLOY_DATE;
  const deployCommit = process.env.UXBOX_DEPLOY_COMMIT;

  let cfg = {
    demoWarning: demoWarn === "true"
  };

  if (publicURL !== undefined) {
    cfg.publicURL = publicURL;
  }

  if (deployDate !== undefined) {
    cfg.deployDate = deployDate;
  }

  if (deployCommit !== undefined) {
    cfg.deployCommit = deployCommit;
  }

  return JSON.stringify(cfg);
}

function templatePipeline(options) {
  return function() {
    const input = options.input;
    const output = options.output;
    const ts = Math.floor(new Date());

    const locales = readLocales();
    const config = readConfig();

    const tmpl = mustache({
      ts: ts,
      config: JSON.stringify(config),
      translations: JSON.stringify(locales),
    });

    return gulp.src(input)
      .pipe(tmpl)
      .pipe(rename("index.html"))
      .pipe(gulp.dest(output));
  };
}

/***********************************************
 * Generic
 ***********************************************/

gulp.task("scss:main", scssPipeline({
  input: paths.resources + "styles/main.scss",
  output: paths.output + "css/main.css"
}));

gulp.task("scss", gulp.parallel("scss:main"));

gulp.task("svg:sprite", function() {
  return gulp.src(paths.resources + "images/icons/*.svg")
    .pipe(rename({prefix: 'icon-'}))
    .pipe(svgSprite({mode:{symbol: {inline: false}}}))
    .pipe(gulp.dest(paths.output + "images/svg-sprite/"));
});

gulp.task("template:main", templatePipeline({
  input: paths.resources + "templates/index.mustache",
  output: paths.output
}));

gulp.task("templates", gulp.series("template:main"));

/***********************************************
 * Development
 ***********************************************/

gulp.task("dev:clean", function(next) {
  rimraf(paths.output, next);
});

gulp.task("dev:copy:images", function() {
  return gulp.src(paths.resources + "images/**/*")
    .pipe(gulp.dest(paths.output + "images/"));
});

gulp.task("dev:copy:fonts", function() {
  return gulp.src(paths.resources + "fonts/**/*")
    .pipe(gulp.dest(paths.output + "fonts/"));
});

gulp.task("dev:copy", gulp.parallel("dev:copy:images",
                                    "dev:copy:fonts"));

gulp.task("dev:dirs", function(next) {
  mkdirp("./resources/public/css/").then(() => next())
});

gulp.task("watch:main", function() {
  gulp.watch(paths.scss, gulp.series("scss"));
  gulp.watch(paths.resources + "images/**/*",
             gulp.series("svg:sprite",
                         "dev:copy:images"));

  gulp.watch([paths.resources + "templates/*.mustache",
              paths.resources + "locales.json"],
             gulp.series("templates"));
});

gulp.task("watch", gulp.series(
  "dev:dirs",
  gulp.parallel("scss", "templates", "svg:sprite"),
  "dev:copy",
  "watch:main"
));

/***********************************************
 * Production
 ***********************************************/

gulp.task("dist:clean", function(next) {
  rimraf(paths.dist, next);
});

gulp.task("dist:copy", function() {
  return gulp.src(paths.output + "**/*")
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist:gzip", function() {
  return gulp.src(`${paths.dist}**/!(*.gz|*.br|*.jpg|*.png)`)
    .pipe(gzip({gzipOptions: {level: 9}}))
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist", gulp.series(
  "dev:clean",
  "dist:clean",
  gulp.parallel("scss", "templates", "svg:sprite", "dev:copy"),
  "dist:copy"
));
<commit_msg>:fire: Remove unused code from gulpfile.<commit_after>const fs = require("fs");
const path = require("path");
const l = require("lodash");

const CleanCSS = require("clean-css");
const gulp = require("gulp");
const gulpif = require("gulp-if");
const gzip = require("gulp-gzip");

const mustache = require("gulp-mustache");
const rename = require("gulp-rename");
const svgSprite = require("gulp-svg-sprite");

const mkdirp = require("mkdirp");
const rimraf = require("rimraf");
const sass = require("sass");
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')

const paths = {};
paths.resources = "./resources/";
paths.output = "./resources/public/";
paths.dist = "./target/dist/";
paths.scss = "./resources/styles/**/*.scss";

/***********************************************
 * Helpers
 ***********************************************/

function isProduction() {
  return (process.env.NODE_ENV === 'production');
}

function scssPipeline(options) {
  const write = (_path, data) => {
    return new Promise((resolve, reject) => {
      fs.writeFile(_path, data, function(err) {
        if (err) { reject(err); }
        else { resolve(); }
      });
    });
  };

  const render = (input) => {
    return new Promise((resolve, reject) => {
      sass.render({file: input}, async function(err, result) {
        if (err) {
          console.log(err.formatted);
          reject(err);
        } else {
          resolve(result.css);
        }
      });
    });
  };

  const postprocess = (data, input, output) => {
    return postcss([autoprefixer])
      .process(data, {map: false, from: input, to: output})
  };

  return function(next) {
    const input = options.input;
    const output = options.output;

    return mkdirp(path.dirname(output))
      .then(() => render(input))
      .then((res) => postprocess(res, input, output))
      .then((res) => write(output, res))
      .catch((err) => null)
      .then(() => {
        next();
      });
  };
}

// Templates

function readLocales() {
  const path = __dirname + "/resources/locales.json";
  const content = JSON.parse(fs.readFileSync(path, {encoding: "utf8"}));

  let result = {};
  for (let key of Object.keys(content)) {
    const item = content[key];
    if (l.isString(item)) {
      result[key] = {"en": item};
    } else if (l.isPlainObject(item) && l.isPlainObject(item.translations)) {
      result[key] = item.translations;
    }
  }

  return JSON.stringify(result);
}

function readConfig() {
  const publicURL = process.env.UXBOX_PUBLIC_URL;
  const demoWarn = process.env.UXBOX_DEMO_WARNING;
  const deployDate = process.env.UXBOX_DEPLOY_DATE;
  const deployCommit = process.env.UXBOX_DEPLOY_COMMIT;

  let cfg = {
    demoWarning: demoWarn === "true"
  };

  if (publicURL !== undefined) {
    cfg.publicURL = publicURL;
  }

  if (deployDate !== undefined) {
    cfg.deployDate = deployDate;
  }

  if (deployCommit !== undefined) {
    cfg.deployCommit = deployCommit;
  }

  return JSON.stringify(cfg);
}

function templatePipeline(options) {
  return function() {
    const input = options.input;
    const output = options.output;
    const ts = Math.floor(new Date());

    const locales = readLocales();
    const config = readConfig();

    const tmpl = mustache({
      ts: ts,
      config: JSON.stringify(config),
      translations: JSON.stringify(locales),
    });

    return gulp.src(input)
      .pipe(tmpl)
      .pipe(rename("index.html"))
      .pipe(gulp.dest(output));
  };
}

/***********************************************
 * Generic
 ***********************************************/

gulp.task("scss:main", scssPipeline({
  input: paths.resources + "styles/main.scss",
  output: paths.output + "css/main.css"
}));

gulp.task("scss", gulp.parallel("scss:main"));

gulp.task("svg:sprite", function() {
  return gulp.src(paths.resources + "images/icons/*.svg")
    .pipe(rename({prefix: 'icon-'}))
    .pipe(svgSprite({mode:{symbol: {inline: false}}}))
    .pipe(gulp.dest(paths.output + "images/svg-sprite/"));
});

gulp.task("template:main", templatePipeline({
  input: paths.resources + "templates/index.mustache",
  output: paths.output
}));

gulp.task("templates", gulp.series("template:main"));

/***********************************************
 * Development
 ***********************************************/

gulp.task("dev:clean", function(next) {
  rimraf(paths.output, next);
});

gulp.task("dev:copy:images", function() {
  return gulp.src(paths.resources + "images/**/*")
    .pipe(gulp.dest(paths.output + "images/"));
});

gulp.task("dev:copy:fonts", function() {
  return gulp.src(paths.resources + "fonts/**/*")
    .pipe(gulp.dest(paths.output + "fonts/"));
});

gulp.task("dev:copy", gulp.parallel("dev:copy:images",
                                    "dev:copy:fonts"));

gulp.task("dev:dirs", function(next) {
  mkdirp("./resources/public/css/").then(() => next())
});

gulp.task("watch:main", function() {
  gulp.watch(paths.scss, gulp.series("scss"));
  gulp.watch(paths.resources + "images/**/*",
             gulp.series("svg:sprite",
                         "dev:copy:images"));

  gulp.watch([paths.resources + "templates/*.mustache",
              paths.resources + "locales.json"],
             gulp.series("templates"));
});

gulp.task("watch", gulp.series(
  "dev:dirs",
  gulp.parallel("scss", "templates", "svg:sprite"),
  "dev:copy",
  "watch:main"
));

/***********************************************
 * Production
 ***********************************************/

gulp.task("dist:clean", function(next) {
  rimraf(paths.dist, next);
});

gulp.task("dist:copy", function() {
  return gulp.src(paths.output + "**/*")
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist:gzip", function() {
  return gulp.src(`${paths.dist}**/!(*.gz|*.br|*.jpg|*.png)`)
    .pipe(gzip({gzipOptions: {level: 9}}))
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist", gulp.series(
  "dev:clean",
  "dist:clean",
  gulp.parallel("scss", "templates", "svg:sprite", "dev:copy"),
  "dist:copy"
));
<|endoftext|>


<commit_before>require('babel/polyfill');

// Webpack config for development
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var WebpackIsomorphicTools = require('webpack-isomorphic-tools');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = (process.env.HOST || 'localhost');
var port = parseInt(process.env.PORT) + 1 || 3001;

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

var babelrc = fs.readFileSync('./.babelrc');
var babelrcObject = {};

try {
  babelrcObject = JSON.parse(babelrc);
} catch (err) {
  console.error('==>     ERROR: Error parsing your .babelrc.');
  console.error(err);
}

var babelrcObjectDevelopment = babelrcObject.env && babelrcObject.env.development || {};
var babelLoaderQuery = Object.assign({}, babelrcObject, babelrcObjectDevelopment);
delete babelLoaderQuery.env;

babelLoaderQuery.plugins = babelLoaderQuery.plugins || [];
if (babelLoaderQuery.plugins.indexOf('react-transform') < 0) {
  babelLoaderQuery.plugins.push('react-transform');
}

babelLoaderQuery.extra = babelLoaderQuery.extra || {};
if (!babelLoaderQuery.extra['react-transform']) {
  babelLoaderQuery.extra['react-transform'] = {};
}
if (!babelLoaderQuery.extra['react-transform'].transforms) {
  babelLoaderQuery.extra['react-transform'].transforms = [];
}
babelLoaderQuery.extra['react-transform'].transforms.push({
  transform: 'react-transform-hmr',
  imports: ['react'],
  locals: ['module']
});

module.exports = {
  devtool: 'inline-source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': [
      'webpack-hot-middleware/client?path=http://' + host + ':' + port + '/__webpack_hmr',
      'bootstrap-sass!./src/theme/bootstrap.config.js',
      'font-awesome-webpack!./src/theme/font-awesome.config.js',
      './src/client.js'
    ]
  },
  output: {
    path: assetsPath,
    filename: '[name]-[hash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'http://' + host + ':' + port + '/dist/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel?' + JSON.stringify(babelLoaderQuery), 'eslint-loader']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.less$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' },
      { test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  progress: true,
  resolve: {
    modulesDirectories: [
      'src',
      'node_modules'
    ],
    extensions: ['', '.json', '.js', '.jsx']
  },
  plugins: [
    // hot reload
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(/webpack-stats\.json$/),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: true  // <-------- DISABLE redux-devtools HERE
    }),
    webpackIsomorphicToolsPlugin.development()
  ]
};
<commit_msg>disabled devtools for now<commit_after>require('babel/polyfill');

// Webpack config for development
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var WebpackIsomorphicTools = require('webpack-isomorphic-tools');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = (process.env.HOST || 'localhost');
var port = parseInt(process.env.PORT) + 1 || 3001;

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

var babelrc = fs.readFileSync('./.babelrc');
var babelrcObject = {};

try {
  babelrcObject = JSON.parse(babelrc);
} catch (err) {
  console.error('==>     ERROR: Error parsing your .babelrc.');
  console.error(err);
}

var babelrcObjectDevelopment = babelrcObject.env && babelrcObject.env.development || {};
var babelLoaderQuery = Object.assign({}, babelrcObject, babelrcObjectDevelopment);
delete babelLoaderQuery.env;

babelLoaderQuery.plugins = babelLoaderQuery.plugins || [];
if (babelLoaderQuery.plugins.indexOf('react-transform') < 0) {
  babelLoaderQuery.plugins.push('react-transform');
}

babelLoaderQuery.extra = babelLoaderQuery.extra || {};
if (!babelLoaderQuery.extra['react-transform']) {
  babelLoaderQuery.extra['react-transform'] = {};
}
if (!babelLoaderQuery.extra['react-transform'].transforms) {
  babelLoaderQuery.extra['react-transform'].transforms = [];
}
babelLoaderQuery.extra['react-transform'].transforms.push({
  transform: 'react-transform-hmr',
  imports: ['react'],
  locals: ['module']
});

module.exports = {
  devtool: 'inline-source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': [
      'webpack-hot-middleware/client?path=http://' + host + ':' + port + '/__webpack_hmr',
      'bootstrap-sass!./src/theme/bootstrap.config.js',
      'font-awesome-webpack!./src/theme/font-awesome.config.js',
      './src/client.js'
    ]
  },
  output: {
    path: assetsPath,
    filename: '[name]-[hash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'http://' + host + ':' + port + '/dist/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel?' + JSON.stringify(babelLoaderQuery), 'eslint-loader']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.less$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' },
      { test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  progress: true,
  resolve: {
    modulesDirectories: [
      'src',
      'node_modules'
    ],
    extensions: ['', '.json', '.js', '.jsx']
  },
  plugins: [
    // hot reload
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(/webpack-stats\.json$/),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: false  // <-------- DISABLE redux-devtools HERE
    }),
    webpackIsomorphicToolsPlugin.development()
  ]
};
<|endoftext|>


<commit_before>var xtend = require('xtend');
var knownHosts = require('known-hosts');
var read = require('read');
var path = require('path');
var ui = require('../lib/ui');
var remotes = require('../lib/remotes');
var select = require('select-keys');
var client = require('../');

var isKnownHost = function(host, fingerprint) {
	host = host.split('@').pop();
	return knownHosts.some(function(entry) {
		return entry.host === host && entry.fingerprint === fingerprint;
	});
};

module.exports = function(cmd, remote, url, opts) {
	var conf = xtend(remotes.read(remote) || {}, opts);

	var remove = function() {
		if (!remote) return ui.error('Remote is required');

		var r = remotes.read(remote);
		if (!r) return ui.error('Remote not found');
		remotes.remove(remote);
		ui.success('Remote was removed');
	};

	var list = function() {
		var l = remotes.list();

		if (!l.length) return ui.empty();

		l.forEach(function(name) {
			ui.tree({
				label: name,
				leaf: remotes.read(name)
			});
		});
	};

	var add = function() {
		if (!remote) return ui.error('Remote is required');
		if (!url) return ui.error('Remote url is required');
		if (conf.key && conf.key.indexOf(path.resolve('/')) !== 0) conf.key = path.join(process.cwd(), conf.key);

		var oldFingerprint = conf.fingerprint;
		delete conf.fingerprint;

		var c = client(url, conf);

		c.on('verify', function(fingerprint, cb) {
			conf.fingerprint = fingerprint;

			var next = function(err) {
				console.log('');
				cb(err);
			};

			if (fingerprint === oldFingerprint || opts.yes) {
				console.log('Remote is already verified.')
				return next();
			}
			if (isKnownHost(url, fingerprint)) {
				console.log('Remote is verified by ~/.ssh/known_hosts.');
				return next();
			}

			console.log('Remote rsa fingerprint is: '+fingerprint);
			read({prompt: 'Do you want to continue (yes/no)? '}, function onanswer(err, answer) {
				if (err) return ui.error(err);
				if (answer === 'no') return next(new Error('Host could not be verified'));
				if (answer === 'yes') return next();
				read({prompt:'Please type \'yes\' or \'no\': '}, onanswer);
			});
		});

		c.list(function(err) {
			if (err) return ui.error(err);

			conf.url = url;
			conf = select(conf, ['url', 'key', 'passphrase', 'fingerprint']);

			ui.tree({
				label: remote,
				leaf: conf
			});

			remotes.write(remote, conf);
		});
	};

	if (cmd === 'add') return add();
	if (cmd === 'remove') return remove();

	list();
};<commit_msg>fixed key file parsing<commit_after>var xtend = require('xtend');
var knownHosts = require('known-hosts');
var read = require('read');
var path = require('path');
var select = require('select-keys');
var fs = require('fs');
var ui = require('../lib/ui');
var remotes = require('../lib/remotes');
var client = require('../');

var isKnownHost = function(host, fingerprint) {
	host = host.split('@').pop();
	return knownHosts.some(function(entry) {
		return entry.host === host && entry.fingerprint === fingerprint;
	});
};

module.exports = function(cmd, remote, url, opts) {
	var conf = xtend(remotes.read(remote) || {}, opts);

	var remove = function() {
		if (!remote) return ui.error('Remote is required');

		var r = remotes.read(remote);
		if (!r) return ui.error('Remote not found');
		remotes.remove(remote);
		ui.success('Remote was removed');
	};

	var list = function() {
		var l = remotes.list();

		if (!l.length) return ui.empty();

		l.forEach(function(name) {
			ui.tree({
				label: name,
				leaf: remotes.read(name)
			});
		});
	};

	var add = function() {
		if (!remote) return ui.error('Remote is required');
		if (!url) return ui.error('Remote url is required');
		if (conf.key && !fs.existsSync(conf.key)) return ui.error('Key file does not exist');
		if (conf.key) conf.key = fs.realpathSync(conf.key);

		var oldFingerprint = conf.fingerprint;
		delete conf.fingerprint;

		var c = client(url, conf);

		c.on('verify', function(fingerprint, cb) {
			conf.fingerprint = fingerprint;

			var next = function(err) {
				console.log('');
				cb(err);
			};

			if (fingerprint === oldFingerprint || opts.yes) {
				console.log('Remote is already verified.')
				return next();
			}
			if (isKnownHost(url, fingerprint)) {
				console.log('Remote is verified by ~/.ssh/known_hosts.');
				return next();
			}

			console.log('Remote rsa fingerprint is: '+fingerprint);
			read({prompt: 'Do you want to continue (yes/no)? '}, function onanswer(err, answer) {
				if (err) return ui.error(err);
				if (answer === 'no') return next(new Error('Host could not be verified'));
				if (answer === 'yes') return next();
				read({prompt:'Please type \'yes\' or \'no\': '}, onanswer);
			});
		});

		c.list(function(err) {
			if (err) return ui.error(err);

			conf.url = url;
			conf = select(conf, ['url', 'key', 'passphrase', 'fingerprint']);

			ui.tree({
				label: remote,
				leaf: conf
			});

			remotes.write(remote, conf);
		});
	};

	if (cmd === 'add') return add();
	if (cmd === 'remove') return remove();

	list();
};<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

// See https://docusaurus.io/docs/site-config.html for all the possible
// site configuration options.

/* List of projects/orgs using your project for the users page */
const users = [
  {
    caption: 'User1',
    // You will need to prepend the image path with your baseUrl
    // if it is not '/', like: '/test-site/img/docusaurus.svg'.
    image: '/img/docusaurus.svg',
    infoLink: 'https://www.facebook.com',
    pinned: true,
  },
];

const siteConfig = {
  title: 'web1992\'s blog' /* title for your website */,
  tagline: 'Read Write Share',
  url: 'https://your-docusaurus-test-site.com' /* your website url */,
  baseUrl: '/' /* base url for your project */,
  // For github.io type URLs, you would set the url and baseUrl like:
  //   url: 'https://facebook.github.io',
  //   baseUrl: '/test-site/',

  // Used for publishing and more
  projectName: 'web1992-blog',
  organizationName: 'web1992',
  // For top-level user or org sites, the organization is still the same.
  // e.g., for the https://JoelMarcey.github.io site, it would be set like...
  //   organizationName: 'JoelMarcey'

  // For no header links in the top nav bar -> headerLinks: [],
  headerLinks: [
    // { doc: 'doc1', label: 'Docs' },
    // { doc: 'doc4', label: 'API' },
    // { page: 'help', label: 'Help' },
    { blog: true, label: 'Blog' },
    // Links to href destination
    { href: "https://github.com/web1992", label: "GitHub" },
    { page: 'about', label: 'About' },
    { search: true }
  ],

  blogSidebarTitle: { default: 'Recent posts', all: 'All' },
  //blogSidebarCount: 'ALL',
  blogSidebarCount:20,
  // If you have users set above, you add it here:
  users,

  /* path to images for header/footer */
  headerIcon: 'img/docusaurus.svg',
  footerIcon: 'img/docusaurus.svg',
  favicon: 'img/favicon.png',

  /* colors for website */
  colors: {
    primaryColor: '#4285f4',
    secondaryColor: '#205C3B',
  },

  /* custom fonts for website */
  /*fonts: {
    myFont: [
      "Times New Roman",
      "Serif"
    ],
    myOtherFont: [
      "-apple-system",
      "system-ui"
    ]
  },*/

  // This copyright info is used in /core/Footer.js and blog rss/atom feeds.
  copyright:
    'Copyright © ' +
    new Date().getFullYear() +
    ' 京ICP备15055486号',

  highlight: {
    // Highlight.js theme to use for syntax highlighting in code blocks
    // theme: 'default',
    theme: 'vs2015',
  },

  // Add custom scripts here that would be placed in <script> tags
  scripts: ['https://buttons.github.io/buttons.js'],

  /* On page navigation for the current documentation page */
  onPageNav: 'separate',

  /* Open Graph and Twitter card images */
  ogImage: 'img/docusaurus.png',
  twitterImage: 'img/docusaurus.png',

  // You may provide arbitrary config keys to be used as needed by your
  // template. For example, if you need your repo's URL...
  //   repoUrl: 'https://github.com/facebook/test-site',
};

module.exports = siteConfig;
<commit_msg>fix headerLinks<commit_after>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

// See https://docusaurus.io/docs/site-config.html for all the possible
// site configuration options.

/* List of projects/orgs using your project for the users page */
const users = [
  {
    caption: 'User1',
    // You will need to prepend the image path with your baseUrl
    // if it is not '/', like: '/test-site/img/docusaurus.svg'.
    image: '/img/docusaurus.svg',
    infoLink: 'https://www.facebook.com',
    pinned: true,
  },
];

const siteConfig = {
  title: 'web1992\'s blog' /* title for your website */,
  tagline: 'Read Write Share',
  url: 'https://your-docusaurus-test-site.com' /* your website url */,
  baseUrl: '/' /* base url for your project */,
  // For github.io type URLs, you would set the url and baseUrl like:
  //   url: 'https://facebook.github.io',
  //   baseUrl: '/test-site/',

  // Used for publishing and more
  projectName: 'web1992-blog',
  organizationName: 'web1992',
  // For top-level user or org sites, the organization is still the same.
  // e.g., for the https://JoelMarcey.github.io site, it would be set like...
  //   organizationName: 'JoelMarcey'

  // For no header links in the top nav bar -> headerLinks: [],
  headerLinks: [
    // { doc: 'doc1', label: 'Docs' },
    // { doc: 'doc4', label: 'API' },
    // { page: 'help', label: 'Help' },
    { blog: true, label: 'Blog' },
    { page: 'about', label: 'About' },
    // Links to href destination
    { href: "https://github.com/web1992", label: "GitHub" },
    { search: true }
  ],

  blogSidebarTitle: { default: 'Recent posts', all: 'All' },
  //blogSidebarCount: 'ALL',
  blogSidebarCount:20,
  // If you have users set above, you add it here:
  users,

  /* path to images for header/footer */
  headerIcon: 'img/docusaurus.svg',
  footerIcon: 'img/docusaurus.svg',
  favicon: 'img/favicon.png',

  /* colors for website */
  colors: {
    primaryColor: '#4285f4',
    secondaryColor: '#205C3B',
  },

  /* custom fonts for website */
  /*fonts: {
    myFont: [
      "Times New Roman",
      "Serif"
    ],
    myOtherFont: [
      "-apple-system",
      "system-ui"
    ]
  },*/

  // This copyright info is used in /core/Footer.js and blog rss/atom feeds.
  copyright:
    'Copyright © ' +
    new Date().getFullYear() +
    ' 京ICP备15055486号',

  highlight: {
    // Highlight.js theme to use for syntax highlighting in code blocks
    // theme: 'default',
    theme: 'vs2015',
  },

  // Add custom scripts here that would be placed in <script> tags
  scripts: ['https://buttons.github.io/buttons.js'],

  /* On page navigation for the current documentation page */
  onPageNav: 'separate',

  /* Open Graph and Twitter card images */
  ogImage: 'img/docusaurus.png',
  twitterImage: 'img/docusaurus.png',

  // You may provide arbitrary config keys to be used as needed by your
  // template. For example, if you need your repo's URL...
  //   repoUrl: 'https://github.com/facebook/test-site',
};

module.exports = siteConfig;
<|endoftext|>


<commit_before>/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable no-unused-vars, no-restricted-globals */

'use strict';

var pdfjsVersion =
  typeof PDFJSDev !== 'undefined' ? PDFJSDev.eval('BUNDLE_VERSION') : void 0;
var pdfjsBuild =
  typeof PDFJSDev !== 'undefined' ? PDFJSDev.eval('BUNDLE_BUILD') : void 0;

var pdfjsSharedUtil = require('./shared/util.js');
var pdfjsDisplayAPI = require('./display/api.js');
var pdfjsDisplayTextLayer = require('./display/text_layer.js');
var pdfjsDisplayAnnotationLayer = require('./display/annotation_layer.js');
var pdfjsDisplayDOMUtils = require('./display/dom_utils.js');
var pdfjsDisplaySVG = require('./display/svg.js');
let pdfjsDisplayWorkerOptions = require('./display/worker_options.js');
let pdfjsDisplayAPICompatibility = require('./display/api_compatibility.js');

if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {
  const isNodeJS = require('./shared/is_node.js');
  if (isNodeJS()) {
    let PDFNodeStream = require('./display/node_stream.js').PDFNodeStream;
    pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
      return new PDFNodeStream(params);
    });
  } else if (typeof Response !== 'undefined' && 'body' in Response.prototype &&
             typeof ReadableStream !== 'undefined') {
    let PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;
    pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
      return new PDFFetchStream(params);
    });
  } else {
    let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;
    pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
      return new PDFNetworkStream(params);
    });
  }
} else if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('CHROME')) {
  let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;
  let PDFFetchStream;
  let isChromeWithFetchCredentials = function() {
    // fetch does not include credentials until Chrome 61.0.3138.0 and later.
    // https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707
    try {
      // Indexed properties on window are read-only in Chrome 61.0.3151.0+
      // https://chromium.googlesource.com/chromium/src.git/+/58ab4a971b06dec13e4edf9de8382ca6847f6190
      window[999] = 123; // should throw. Note: JS strict mode MUST be enabled.
      delete window[999];
      return false;
    } catch (e) {
      return true;
    }
  };
  if (typeof Response !== 'undefined' && 'body' in Response.prototype &&
      typeof ReadableStream !== 'undefined' && isChromeWithFetchCredentials()) {
    PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;
  }
  pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
    if (PDFFetchStream && /^https?:/i.test(params.url)) {
      // "fetch" is only supported for http(s), not file/ftp.
      return new PDFFetchStream(params);
    }
    return new PDFNetworkStream(params);
  });
}

exports.build = pdfjsDisplayAPI.build;
exports.version = pdfjsDisplayAPI.version;
exports.getDocument = pdfjsDisplayAPI.getDocument;
exports.LoopbackPort = pdfjsDisplayAPI.LoopbackPort;
exports.PDFDataRangeTransport = pdfjsDisplayAPI.PDFDataRangeTransport;
exports.PDFWorker = pdfjsDisplayAPI.PDFWorker;
exports.renderTextLayer = pdfjsDisplayTextLayer.renderTextLayer;
exports.AnnotationLayer = pdfjsDisplayAnnotationLayer.AnnotationLayer;
exports.createPromiseCapability = pdfjsSharedUtil.createPromiseCapability;
exports.PasswordResponses = pdfjsSharedUtil.PasswordResponses;
exports.InvalidPDFException = pdfjsSharedUtil.InvalidPDFException;
exports.MissingPDFException = pdfjsSharedUtil.MissingPDFException;
exports.SVGGraphics = pdfjsDisplaySVG.SVGGraphics;
exports.NativeImageDecoding = pdfjsSharedUtil.NativeImageDecoding;
exports.UnexpectedResponseException =
  pdfjsSharedUtil.UnexpectedResponseException;
exports.OPS = pdfjsSharedUtil.OPS;
exports.VerbosityLevel = pdfjsSharedUtil.VerbosityLevel;
exports.UNSUPPORTED_FEATURES = pdfjsSharedUtil.UNSUPPORTED_FEATURES;
exports.createValidAbsoluteUrl = pdfjsSharedUtil.createValidAbsoluteUrl;
exports.createObjectURL = pdfjsSharedUtil.createObjectURL;
exports.removeNullCharacters = pdfjsSharedUtil.removeNullCharacters;
exports.shadow = pdfjsSharedUtil.shadow;
exports.Util = pdfjsSharedUtil.Util;
exports.ReadableStream = pdfjsSharedUtil.ReadableStream;
exports.URL = pdfjsSharedUtil.URL;
exports.RenderingCancelledException =
  pdfjsDisplayDOMUtils.RenderingCancelledException;
exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl;
exports.LinkTarget = pdfjsDisplayDOMUtils.LinkTarget;
exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes;
exports.loadScript = pdfjsDisplayDOMUtils.loadScript;
exports.GlobalWorkerOptions = pdfjsDisplayWorkerOptions.GlobalWorkerOptions;
exports.apiCompatibilityParams =
  pdfjsDisplayAPICompatibility.apiCompatibilityParams;
<commit_msg>Export `CMapCompressionType` and `PermissionFlag` on the `pdfjsLib` object (issue 10148, PR 10033 follow-up)<commit_after>/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable no-unused-vars, no-restricted-globals */

'use strict';

var pdfjsVersion =
  typeof PDFJSDev !== 'undefined' ? PDFJSDev.eval('BUNDLE_VERSION') : void 0;
var pdfjsBuild =
  typeof PDFJSDev !== 'undefined' ? PDFJSDev.eval('BUNDLE_BUILD') : void 0;

var pdfjsSharedUtil = require('./shared/util.js');
var pdfjsDisplayAPI = require('./display/api.js');
var pdfjsDisplayTextLayer = require('./display/text_layer.js');
var pdfjsDisplayAnnotationLayer = require('./display/annotation_layer.js');
var pdfjsDisplayDOMUtils = require('./display/dom_utils.js');
var pdfjsDisplaySVG = require('./display/svg.js');
let pdfjsDisplayWorkerOptions = require('./display/worker_options.js');
let pdfjsDisplayAPICompatibility = require('./display/api_compatibility.js');

if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {
  const isNodeJS = require('./shared/is_node.js');
  if (isNodeJS()) {
    let PDFNodeStream = require('./display/node_stream.js').PDFNodeStream;
    pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
      return new PDFNodeStream(params);
    });
  } else if (typeof Response !== 'undefined' && 'body' in Response.prototype &&
             typeof ReadableStream !== 'undefined') {
    let PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;
    pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
      return new PDFFetchStream(params);
    });
  } else {
    let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;
    pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
      return new PDFNetworkStream(params);
    });
  }
} else if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('CHROME')) {
  let PDFNetworkStream = require('./display/network.js').PDFNetworkStream;
  let PDFFetchStream;
  let isChromeWithFetchCredentials = function() {
    // fetch does not include credentials until Chrome 61.0.3138.0 and later.
    // https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707
    try {
      // Indexed properties on window are read-only in Chrome 61.0.3151.0+
      // https://chromium.googlesource.com/chromium/src.git/+/58ab4a971b06dec13e4edf9de8382ca6847f6190
      window[999] = 123; // should throw. Note: JS strict mode MUST be enabled.
      delete window[999];
      return false;
    } catch (e) {
      return true;
    }
  };
  if (typeof Response !== 'undefined' && 'body' in Response.prototype &&
      typeof ReadableStream !== 'undefined' && isChromeWithFetchCredentials()) {
    PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;
  }
  pdfjsDisplayAPI.setPDFNetworkStreamFactory((params) => {
    if (PDFFetchStream && /^https?:/i.test(params.url)) {
      // "fetch" is only supported for http(s), not file/ftp.
      return new PDFFetchStream(params);
    }
    return new PDFNetworkStream(params);
  });
}

exports.build = pdfjsDisplayAPI.build;
exports.version = pdfjsDisplayAPI.version;
exports.getDocument = pdfjsDisplayAPI.getDocument;
exports.LoopbackPort = pdfjsDisplayAPI.LoopbackPort;
exports.PDFDataRangeTransport = pdfjsDisplayAPI.PDFDataRangeTransport;
exports.PDFWorker = pdfjsDisplayAPI.PDFWorker;
exports.renderTextLayer = pdfjsDisplayTextLayer.renderTextLayer;
exports.AnnotationLayer = pdfjsDisplayAnnotationLayer.AnnotationLayer;
exports.createPromiseCapability = pdfjsSharedUtil.createPromiseCapability;
exports.PasswordResponses = pdfjsSharedUtil.PasswordResponses;
exports.InvalidPDFException = pdfjsSharedUtil.InvalidPDFException;
exports.MissingPDFException = pdfjsSharedUtil.MissingPDFException;
exports.SVGGraphics = pdfjsDisplaySVG.SVGGraphics;
exports.NativeImageDecoding = pdfjsSharedUtil.NativeImageDecoding;
exports.CMapCompressionType = pdfjsSharedUtil.CMapCompressionType;
exports.PermissionFlag = pdfjsSharedUtil.PermissionFlag;
exports.UnexpectedResponseException =
  pdfjsSharedUtil.UnexpectedResponseException;
exports.OPS = pdfjsSharedUtil.OPS;
exports.VerbosityLevel = pdfjsSharedUtil.VerbosityLevel;
exports.UNSUPPORTED_FEATURES = pdfjsSharedUtil.UNSUPPORTED_FEATURES;
exports.createValidAbsoluteUrl = pdfjsSharedUtil.createValidAbsoluteUrl;
exports.createObjectURL = pdfjsSharedUtil.createObjectURL;
exports.removeNullCharacters = pdfjsSharedUtil.removeNullCharacters;
exports.shadow = pdfjsSharedUtil.shadow;
exports.Util = pdfjsSharedUtil.Util;
exports.ReadableStream = pdfjsSharedUtil.ReadableStream;
exports.URL = pdfjsSharedUtil.URL;
exports.RenderingCancelledException =
  pdfjsDisplayDOMUtils.RenderingCancelledException;
exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl;
exports.LinkTarget = pdfjsDisplayDOMUtils.LinkTarget;
exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes;
exports.loadScript = pdfjsDisplayDOMUtils.loadScript;
exports.GlobalWorkerOptions = pdfjsDisplayWorkerOptions.GlobalWorkerOptions;
exports.apiCompatibilityParams =
  pdfjsDisplayAPICompatibility.apiCompatibilityParams;
<|endoftext|>


<commit_before>'use strict';
var Builder = require('buffer-builder'),
    DescribedType = require('./types/described_type'),
    errors = require('./errors'),
    codec = require('./codec'),
    debug = require('debug')('amqp10:framing'),
    trace = require('debug')('amqp10:trace'),
    constants = require('./constants'),
    defineComposite = require('./types/composite_type').defineComposite,
    terminus = require('./types/terminus'),
    util = require('util');

var frames = module.exports = {};
var framesByDescriptor = {};

var FrameType = { AMQP: 0x00, SASL: 0x01 };
frames.Frame = function(type) { this.type = type; };
frames.AMQPFrame = function(channel) {
  frames.AMQPFrame.super_.call(this, constants.frameType.amqp);
  this.channel = channel || 0;
};
util.inherits(frames.AMQPFrame, frames.Frame);

frames.SaslFrame = function() {
  frames.SaslFrame.super_.call(this, constants.frameType.sasl);
};
util.inherits(frames.SaslFrame, frames.Frame);

frames.writeFrame = function(frame, stream, options, callback) {
  if (!(frame instanceof frames.Frame)) {
    throw new errors.EncodingError(frame, 'unknown frame type');
  }

  options = options || { verbose: true };
  if (callback === undefined && typeof options === 'function') {
    callback = options;
  }

  var builder = new Builder();
  builder.appendUInt32BE(0); // size placeholder
  builder.appendUInt8(2);  // doff, no extended headers
  builder.appendUInt8(frame.type);
  if (frame instanceof frames.AMQPFrame) {
    builder.appendUInt16BE(frame.channel);
  } else {
    builder.appendUInt16BE(0);
  }

  var performative = frame.toDescribedType();
  if (performative !== null && performative !== undefined) {
    codec.encode(performative, builder);
    if (frame instanceof frames.TransferFrame) {
      if (frame.payload !== undefined) builder.appendBuffer(frame.payload);
    }
  }

  var buffer = builder.get();
  buffer.writeUInt32BE(buffer.length, 0);
  if (options.verbose) {
    debug('=>', frame);
    trace('raw: [' + buffer.toString('hex') + ']');
  }

  stream.write(buffer, callback);
};

frames.readFrame = function(buffer) {
  if (buffer.length < 8) return undefined;

  var sizeAndDoff = buffer.slice(0, 8);
  var size = sizeAndDoff.readUInt32BE(0);
  var doff = sizeAndDoff.readUInt8(4);
  if (doff !== 2) throw new errors.MalformedHeaderError('Invalid DOFF');
  if (size > buffer.length) return undefined;

  var frameType = sizeAndDoff[5];
  if (frameType !== FrameType.AMQP && frameType !== FrameType.SASL) {
    throw new errors.NotImplementedError('Unsupported frame type: ' + frameType);
  }

  // actually consume the bytes now that we have no errors
  buffer.consume(8);

  var payloadSize = size - (doff * 4);
  if (payloadSize <= 0) {
    // @todo: this is probably a heartbeat frame, but what if its not?
    debug('<= (EMPTY FRAME)');
    trace('raw: [' + sizeAndDoff.toString('hex') + ']');
    return;
  }

  var xHeaderSize = (doff * 4) - 8;
  if (xHeaderSize > 0) {
    var xHeaderBuf = buffer.slice(0, xHeaderSize);
    buffer.consume(xHeaderSize);

    // @todo: Process x-header
    debug('received extended header');
    trace('raw: [' + xHeaderBuf.toString('hex') + ']');
  }

  // read payload
  var payloadBuffer = buffer.slice(0, payloadSize);
  buffer.consume(payloadSize);

  // decode payload
  var decodedPayload = codec.decode(payloadBuffer, 0);
  if (!decodedPayload) {
    throw new errors.MalformedPayloadError('Unable to parse frame payload [' + payloadBuffer.toString('hex') + ']');
  }

  if (!(decodedPayload[0] instanceof DescribedType)) {
    throw new errors.MalformedPayloadError('Expected DescribedType from AMQP Payload, but received ' + JSON.stringify(decodedPayload[0]));
  }

  // read frame
  var channel = sizeAndDoff.readUInt16BE(6); // Bytes 6 & 7 are channel
  var messageBuffer = payloadBuffer.slice(decodedPayload[1]);

  var described = decodedPayload[0];
  if (!framesByDescriptor.hasOwnProperty(described.descriptor)) {
    throw new errors.MalformedPayloadError('Unknown frame descriptor: ' + described.descriptor);
  }

  var frame = new framesByDescriptor[described.descriptor](described);
  if (messageBuffer.length) frame.payload = messageBuffer;
  if (frameType === FrameType.AMQP) {
    frame.channel = channel;
  }

  debug('<=', frame);
  trace('raw: [' + payloadBuffer.toString('hex') + ']');
  return frame;
};

function defineFrame(type, definition) {
  var FrameBase = (type === FrameType.AMQP) ? frames.AMQPFrame : frames.SaslFrame;
  var Frame = defineComposite(FrameBase, definition);
  framesByDescriptor[Frame.descriptor.code] = Frame;
  framesByDescriptor[Frame.descriptor.name] = Frame;
  return Frame;
}

// restricted type helpers
function role(value) {
  if (typeof value === 'boolean')
    return value;

  if (value !== 'sender' && value !== 'receiver')
    throw new errors.EncodingError(value, 'invalid role');
  return (value === 'sender') ? false : true;
}

var ReceiverSettleModes = [ 'first', 'second', 'auto', 'settle' ];
function receiverSettleMode(value) {
  if (typeof value === 'number' || value instanceof Number)
    return value;

  if (ReceiverSettleModes.indexOf(value) === -1)
    throw new errors.EncodingError(value, 'invalid receiver settle mode');
  return (value === 'first' || value === 'auto') ? 0 : 1;
}

function senderSettleMode(value) {
  if (typeof value === 'number' || value instanceof Number)
    return value;

  if (value !== 'unsettled' && value !== 'settled' && value !== 'mixed')
    throw new errors.EncodingError(value, 'invalid sender settle mode');

  if (value === 'unsettled') return 0;
  else if (value === 'settled') return 1;
  return 2;
}

// AMQP frames
frames.OpenFrame = defineFrame(FrameType.AMQP, {
  name: 'open', code: 0x10,
  fields: [
    { name: 'containerId', type: 'string', mandatory: true },
    { name: 'hostname', type: 'string' },
    { name: 'maxFrameSize', type: 'uint', default: constants.defaultMaxFrameSize },
    { name: 'channelMax', type: 'ushort', default: constants.defaultChannelMax },
    { name: 'idleTimeout', type: 'milliseconds', default: constants.defaultIdleTimeout },
    { name: 'outgoingLocales', type: 'ietf-language-tag',
      multiple: true, default: constants.defaultOutgoingLocales },
    { name: 'incomingLocales', type: 'ietf-language-tag',
      multiple: true, default: constants.defaultIncomingLocales },
    { name: 'offeredCapabilities', type: 'symbol', multiple: true },
    { name: 'desiredCapabilities', type: 'symbol', multiple: true },
    { name: 'properties', type: 'fields', default: {} }
  ]
});

frames.BeginFrame = defineFrame(FrameType.AMQP, {
  name: 'begin', code: 0x11,
  fields: [
    { name: 'remoteChannel', type: 'ushort' },
    { name: 'nextOutgoingId', type: 'transfer-number', mandatory: true },
    { name: 'incomingWindow', type: 'uint', mandatory: true },
    { name: 'outgoingWindow', type: 'uint', mandatory: true },
    { name: 'handleMax', type: 'handle', default: constants.defaultHandleMax },
    { name: 'offeredCapabilities', type: 'symbol', multiple: true },
    { name: 'desiredCapabilities', type: 'symbol', multiple: true },
    { name: 'properties', type: 'fields', default: {} }
  ]
});

frames.AttachFrame = defineFrame(FrameType.AMQP, {
  name: 'attach', code: 0x12,
  fields: [
    { name: 'name', type: 'string', mandatory: true },
    { name: 'handle', type: 'handle', mandatory: true },
    { name: 'role', type: 'boolean', requires: role, mandatory: true },
    { name: 'sndSettleMode', type: 'ubyte', requires: senderSettleMode, default: 'mixed' },
    { name: 'rcvSettleMode', type: 'ubyte', requires: receiverSettleMode, default: 'auto' },
    { name: 'source', type: '*', requires: terminus.Source },
    { name: 'target', type: '*', requires: terminus.Target },
    { name: 'unsettled', type: 'map', default: {} },
    { name: 'incompleteUnsettled', type: 'boolean', default: false },
    { name: 'initialDeliveryCount', type: 'sequence-no' },
    { name: 'maxMessageSize', type: 'ulong', default: 0 },
    { name: 'offeredCapabilities', type: 'symbol', multiple: true },
    { name: 'desiredCapabilities', type: 'symbol', multiple: true },
    { name: 'properties', type: 'fields', default: {} }
  ]
});

frames.FlowFrame = defineFrame(FrameType.AMQP, {
  name: 'flow', code: 0x13,
  fields: [
    { name:'nextIncomingId', type: 'transfer-number' },
    { name:'incomingWindow', type: 'uint', mandatory: true },
    { name:'nextOutgoingId', type: 'transfer-number', mandatory: true },
    { name:'outgoingWindow', type: 'uint', mandatory: true },
    { name:'handle', type: 'handle' },
    { name:'deliveryCount', type: 'sequence-no' },
    { name:'linkCredit', type: 'uint' },
    { name:'available', type: 'uint' },
    { name:'drain', type: 'boolean', default: false },
    { name:'echo', type: 'boolean', default: false },
    { name:'properties', type: 'fields', default: {} }
  ]
});

frames.TransferFrame = defineFrame(FrameType.AMQP, {
  name: 'transfer', code: 0x14,
  fields:[
    { name: 'handle', type: 'handle', mandatory: true },
    { name: 'deliveryId', type: 'delivery-number' },
    { name: 'deliveryTag', type: 'delivery-tag' },
    { name: 'messageFormat', type: 'message-format', default: 0 },
    { name: 'settled', type: 'boolean' },
    { name: 'more', type: 'boolean', default: false },
    { name: 'rcvSettleMode', type: 'ubyte', requires: receiverSettleMode, default: 'auto' },
    { name: 'state', type: '*' /* @todo: requires: deliveryState */ },
    { name: 'resume', type: 'boolean', default: false },
    { name: 'aborted', type: 'boolean', default: false },
    { name: 'batchable', type: 'boolean', default: false }
  ]
});

frames.DispositionFrame = defineFrame(FrameType.AMQP, {
  name: 'disposition', code: 0x15,
  fields:[
    { name: 'role', type: 'boolean', requires: role, mandatory: true },
    { name: 'first', type: 'delivery-number', mandatory: true },
    { name: 'last', type: 'delivery-number' },
    { name: 'settled', type: 'boolean', default: false },
    { name: 'state', type: '*' /* @todo: requires: deliveryState */ },
    { name: 'batchable', type: 'boolean', default: false }
  ]
});

frames.DetachFrame = defineFrame(FrameType.AMQP, {
  name: 'detach', code: 0x16,
  fields: [
    { name: 'handle', type: 'handle', mandatory: true },
    { name: 'closed', type: 'boolean', default: false },
    { name: 'error', type: 'error' }
  ]
});

frames.EndFrame = defineFrame(FrameType.AMQP, {
  name: 'end', code: 0x17,
  fields: [
    { name: 'error', type: 'error' }
  ]
});

frames.CloseFrame = defineFrame(FrameType.AMQP, {
  name: 'close', code: 0x18,
  fields: [
    { name: 'error', type: 'error' }
  ]
});

// SASL frames
frames.SaslMechanismsFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-mechanisms', code: 0x40,
  fields: [
    { name: 'saslServerMechanisms', type: 'symbol', multiple: true, mandatory: true }
  ]
});

frames.SaslInitFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-init', code: 0x41,
  fields: [
    { name: 'mechanism', type: 'symbol', mandatory: true },
    { name: 'initialResponse', type: 'binary' },
    { name: 'hostname', type: 'string' }
  ]
});

frames.SaslChallengeFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-challenge', code: 0x42,
  fields: [
    { name: 'challenge', type: 'binary', mandatory: true }
  ]
});

frames.SaslResponseFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-response', code: 0x43,
  fields: [
    { name: 'response', type: 'binary', mandatory: true }
  ]
});

frames.SaslOutcomeFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-outcome', code: 0x44,
  fields: [
    { name: 'code', type: 'ubyte', mandatory: true },
    { name: 'additionalData', type: 'binary' }
  ]
});

// special frames
frames.HeartbeatFrame = function() {
  frames.AMQPFrame.call(this, 0);
};
frames.HeartbeatFrame.prototype = Object.create(frames.AMQPFrame.prototype);
frames.HeartbeatFrame.prototype.toDescribedType = function() { return null; };
frames.HeartbeatFrame.prototype.inspect = function(depth) {
  return '(EMPTY FRAME)';
};

// used to determine if a message should be split to multiple frames
frames.TRANSFER_FRAME_OVERHEAD = 29;
<commit_msg>refactor(frames): add concept of verbosity to frames.readFrame<commit_after>'use strict';
var Builder = require('buffer-builder'),
    DescribedType = require('./types/described_type'),
    errors = require('./errors'),
    codec = require('./codec'),
    debug = require('debug')('amqp10:framing'),
    trace = require('debug')('amqp10:trace'),
    constants = require('./constants'),
    defineComposite = require('./types/composite_type').defineComposite,
    terminus = require('./types/terminus'),
    util = require('util');

var frames = module.exports = {};
var framesByDescriptor = {};

var FrameType = { AMQP: 0x00, SASL: 0x01 };
frames.Frame = function(type) { this.type = type; };
frames.AMQPFrame = function(channel) {
  frames.AMQPFrame.super_.call(this, constants.frameType.amqp);
  this.channel = channel || 0;
};
util.inherits(frames.AMQPFrame, frames.Frame);

frames.SaslFrame = function() {
  frames.SaslFrame.super_.call(this, constants.frameType.sasl);
};
util.inherits(frames.SaslFrame, frames.Frame);

frames.writeFrame = function(frame, stream, options, callback) {
  if (!(frame instanceof frames.Frame)) {
    throw new errors.EncodingError(frame, 'unknown frame type');
  }

  options = options || { verbose: true };
  if (callback === undefined && typeof options === 'function') {
    callback = options;
  }

  var builder = new Builder();
  builder.appendUInt32BE(0); // size placeholder
  builder.appendUInt8(2);  // doff, no extended headers
  builder.appendUInt8(frame.type);
  if (frame instanceof frames.AMQPFrame) {
    builder.appendUInt16BE(frame.channel);
  } else {
    builder.appendUInt16BE(0);
  }

  var performative = frame.toDescribedType();
  if (performative !== null && performative !== undefined) {
    codec.encode(performative, builder);
    if (frame instanceof frames.TransferFrame) {
      if (frame.payload !== undefined) builder.appendBuffer(frame.payload);
    }
  }

  var buffer = builder.get();
  buffer.writeUInt32BE(buffer.length, 0);
  if (options.verbose) {
    debug('=>', frame);
    trace('raw: [' + buffer.toString('hex') + ']');
  }

  stream.write(buffer, callback);
};

frames.readFrame = function(buffer, options) {
  options = options || { verbose: true };
  if (buffer.length < 8) return undefined;

  var sizeAndDoff = buffer.slice(0, 8);
  var size = sizeAndDoff.readUInt32BE(0);
  var doff = sizeAndDoff.readUInt8(4);
  if (doff !== 2) throw new errors.MalformedHeaderError('Invalid DOFF');
  if (size > buffer.length) return undefined;

  var frameType = sizeAndDoff[5];
  if (frameType !== FrameType.AMQP && frameType !== FrameType.SASL) {
    throw new errors.NotImplementedError('Unsupported frame type: ' + frameType);
  }

  // actually consume the bytes now that we have no errors
  buffer.consume(8);

  var payloadSize = size - (doff * 4);
  if (payloadSize <= 0) {
    // @todo: this is probably a heartbeat frame, but what if its not?
    if (options.verbose) {
      debug('<= (EMPTY FRAME)');
      trace('raw: [' + sizeAndDoff.toString('hex') + ']');
    }

    return;
  }

  var xHeaderSize = (doff * 4) - 8;
  if (xHeaderSize > 0) {
    var xHeaderBuf = buffer.slice(0, xHeaderSize);
    buffer.consume(xHeaderSize);

    // @todo: Process x-header
    if (options.verbose) {
      debug('received extended header');
      trace('raw: [' + xHeaderBuf.toString('hex') + ']');
    }
  }

  // read payload
  var payloadBuffer = buffer.slice(0, payloadSize);
  buffer.consume(payloadSize);

  // decode payload
  var decodedPayload = codec.decode(payloadBuffer, 0);
  if (!decodedPayload) {
    throw new errors.MalformedPayloadError('Unable to parse frame payload [' + payloadBuffer.toString('hex') + ']');
  }

  if (!(decodedPayload[0] instanceof DescribedType)) {
    throw new errors.MalformedPayloadError('Expected DescribedType from AMQP Payload, but received ' + JSON.stringify(decodedPayload[0]));
  }

  // read frame
  var channel = sizeAndDoff.readUInt16BE(6); // Bytes 6 & 7 are channel
  var messageBuffer = payloadBuffer.slice(decodedPayload[1]);

  var described = decodedPayload[0];
  if (!framesByDescriptor.hasOwnProperty(described.descriptor)) {
    throw new errors.MalformedPayloadError('Unknown frame descriptor: ' + described.descriptor);
  }

  var frame = new framesByDescriptor[described.descriptor](described);
  if (messageBuffer.length) frame.payload = messageBuffer;
  if (frameType === FrameType.AMQP) {
    frame.channel = channel;
  }

  if (options.verbose) {
    debug('<=', frame);
    trace('raw: [' + payloadBuffer.toString('hex') + ']');
  }

  return frame;
};

function defineFrame(type, definition) {
  var FrameBase = (type === FrameType.AMQP) ? frames.AMQPFrame : frames.SaslFrame;
  var Frame = defineComposite(FrameBase, definition);
  framesByDescriptor[Frame.descriptor.code] = Frame;
  framesByDescriptor[Frame.descriptor.name] = Frame;
  return Frame;
}

// restricted type helpers
function role(value) {
  if (typeof value === 'boolean')
    return value;

  if (value !== 'sender' && value !== 'receiver')
    throw new errors.EncodingError(value, 'invalid role');
  return (value === 'sender') ? false : true;
}

var ReceiverSettleModes = [ 'first', 'second', 'auto', 'settle' ];
function receiverSettleMode(value) {
  if (typeof value === 'number' || value instanceof Number)
    return value;

  if (ReceiverSettleModes.indexOf(value) === -1)
    throw new errors.EncodingError(value, 'invalid receiver settle mode');
  return (value === 'first' || value === 'auto') ? 0 : 1;
}

function senderSettleMode(value) {
  if (typeof value === 'number' || value instanceof Number)
    return value;

  if (value !== 'unsettled' && value !== 'settled' && value !== 'mixed')
    throw new errors.EncodingError(value, 'invalid sender settle mode');

  if (value === 'unsettled') return 0;
  else if (value === 'settled') return 1;
  return 2;
}

// AMQP frames
frames.OpenFrame = defineFrame(FrameType.AMQP, {
  name: 'open', code: 0x10,
  fields: [
    { name: 'containerId', type: 'string', mandatory: true },
    { name: 'hostname', type: 'string' },
    { name: 'maxFrameSize', type: 'uint', default: constants.defaultMaxFrameSize },
    { name: 'channelMax', type: 'ushort', default: constants.defaultChannelMax },
    { name: 'idleTimeout', type: 'milliseconds', default: constants.defaultIdleTimeout },
    { name: 'outgoingLocales', type: 'ietf-language-tag',
      multiple: true, default: constants.defaultOutgoingLocales },
    { name: 'incomingLocales', type: 'ietf-language-tag',
      multiple: true, default: constants.defaultIncomingLocales },
    { name: 'offeredCapabilities', type: 'symbol', multiple: true },
    { name: 'desiredCapabilities', type: 'symbol', multiple: true },
    { name: 'properties', type: 'fields', default: {} }
  ]
});

frames.BeginFrame = defineFrame(FrameType.AMQP, {
  name: 'begin', code: 0x11,
  fields: [
    { name: 'remoteChannel', type: 'ushort' },
    { name: 'nextOutgoingId', type: 'transfer-number', mandatory: true },
    { name: 'incomingWindow', type: 'uint', mandatory: true },
    { name: 'outgoingWindow', type: 'uint', mandatory: true },
    { name: 'handleMax', type: 'handle', default: constants.defaultHandleMax },
    { name: 'offeredCapabilities', type: 'symbol', multiple: true },
    { name: 'desiredCapabilities', type: 'symbol', multiple: true },
    { name: 'properties', type: 'fields', default: {} }
  ]
});

frames.AttachFrame = defineFrame(FrameType.AMQP, {
  name: 'attach', code: 0x12,
  fields: [
    { name: 'name', type: 'string', mandatory: true },
    { name: 'handle', type: 'handle', mandatory: true },
    { name: 'role', type: 'boolean', requires: role, mandatory: true },
    { name: 'sndSettleMode', type: 'ubyte', requires: senderSettleMode, default: 'mixed' },
    { name: 'rcvSettleMode', type: 'ubyte', requires: receiverSettleMode, default: 'auto' },
    { name: 'source', type: '*', requires: terminus.Source },
    { name: 'target', type: '*', requires: terminus.Target },
    { name: 'unsettled', type: 'map', default: {} },
    { name: 'incompleteUnsettled', type: 'boolean', default: false },
    { name: 'initialDeliveryCount', type: 'sequence-no' },
    { name: 'maxMessageSize', type: 'ulong', default: 0 },
    { name: 'offeredCapabilities', type: 'symbol', multiple: true },
    { name: 'desiredCapabilities', type: 'symbol', multiple: true },
    { name: 'properties', type: 'fields', default: {} }
  ]
});

frames.FlowFrame = defineFrame(FrameType.AMQP, {
  name: 'flow', code: 0x13,
  fields: [
    { name:'nextIncomingId', type: 'transfer-number' },
    { name:'incomingWindow', type: 'uint', mandatory: true },
    { name:'nextOutgoingId', type: 'transfer-number', mandatory: true },
    { name:'outgoingWindow', type: 'uint', mandatory: true },
    { name:'handle', type: 'handle' },
    { name:'deliveryCount', type: 'sequence-no' },
    { name:'linkCredit', type: 'uint' },
    { name:'available', type: 'uint' },
    { name:'drain', type: 'boolean', default: false },
    { name:'echo', type: 'boolean', default: false },
    { name:'properties', type: 'fields', default: {} }
  ]
});

frames.TransferFrame = defineFrame(FrameType.AMQP, {
  name: 'transfer', code: 0x14,
  fields:[
    { name: 'handle', type: 'handle', mandatory: true },
    { name: 'deliveryId', type: 'delivery-number' },
    { name: 'deliveryTag', type: 'delivery-tag' },
    { name: 'messageFormat', type: 'message-format', default: 0 },
    { name: 'settled', type: 'boolean' },
    { name: 'more', type: 'boolean', default: false },
    { name: 'rcvSettleMode', type: 'ubyte', requires: receiverSettleMode, default: 'auto' },
    { name: 'state', type: '*' /* @todo: requires: deliveryState */ },
    { name: 'resume', type: 'boolean', default: false },
    { name: 'aborted', type: 'boolean', default: false },
    { name: 'batchable', type: 'boolean', default: false }
  ]
});

frames.DispositionFrame = defineFrame(FrameType.AMQP, {
  name: 'disposition', code: 0x15,
  fields:[
    { name: 'role', type: 'boolean', requires: role, mandatory: true },
    { name: 'first', type: 'delivery-number', mandatory: true },
    { name: 'last', type: 'delivery-number' },
    { name: 'settled', type: 'boolean', default: false },
    { name: 'state', type: '*' /* @todo: requires: deliveryState */ },
    { name: 'batchable', type: 'boolean', default: false }
  ]
});

frames.DetachFrame = defineFrame(FrameType.AMQP, {
  name: 'detach', code: 0x16,
  fields: [
    { name: 'handle', type: 'handle', mandatory: true },
    { name: 'closed', type: 'boolean', default: false },
    { name: 'error', type: 'error' }
  ]
});

frames.EndFrame = defineFrame(FrameType.AMQP, {
  name: 'end', code: 0x17,
  fields: [
    { name: 'error', type: 'error' }
  ]
});

frames.CloseFrame = defineFrame(FrameType.AMQP, {
  name: 'close', code: 0x18,
  fields: [
    { name: 'error', type: 'error' }
  ]
});

// SASL frames
frames.SaslMechanismsFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-mechanisms', code: 0x40,
  fields: [
    { name: 'saslServerMechanisms', type: 'symbol', multiple: true, mandatory: true }
  ]
});

frames.SaslInitFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-init', code: 0x41,
  fields: [
    { name: 'mechanism', type: 'symbol', mandatory: true },
    { name: 'initialResponse', type: 'binary' },
    { name: 'hostname', type: 'string' }
  ]
});

frames.SaslChallengeFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-challenge', code: 0x42,
  fields: [
    { name: 'challenge', type: 'binary', mandatory: true }
  ]
});

frames.SaslResponseFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-response', code: 0x43,
  fields: [
    { name: 'response', type: 'binary', mandatory: true }
  ]
});

frames.SaslOutcomeFrame = defineFrame(FrameType.SASL, {
  name: 'sasl-outcome', code: 0x44,
  fields: [
    { name: 'code', type: 'ubyte', mandatory: true },
    { name: 'additionalData', type: 'binary' }
  ]
});

// special frames
frames.HeartbeatFrame = function() {
  frames.AMQPFrame.call(this, 0);
};
frames.HeartbeatFrame.prototype = Object.create(frames.AMQPFrame.prototype);
frames.HeartbeatFrame.prototype.toDescribedType = function() { return null; };
frames.HeartbeatFrame.prototype.inspect = function(depth) {
  return '(EMPTY FRAME)';
};

// used to determine if a message should be split to multiple frames
frames.TRANSFER_FRAME_OVERHEAD = 29;
<|endoftext|>