<commit_before>var FS = require('fs'),
    UTIL = require('util'),
    Q = require('qq'),
    bemUtil = require('./util'),
    PATH = require('./path'),
    INHERIT = require('inherit'),

    /**
     * Returns tech class for tech module path
     * @param {String} path  path to tech module
     * @returns {Tech}
     */
    getTechClass = exports.getTechClass = function(path) {
        var tech = require(path),
            TechClass = Tech;

        if(tech.Tech) return tech.Tech;
        if(tech.baseTechPath) TechClass = getTechClass(tech.baseTechPath);
        else if (tech.techModule || tech.bemBuild || tech.bemCreate) TechClass = LegacyTech;

        return INHERIT(TechClass, tech);
    },

    /**
     * Returns tech object for tech module
     * @param {String} path  tech module absolute path
     * @param {String} name  tech name
     * @returns {Tech}
     */
    createTech = exports.createTech = function(path, name) {
        path = require.resolve(path);
        return new (getTechClass(path))(name, path);
    },

    Tech = exports.Tech = INHERIT({

        /**
         * @class Base tech class
         * @constructs
         * @private
         * @param {Object} name  tech name
         * @param {Object} path  tech module absolute path
         */
        __constructor: function(name, path) {
            this.techName = name;
            this.techPath = path;
        },

        /**
         * Sets context to use in tech modules
         * @public
         * @param {Context} ctx  context
         */
        setContext: function(ctx) {
            this.context = ctx;
            return this;
        },

        /**
         * Returns context
         * @public
         * @returns {Context}
         */
        getContext: function() {
            return this.context;
        },

        /**
         * Implementation of 'bem create block | elem | mod' commands
         * @public
         * @param {String}  prefix  path prefix of object to create
         * @param {Object}  vars    variables to use in template
         * @param {Boolean} force   force creation flag
         */
        create: function(prefix, vars, force) {
            return this.storeCreateResults(prefix, this.getCreateResults(prefix, vars), force);
        },

        /**
         * Returns create result for one suffix
         * @protected
         * @param {String} path    full path of object to create
         * @param {String} suffix  suffix of object to create
         * @param {Object} vars    variables to use in template
         * @returns {String}
         */
        getCreateResult: function(path, suffix, vars) {
            return '';
        },

        /**
         * Returns create result for all suffixes
         * @protected
         * @param {String}  prefix  path prefix of object to create
         * @param {Object}  vars    variables to use in template
         * @returns {Object}
         */
        getCreateResults: function(prefix, vars) {
            var _this = this,
                res = {};

            this.getSuffixes().forEach(function(suffix) {
                res[suffix] = _this.getCreateResult(_this.getPath(prefix, suffix), suffix, vars);
            });

            return Q.shallow(res);
        },

        /**
         * Stores result of object creation for one suffix
         * @protected
         * @param {String}  path    full path of object to create
         * @param {String}  suffix  suffix of object to create
         * @param {Object}  res     result of object creation
         * @param {Boolean} force   force creation flag
         */
        storeCreateResult: function(path, suffix, res, force) {
            return Q.step(
                function() {
                    return bemUtil.isFileP(path);
                },
                function(exists) {
                    if(exists && !force) {
                        // TODO: bad idea to output error to console directly
                        UTIL.error("Already exists '" + path + "'");
                        return;
                    }
                    return bemUtil.writeFile(path, res);
                }
            );
        },

        /**
         * Stores results of object creation
         * @protected
         * @param {String}  prefix  path prefix of object to create
         * @param {Object}  res     result of object creation
         * @param {Boolean} force   force creation flag
         */
        storeCreateResults: function(prefix, res, force) {
            var _this = this;
            return Q.when(res, function(res) {
                var done;
                _this.getSuffixes().forEach(function(suffix) {
                    done = Q.wait(done, _this.storeCreateResult(_this.getPath(prefix, suffix), suffix, res[suffix], force));
                });
                return done;
            });
        },

        /**
         * Reads and returns content of object with specified prefix
         * for specified suffix
         * @protected
         * @param {String} path    full path of object to read
         * @param {String} suffix  suffix of object to read
         * @returns {String}
         */
        readContent: function(path, suffix) {
            return Q.when(bemUtil.isFile(path), function(exists) {
                if(exists) {
                    return bemUtil.readFile(path);
                }
                return '';
            });
        },

        /**
         * Reads and returns content of object with specified prefix
         * @param {String}  prefix  path prefix of object to read content of
         * @returns {Object}
         */
        readAllContent: function(prefix) {
            var _this = this,
                res = {};

            this.getSuffixes().forEach(function(suffix) {
                res[suffix] = _this.readContent(_this.getPath(prefix, suffix), suffix);
            });

            return Q.shallow(res);
        },

        /**
         * Implementation of 'bem build' command
         * @public
         * @param {Array}  prefixes    prefixes to build
         * @param {String} outputDir   dir to output result to
         * @param {String} outputName  name prefix of output
         */
        build: function(prefixes, outputDir, outputName) {
            return this.storeBuildResults(
                PATH.join(outputDir, outputName),
                this.getBuildResults(prefixes, outputDir, outputName));
        },

        /**
         * Filters prefixes with attached suffixes and returns
         * array of paths to aggregate during build process
         * @protected
         * @param {Array} prefixes
         * @param {Array} suffixes
         * @return {Array}
         */
        filterPrefixes: function(prefixes, suffixes) {
            var _this = this,
                res = {};

            prefixes.forEach(function(prefix) {
                suffixes.forEach(function(suffix) {
                    var path = _this.getPath(prefix, suffix);
                    res[path] = bemUtil.isExists(path);
                });
            });

            return Q.when(Q.shallow(res), function(res) {
                var paths = [];
                for(var path in res) {
                    if(res[path]) paths.push(path);
                }
                return paths;
            });
        },

        /**
         * Returns build result chunk
         * @protected
         * @param {String} relPath  relative path to source object
         * @param {String} path     path to source object
         * @param {String} suffix   suffix of source object
         * @returns {String}
         */
        getBuildResultChunk: function(relPath, path, suffix) {
            return relPath + '\n';
        },

        /**
         * Builds and returns result of build of specified prefixes
         * for specified suffix
         * @protected
         * @param {Array} prefixes     prfixes to build
         * @param {String} suffix      suffix to build result for
         * @param {String} outputDir   output dir name for build result
         * @param {String} outputName  output name of build result
         */
        getBuildResult: function(prefixes, suffix, outputDir, outputName) {
            var _this = this;
            return Q.when(this.filterPrefixes(prefixes, [suffix]), function(paths) {
                return Q.shallow(paths.map(function(path) {
                    return _this.getBuildResultChunk(
                        PATH.relative(outputDir, path), path, suffix);
                }));
            });
        },

        /**
         * Builds and returns result of build of specified prefixes
         * @protected
         * @param {Array} prefixes     prfixes to build
         * @param {String} outputDir   output dir name for build result
         * @param {String} outputName  output name of build result
         * @return {Object}
         */
        getBuildResults: function(prefixes, outputDir, outputName) {
            var _this = this,
                res = {};

            this.getSuffixes().forEach(function(suffix) {
                res[suffix] = _this.getBuildResult(prefixes, suffix, outputDir, outputName);
            });

            return Q.shallow(res);
        },

        /**
         * Stores result of build for specified suffix
         * @protected
         * @param {String} path    path of object to store
         * @param {String} suffix  suffix of object to store
         * @param {String} res     result of build for specified suffix
         */
        storeBuildResult: function(path, suffix, res) {
            return bemUtil.writeFile(path, res);
        },

        /**
         * Stores results of build
         * @protected
         * @param {String} prefix  prefix of object to build
         * @param {String} res     result of build
         */
        storeBuildResults: function(prefix, res) {
            var _this = this;
            return Q.when(res, function(res) {
                var done;
                _this.getSuffixes().forEach(function(suffix) {
                    done = Q.wait(done, _this.storeBuildResult(_this.getPath(prefix, suffix), suffix, res[suffix]));
                });
                return done;
            });
        },

        /**
         * Returns true if suffix mathes one of tech suffixes
         * @public
         * @param {String} suffix
         * @returns {Boolean}
         */
        matchSuffix: function(suffix) {
            (suffix.substr(0, 1) == '.') && (suffix = suffix.substr(1));
            return this.getSuffixes().indexOf(suffix) >= 0;
        },

        /**
         * Returns all tech suffixes
         * @public
         * @returns {Array}
         */
        getSuffixes: function() {
            return [this.getTechName()];
        },

        /**
         * Returns path by prefix and suffix
         * @public
         * @param {String} prefix
         * @param {String} suffix
         * @returns {String}
         */
        getPath: function(prefix, suffix) {
            suffix = suffix || this.getTechName();
            return [prefix, suffix].join('.');
        },

        /**
         * Returns tech name
         * @public
         * @returns {String}
         */
        getTechName: function() {
            if(this.techName) return this.techName;
            return bemUtil.stripModuleExt(PATH.basename(this.getTechPath()));
        },

        /**
         * Returns tech module absolute path
         * @public
         * @returns {String}
         */
        getTechPath: function() {
            return this.techPath;
        },

        /**
         * Returns tech module relative path
         * @public
         * @param   {String} from  path to calculate relative path from
         * @returns {String}
         */
        getTechRelativePath: function(from) {
            from = PATH.join(from || '.', PATH.dirSep);
            var absPath = this.getTechPath(),
                techPath = PATH.relative(PATH.join(__dirname, PATH.unixToOs('../../')), absPath),

                testDotRe = new RegExp('^[\\.' + PATH.dirSepRe + ']'),
                testLibRe = new RegExp('^.*?' + PATH.dirSepRe + 'lib'),
                replaceRe = new RegExp('^.*?' + PATH.dirSepRe);

            // tech from 'bem' module
            if(!testDotRe.test(techPath) && testLibRe.test(techPath)) {
                techPath = techPath.replace(replaceRe, PATH.unixToOs('bem/'));
            } else {
                // look for tech into node_modules and NODE_PATH env variable
                var shortestPath = PATH.relative(from, absPath);
                shortestPath = shortestPath.split(PATH.dirSep);
                module.paths.concat(bemUtil.getNodePaths()).forEach(function(reqPath) {
                    var relPath = PATH.relative(PATH.join(reqPath, PATH.dirSep), absPath);
                    if(!/^\./.test(relPath)) {
                        relPath = relPath.split(PATH.dirSep);
                        if(relPath.length < shortestPath.length) {
                            shortestPath = relPath;
                        }
                    }
                });

                techPath = PATH.join.apply(null, shortestPath);
                // NOTE: could not replace to PATH.join('.', techPath), because of
                // '.' will be stripped
                if(!/^\./.test(techPath)) techPath = '.' + PATH.dirSep + techPath;
            }

            techPath = bemUtil.stripModuleExt(techPath);

            // NOTE: default tech, need to return empty path for it
            if(techPath == bemUtil.getBemTechPath('default')) return '';
            return techPath;
        }

    }, {

        /**
         * Sets context to use in tech modules
         * @static
         * @public
         * @param {Context} ctx  context
         */
        setContext: function(ctx) {
            Tech.prototype.context = ctx;
            require('./legacy-tech').Tech.setContext(ctx);
        }

    }),

    LegacyTech = INHERIT(Tech, {

        /**
         * @class Legacy tech modules wrapper class
         * @constructs
         * @private
         * @param {Object} name  tech name
         * @param {Object} path  tech module absolute path
         */
        __constructor: function(name, path) {
            this.techObj = new (require('./legacy-tech').Tech)(path, name);
            this.__base(name, path);
        },

        create: function(prefix, vars, force) {
            return this.techObj.bemCreate(prefix, vars, force);
        },

        readAllContent: function(prefix) {
            var res = {};
            res[this.getTechName()] = this.techObj.getFileContent(prefix);
            return res;
        },

        build: function(prefixes, outputDir, outputName) {
            return this.techObj.bemBuild(prefixes, outputDir, outputName);
        },

        getTechName: function() {
            return this.techObj.getTechName();
        }

    });
<commit_msg>Remove unused require<commit_after>var UTIL = require('util'),
    Q = require('qq'),
    bemUtil = require('./util'),
    PATH = require('./path'),
    INHERIT = require('inherit'),

    /**
     * Returns tech class for tech module path
     * @param {String} path  path to tech module
     * @returns {Tech}
     */
    getTechClass = exports.getTechClass = function(path) {
        var tech = require(path),
            TechClass = Tech;

        if(tech.Tech) return tech.Tech;
        if(tech.baseTechPath) TechClass = getTechClass(tech.baseTechPath);
        else if (tech.techModule || tech.bemBuild || tech.bemCreate) TechClass = LegacyTech;

        return INHERIT(TechClass, tech);
    },

    /**
     * Returns tech object for tech module
     * @param {String} path  tech module absolute path
     * @param {String} name  tech name
     * @returns {Tech}
     */
    createTech = exports.createTech = function(path, name) {
        path = require.resolve(path);
        return new (getTechClass(path))(name, path);
    },

    Tech = exports.Tech = INHERIT({

        /**
         * @class Base tech class
         * @constructs
         * @private
         * @param {Object} name  tech name
         * @param {Object} path  tech module absolute path
         */
        __constructor: function(name, path) {
            this.techName = name;
            this.techPath = path;
        },

        /**
         * Sets context to use in tech modules
         * @public
         * @param {Context} ctx  context
         */
        setContext: function(ctx) {
            this.context = ctx;
            return this;
        },

        /**
         * Returns context
         * @public
         * @returns {Context}
         */
        getContext: function() {
            return this.context;
        },

        /**
         * Implementation of 'bem create block | elem | mod' commands
         * @public
         * @param {String}  prefix  path prefix of object to create
         * @param {Object}  vars    variables to use in template
         * @param {Boolean} force   force creation flag
         */
        create: function(prefix, vars, force) {
            return this.storeCreateResults(prefix, this.getCreateResults(prefix, vars), force);
        },

        /**
         * Returns create result for one suffix
         * @protected
         * @param {String} path    full path of object to create
         * @param {String} suffix  suffix of object to create
         * @param {Object} vars    variables to use in template
         * @returns {String}
         */
        getCreateResult: function(path, suffix, vars) {
            return '';
        },

        /**
         * Returns create result for all suffixes
         * @protected
         * @param {String}  prefix  path prefix of object to create
         * @param {Object}  vars    variables to use in template
         * @returns {Object}
         */
        getCreateResults: function(prefix, vars) {
            var _this = this,
                res = {};

            this.getSuffixes().forEach(function(suffix) {
                res[suffix] = _this.getCreateResult(_this.getPath(prefix, suffix), suffix, vars);
            });

            return Q.shallow(res);
        },

        /**
         * Stores result of object creation for one suffix
         * @protected
         * @param {String}  path    full path of object to create
         * @param {String}  suffix  suffix of object to create
         * @param {Object}  res     result of object creation
         * @param {Boolean} force   force creation flag
         */
        storeCreateResult: function(path, suffix, res, force) {
            return Q.step(
                function() {
                    return bemUtil.isFileP(path);
                },
                function(exists) {
                    if(exists && !force) {
                        // TODO: bad idea to output error to console directly
                        UTIL.error("Already exists '" + path + "'");
                        return;
                    }
                    return bemUtil.writeFile(path, res);
                }
            );
        },

        /**
         * Stores results of object creation
         * @protected
         * @param {String}  prefix  path prefix of object to create
         * @param {Object}  res     result of object creation
         * @param {Boolean} force   force creation flag
         */
        storeCreateResults: function(prefix, res, force) {
            var _this = this;
            return Q.when(res, function(res) {
                var done;
                _this.getSuffixes().forEach(function(suffix) {
                    done = Q.wait(done, _this.storeCreateResult(_this.getPath(prefix, suffix), suffix, res[suffix], force));
                });
                return done;
            });
        },

        /**
         * Reads and returns content of object with specified prefix
         * for specified suffix
         * @protected
         * @param {String} path    full path of object to read
         * @param {String} suffix  suffix of object to read
         * @returns {String}
         */
        readContent: function(path, suffix) {
            return Q.when(bemUtil.isFile(path), function(exists) {
                if(exists) {
                    return bemUtil.readFile(path);
                }
                return '';
            });
        },

        /**
         * Reads and returns content of object with specified prefix
         * @param {String}  prefix  path prefix of object to read content of
         * @returns {Object}
         */
        readAllContent: function(prefix) {
            var _this = this,
                res = {};

            this.getSuffixes().forEach(function(suffix) {
                res[suffix] = _this.readContent(_this.getPath(prefix, suffix), suffix);
            });

            return Q.shallow(res);
        },

        /**
         * Implementation of 'bem build' command
         * @public
         * @param {Array}  prefixes    prefixes to build
         * @param {String} outputDir   dir to output result to
         * @param {String} outputName  name prefix of output
         */
        build: function(prefixes, outputDir, outputName) {
            return this.storeBuildResults(
                PATH.join(outputDir, outputName),
                this.getBuildResults(prefixes, outputDir, outputName));
        },

        /**
         * Filters prefixes with attached suffixes and returns
         * array of paths to aggregate during build process
         * @protected
         * @param {Array} prefixes
         * @param {Array} suffixes
         * @return {Array}
         */
        filterPrefixes: function(prefixes, suffixes) {
            var _this = this,
                res = {};

            prefixes.forEach(function(prefix) {
                suffixes.forEach(function(suffix) {
                    var path = _this.getPath(prefix, suffix);
                    res[path] = bemUtil.isExists(path);
                });
            });

            return Q.when(Q.shallow(res), function(res) {
                var paths = [];
                for(var path in res) {
                    if(res[path]) paths.push(path);
                }
                return paths;
            });
        },

        /**
         * Returns build result chunk
         * @protected
         * @param {String} relPath  relative path to source object
         * @param {String} path     path to source object
         * @param {String} suffix   suffix of source object
         * @returns {String}
         */
        getBuildResultChunk: function(relPath, path, suffix) {
            return relPath + '\n';
        },

        /**
         * Builds and returns result of build of specified prefixes
         * for specified suffix
         * @protected
         * @param {Array} prefixes     prfixes to build
         * @param {String} suffix      suffix to build result for
         * @param {String} outputDir   output dir name for build result
         * @param {String} outputName  output name of build result
         */
        getBuildResult: function(prefixes, suffix, outputDir, outputName) {
            var _this = this;
            return Q.when(this.filterPrefixes(prefixes, [suffix]), function(paths) {
                return Q.shallow(paths.map(function(path) {
                    return _this.getBuildResultChunk(
                        PATH.relative(outputDir, path), path, suffix);
                }));
            });
        },

        /**
         * Builds and returns result of build of specified prefixes
         * @protected
         * @param {Array} prefixes     prfixes to build
         * @param {String} outputDir   output dir name for build result
         * @param {String} outputName  output name of build result
         * @return {Object}
         */
        getBuildResults: function(prefixes, outputDir, outputName) {
            var _this = this,
                res = {};

            this.getSuffixes().forEach(function(suffix) {
                res[suffix] = _this.getBuildResult(prefixes, suffix, outputDir, outputName);
            });

            return Q.shallow(res);
        },

        /**
         * Stores result of build for specified suffix
         * @protected
         * @param {String} path    path of object to store
         * @param {String} suffix  suffix of object to store
         * @param {String} res     result of build for specified suffix
         */
        storeBuildResult: function(path, suffix, res) {
            return bemUtil.writeFile(path, res);
        },

        /**
         * Stores results of build
         * @protected
         * @param {String} prefix  prefix of object to build
         * @param {String} res     result of build
         */
        storeBuildResults: function(prefix, res) {
            var _this = this;
            return Q.when(res, function(res) {
                var done;
                _this.getSuffixes().forEach(function(suffix) {
                    done = Q.wait(done, _this.storeBuildResult(_this.getPath(prefix, suffix), suffix, res[suffix]));
                });
                return done;
            });
        },

        /**
         * Returns true if suffix mathes one of tech suffixes
         * @public
         * @param {String} suffix
         * @returns {Boolean}
         */
        matchSuffix: function(suffix) {
            (suffix.substr(0, 1) == '.') && (suffix = suffix.substr(1));
            return this.getSuffixes().indexOf(suffix) >= 0;
        },

        /**
         * Returns all tech suffixes
         * @public
         * @returns {Array}
         */
        getSuffixes: function() {
            return [this.getTechName()];
        },

        /**
         * Returns path by prefix and suffix
         * @public
         * @param {String} prefix
         * @param {String} suffix
         * @returns {String}
         */
        getPath: function(prefix, suffix) {
            suffix = suffix || this.getTechName();
            return [prefix, suffix].join('.');
        },

        /**
         * Returns tech name
         * @public
         * @returns {String}
         */
        getTechName: function() {
            if(this.techName) return this.techName;
            return bemUtil.stripModuleExt(PATH.basename(this.getTechPath()));
        },

        /**
         * Returns tech module absolute path
         * @public
         * @returns {String}
         */
        getTechPath: function() {
            return this.techPath;
        },

        /**
         * Returns tech module relative path
         * @public
         * @param   {String} from  path to calculate relative path from
         * @returns {String}
         */
        getTechRelativePath: function(from) {
            from = PATH.join(from || '.', PATH.dirSep);
            var absPath = this.getTechPath(),
                techPath = PATH.relative(PATH.join(__dirname, PATH.unixToOs('../../')), absPath),

                testDotRe = new RegExp('^[\\.' + PATH.dirSepRe + ']'),
                testLibRe = new RegExp('^.*?' + PATH.dirSepRe + 'lib'),
                replaceRe = new RegExp('^.*?' + PATH.dirSepRe);

            // tech from 'bem' module
            if(!testDotRe.test(techPath) && testLibRe.test(techPath)) {
                techPath = techPath.replace(replaceRe, PATH.unixToOs('bem/'));
            } else {
                // look for tech into node_modules and NODE_PATH env variable
                var shortestPath = PATH.relative(from, absPath);
                shortestPath = shortestPath.split(PATH.dirSep);
                module.paths.concat(bemUtil.getNodePaths()).forEach(function(reqPath) {
                    var relPath = PATH.relative(PATH.join(reqPath, PATH.dirSep), absPath);
                    if(!/^\./.test(relPath)) {
                        relPath = relPath.split(PATH.dirSep);
                        if(relPath.length < shortestPath.length) {
                            shortestPath = relPath;
                        }
                    }
                });

                techPath = PATH.join.apply(null, shortestPath);
                // NOTE: could not replace to PATH.join('.', techPath), because of
                // '.' will be stripped
                if(!/^\./.test(techPath)) techPath = '.' + PATH.dirSep + techPath;
            }

            techPath = bemUtil.stripModuleExt(techPath);

            // NOTE: default tech, need to return empty path for it
            if(techPath == bemUtil.getBemTechPath('default')) return '';
            return techPath;
        }

    }, {

        /**
         * Sets context to use in tech modules
         * @static
         * @public
         * @param {Context} ctx  context
         */
        setContext: function(ctx) {
            Tech.prototype.context = ctx;
            require('./legacy-tech').Tech.setContext(ctx);
        }

    }),

    LegacyTech = INHERIT(Tech, {

        /**
         * @class Legacy tech modules wrapper class
         * @constructs
         * @private
         * @param {Object} name  tech name
         * @param {Object} path  tech module absolute path
         */
        __constructor: function(name, path) {
            this.techObj = new (require('./legacy-tech').Tech)(path, name);
            this.__base(name, path);
        },

        create: function(prefix, vars, force) {
            return this.techObj.bemCreate(prefix, vars, force);
        },

        readAllContent: function(prefix) {
            var res = {};
            res[this.getTechName()] = this.techObj.getFileContent(prefix);
            return res;
        },

        build: function(prefixes, outputDir, outputName) {
            return this.techObj.bemBuild(prefixes, outputDir, outputName);
        },

        getTechName: function() {
            return this.techObj.getTechName();
        }

    });
<|endoftext|>


<commit_before>var http = require('http');
var EventEmitter = require('events').EventEmitter;
var url = require('url');
var path = require('path');

var deepEqual = require('./deep_equal');
var pending = 0;

var test = module.exports = function (name, cb) {
    if (typeof name === 'function') {
        cb = name;
        name = undefined;
    }

    var t = new Test(name, test.push);
    pending ++;

    t.on('testEnd', function () {
        pending --;
        process.nextTick(function () {
            if (pending <= 0) t.push('end', {});
            harness.emit('end', t);
        });
    });

    cb(t);
};

var harness = test.harness = new EventEmitter;

var testId = 0;
function Test (name, push) {
    this.id = testId ++;
    this.push = push;
    push('testBegin', { name : name, testId : this.id });

    this.counts = {
        plan : undefined,
        pass : 0,
        fail : 0
    };
    this.windows = [];
}

Test.prototype = new EventEmitter;

Test.prototype.assert = function (res) {
    if (res.ok) this.counts.pass ++
    else this.counts.fail ++

    if (this.counts.plan !== undefined
    && this.counts.pass + this.counts.fail > this.counts.plan) {
        this.push('fail', {
            type : 'fail',
            ok : false,
            found : this.counts.fail + this.counts.pass,
            wanted : this.counts.plan,
            name : 'more tests run than planned',
            testId : this.id
        });
    }

    res.testId = this.id;
    this.push('assert', res);
    if (!res.ok) res.stack = stack();

    if (this.counts.plan !== undefined
    && this.counts.plan === this.counts.pass + this.counts.fail) {
        this.end();
    }
};

Test.prototype.ok = function (value, name) {
    this.assert({
        type : 'ok',
        ok : !!value,
        name : name,
        found : Boolean(value),
        wanted : true
    });
};

Test.prototype.notOk = function (value, name) {
    this.assert({
        type : 'ok',
        ok : !!!value,
        name : name,
        found : Boolean(value),
        wanted : false
    });
};

Test.prototype.fail = function (value, name) {
    this.assert({
        type : 'fail',
        ok : false,
        name : name,
        found : value,
        wanted : undefined,
        stack : stack()
    });
};

Test.prototype.equal = function (found, wanted, name) {
    this.assert({
        type : 'equal',
        ok : found == wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.notEqual = function (found, wanted, name) {
    this.assert({
        type : 'notEqual',
        ok : found != wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.deepEqual = function (found, wanted, name) {
    this.assert({
        type : 'deepEqual',
        ok : deepEqual(found, wanted),
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.notDeepEqual = function (found, wanted, name) {
    this.assert({
        type : 'notDeepEqual',
        ok : !deepEqual(found, wanted),
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.strictEqual = function (found, wanted, name) {
    this.assert({
        type : 'strictEqual',
        ok : found === wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.notStrictEqual = function (found, wanted, name) {
    this.assert({
        type : 'strictEqual',
        ok : found !== wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

function checkThrows (shouldThrow, fn, expected, name) {
    if (typeof expected === 'string') {
        name = expected;
        expected = null;
    }
    var ok = !shouldThrow, err = undefined;

    try { fn() }
    catch (e) {
        ok = !ok;
        err = e;
    }

    this.assert({
        type : shouldThrow ? 'throws' : 'doesNotThrow',
        ok : ok,
        found : err,
        expected : expected
    });
}

Test.prototype['throws'] = function (fn, expected, name) {
    checkThrows.call(this, true, fn, expected, name);
};

Test.prototype.doesNotThrow = function (fn, expected, name) {
    checkThrows.call(this, false, fn, expected, name);
};

Test.prototype.ifError = function (err, name) {
    this.assert({
        type : 'ifError',
        ok : !!!err,
        name : name,
        found : err,
        wanted : undefined
    });
};

Test.prototype.plan = function (n) {
    if (this.counts.plan === undefined) {
        this.counts.plan = n;
    }
    else {
        this.counts.plan += n;
    }
    this.push('plan', { testId : this.id, n : n });
};

Test.prototype.log = function (msg) {
    this.push('log', { testId : this.id, message : msg });
};

Test.prototype.end = function () {
    if (this.counts.plan !== undefined
    && this.counts.plan > this.counts.fail + this.counts.pass) {
        this.push('planFail', {
            type : 'fail',
            ok : false,
            found : this.counts.fail + this.counts.pass,
            wanted : this.counts.plan,
            name : 'more tests planned than run',
            testId : this.id
        });
    }

    if (!this.ended) {
        this.ended = true;
        this.push('testEnd', { testId : this.id });
        this.emit('testEnd');
    }
};

var jsdom = require('jsdom');

Test.prototype.createWindow = function (url, opts, cb) {
    if (typeof url === 'object') {
        cb = opts;
        opts = url;
        url = opts.url;
    }

    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    opts.url = url;

    var win = createWindow(this, opts, cb);
    this.windows.push(win);
    return win;
};

Test.prototype.submitForm = function (form, params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }
    if (!params) params = {};

    if (form[0]) {
        if (form[0] instanceof jsdom.defaultLevel.HTMLFormElement
        || form[0].elements) {
            form = form[0];
        }
    }

    if (!form.elements) {
        this.fail('encountered a non-form element');
        return;
    }

    var pairs = [];

    var len = 0;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name) {
            len += form.elements[i].name.length
                + 1 + form.elements[i].value.length;
            pairs.push(
                escape(form.elements[i].name)
                + '='
                + escape(form.elements[i].value)
            );
        }
    }

    var data = pairs.join('&');
    var pwin = form.ownerDocument.parentWindow;

    var opts = {
        url : form.action || pwin.location.href.split('?')[0],
        method : form.method || 'GET',
        data : data,
        headers : params.headers || {}
    };

    if (!opts.url.match(/^https?:/)) {
        opts.url = pwin.location.protocol + '//' + pwin.location.host
            + path.resolve(path.dirname(pwin.location.path), opts.url)
        ;
    }

    if (opts.method === 'POST') {
        if (!opts.headers['content-length']
        && opts.headers['transfer-encoding'] !== 'chunked') {
            opts.headers['content-length'] = len + 1;
        }
    }

    var win = createWindow(this, opts, cb);
    this.windows.push(win);
    return win;
};

function createWindow (self, opts, cb) {
    if (opts.url && !opts.host) {
        var u = url.parse(opts.url);
        opts.path = u.pathname + (u.search || '');
        opts.host = u.hostname;
        opts.port = u.port || (u.proto === 'https' ? 443 : 80);
    }
    if (!opts.headers) opts.headers = {};
    opts.method = (opts.method || 'GET').toUpperCase();

    if (opts.data) {
        if (opts.method === 'GET') {
            opts.path = opts.path.split('?')[0] + '?' + opts.data;
        }
        else if (opts.method === 'POST') {
            if (!opts.headers['content-length']
            && opts.headers['transfer-encoding'] !== 'chunked') {
                opts.headers['content-length'] = opts.data.length;
            }
        }
    }

    if (!opts.url) {
        opts.url = (opts.proto.replace(/:\/*$/, '') || 'http')
            + opts.host + (opts.port ? ':' + opts.port : '')
            + (opts.path || '/')
        ;
    }

    var doc = jsdom.jsdom('', '3', {
        deferClose : true,
        url : opts.url
    });

    var win = doc.createWindow();
    win.addEventListener('load', function () {
        try {
            cb(win);
        }
        catch (err) {
            self.assert({
                type : 'error',
                error : err
            });
            self.end();
        }
    });

    var req = http.request(opts, function (res) {
        res.on('data', function (buf) {
            doc.write(buf.toString());
        });

        res.on('end', function () {
            doc.close();
        });
    });

    if (opts.method === 'POST' && opts.data) {
        req.write(opts.data + '\r\n');
    }
    req.end();

    return win;
}

function stack () {
    var lines = new Error().stack.split('\n').slice(4,-4);
    return lines.join('\n');
}
<commit_msg>fix to set the window title<commit_after>var http = require('http');
var EventEmitter = require('events').EventEmitter;
var url = require('url');
var path = require('path');

var deepEqual = require('./deep_equal');
var pending = 0;

var test = module.exports = function (name, cb) {
    if (typeof name === 'function') {
        cb = name;
        name = undefined;
    }

    var t = new Test(name, test.push);
    pending ++;

    t.on('testEnd', function () {
        pending --;
        process.nextTick(function () {
            if (pending <= 0) t.push('end', {});
            harness.emit('end', t);
        });
    });

    cb(t);
};

var harness = test.harness = new EventEmitter;

var testId = 0;
function Test (name, push) {
    this.id = testId ++;
    this.push = push;
    push('testBegin', { name : name, testId : this.id });

    this.counts = {
        plan : undefined,
        pass : 0,
        fail : 0
    };
    this.windows = [];
}

Test.prototype = new EventEmitter;

Test.prototype.assert = function (res) {
    if (res.ok) this.counts.pass ++
    else this.counts.fail ++

    if (this.counts.plan !== undefined
    && this.counts.pass + this.counts.fail > this.counts.plan) {
        this.push('fail', {
            type : 'fail',
            ok : false,
            found : this.counts.fail + this.counts.pass,
            wanted : this.counts.plan,
            name : 'more tests run than planned',
            testId : this.id
        });
    }

    res.testId = this.id;
    this.push('assert', res);
    if (!res.ok) res.stack = stack();

    if (this.counts.plan !== undefined
    && this.counts.plan === this.counts.pass + this.counts.fail) {
        this.end();
    }
};

Test.prototype.ok = function (value, name) {
    this.assert({
        type : 'ok',
        ok : !!value,
        name : name,
        found : Boolean(value),
        wanted : true
    });
};

Test.prototype.notOk = function (value, name) {
    this.assert({
        type : 'ok',
        ok : !!!value,
        name : name,
        found : Boolean(value),
        wanted : false
    });
};

Test.prototype.fail = function (value, name) {
    this.assert({
        type : 'fail',
        ok : false,
        name : name,
        found : value,
        wanted : undefined,
        stack : stack()
    });
};

Test.prototype.equal = function (found, wanted, name) {
    this.assert({
        type : 'equal',
        ok : found == wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.notEqual = function (found, wanted, name) {
    this.assert({
        type : 'notEqual',
        ok : found != wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.deepEqual = function (found, wanted, name) {
    this.assert({
        type : 'deepEqual',
        ok : deepEqual(found, wanted),
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.notDeepEqual = function (found, wanted, name) {
    this.assert({
        type : 'notDeepEqual',
        ok : !deepEqual(found, wanted),
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.strictEqual = function (found, wanted, name) {
    this.assert({
        type : 'strictEqual',
        ok : found === wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

Test.prototype.notStrictEqual = function (found, wanted, name) {
    this.assert({
        type : 'strictEqual',
        ok : found !== wanted,
        name : name,
        found : found,
        wanted : wanted
    });
};

function checkThrows (shouldThrow, fn, expected, name) {
    if (typeof expected === 'string') {
        name = expected;
        expected = null;
    }
    var ok = !shouldThrow, err = undefined;

    try { fn() }
    catch (e) {
        ok = !ok;
        err = e;
    }

    this.assert({
        type : shouldThrow ? 'throws' : 'doesNotThrow',
        ok : ok,
        found : err,
        expected : expected
    });
}

Test.prototype['throws'] = function (fn, expected, name) {
    checkThrows.call(this, true, fn, expected, name);
};

Test.prototype.doesNotThrow = function (fn, expected, name) {
    checkThrows.call(this, false, fn, expected, name);
};

Test.prototype.ifError = function (err, name) {
    this.assert({
        type : 'ifError',
        ok : !!!err,
        name : name,
        found : err,
        wanted : undefined
    });
};

Test.prototype.plan = function (n) {
    if (this.counts.plan === undefined) {
        this.counts.plan = n;
    }
    else {
        this.counts.plan += n;
    }
    this.push('plan', { testId : this.id, n : n });
};

Test.prototype.log = function (msg) {
    this.push('log', { testId : this.id, message : msg });
};

Test.prototype.end = function () {
    if (this.counts.plan !== undefined
    && this.counts.plan > this.counts.fail + this.counts.pass) {
        this.push('planFail', {
            type : 'fail',
            ok : false,
            found : this.counts.fail + this.counts.pass,
            wanted : this.counts.plan,
            name : 'more tests planned than run',
            testId : this.id
        });
    }

    if (!this.ended) {
        this.ended = true;
        this.push('testEnd', { testId : this.id });
        this.emit('testEnd');
    }
};

var jsdom = require('jsdom');

Test.prototype.createWindow = function (url, opts, cb) {
    if (typeof url === 'object') {
        cb = opts;
        opts = url;
        url = opts.url;
    }

    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    opts.url = url;

    var win = createWindow(this, opts, cb);
    this.windows.push(win);
    return win;
};

Test.prototype.submitForm = function (form, params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }
    if (!params) params = {};

    if (form[0]) {
        if (form[0] instanceof jsdom.defaultLevel.HTMLFormElement
        || form[0].elements) {
            form = form[0];
        }
    }

    if (!form.elements) {
        this.fail('encountered a non-form element');
        return;
    }

    var pairs = [];

    var len = 0;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name) {
            len += form.elements[i].name.length
                + 1 + form.elements[i].value.length;
            pairs.push(
                escape(form.elements[i].name)
                + '='
                + escape(form.elements[i].value)
            );
        }
    }

    var data = pairs.join('&');
    var pwin = form.ownerDocument.parentWindow;

    var opts = {
        url : form.action || pwin.location.href.split('?')[0],
        method : form.method || 'GET',
        data : data,
        headers : params.headers || {}
    };

    if (!opts.url.match(/^https?:/)) {
        opts.url = pwin.location.protocol + '//' + pwin.location.host
            + path.resolve(path.dirname(pwin.location.path), opts.url)
        ;
    }

    if (opts.method === 'POST') {
        if (!opts.headers['content-length']
        && opts.headers['transfer-encoding'] !== 'chunked') {
            opts.headers['content-length'] = len + 1;
        }
    }

    var win = createWindow(this, opts, cb);
    this.windows.push(win);
    return win;
};

function createWindow (self, opts, cb) {
    if (opts.url && !opts.host) {
        var u = url.parse(opts.url);
        opts.path = u.pathname + (u.search || '');
        opts.host = u.hostname;
        opts.port = u.port || (u.proto === 'https' ? 443 : 80);
    }
    if (!opts.headers) opts.headers = {};
    opts.method = (opts.method || 'GET').toUpperCase();

    if (opts.data) {
        if (opts.method === 'GET') {
            opts.path = opts.path.split('?')[0] + '?' + opts.data;
        }
        else if (opts.method === 'POST') {
            if (!opts.headers['content-length']
            && opts.headers['transfer-encoding'] !== 'chunked') {
                opts.headers['content-length'] = opts.data.length;
            }
        }
    }

    if (!opts.url) {
        opts.url = (opts.proto.replace(/:\/*$/, '') || 'http')
            + opts.host + (opts.port ? ':' + opts.port : '')
            + (opts.path || '/')
        ;
    }

    var html = '';
    var doc = jsdom.jsdom(html, '3', {
        deferClose : true,
        url : opts.url
    });

    var win = doc.createWindow();
    win.addEventListener('load', function () {
        var ts = doc.getElementsByTagName('title');
        if (ts.length) doc.title = ts[0] && ts[0].textContent || '';

        try {
            cb(win);
        }
        catch (err) {
            self.assert({
                type : 'error',
                error : err
            });
            self.end();
        }
    });

    var req = http.request(opts, function (res) {
        res.on('data', function (buf) {
            doc.write(buf.toString());
        });

        res.on('end', function () {
            doc.close();
        });
    });

    if (opts.method === 'POST' && opts.data) {
        req.write(opts.data + '\r\n');
    }
    req.end();

    return win;
}

function stack () {
    var lines = new Error().stack.split('\n').slice(4,-4);
    return lines.join('\n');
}
<|endoftext|>


<commit_before>'use strict';

var Pagelet = require('bigpipe').Pagelet
  , read = require('fs').readFileSync
  , lexer = require('marked').lexer
  , renderme = require('renderme')
  , path = require('path');

/**
 * The representation of a single README source.
 *
 * @constructor
 * @param {String} name The name of module who's README.
 * @api private
 */
function Source(name, remove) {
  if (!(this instanceof Source)) return new Source(name, remove);

  remove = remove || [];
  var directory = path.dirname(require.resolve(name));

  this.json = require(path.join(directory, 'package.json'));
  this.file = path.join(directory, 'README.md');
  this.content = read(this.file, 'utf-8');
  this.tableofcontents = null;
  this.name = name;
  this.html = '';

  this.toc().remove(remove);
}

/**
 * Render the markdown file.
 *
 * @param {Function} fn
 * @api private
 */
Source.prototype.render = function render(fn) {
  if (this.html) return fn(undefined, this.html);

  var source = this;

  renderme({
    renderFilename: this.file,
    readme: this.content
  }, {
    limit: Infinity,
    github: {
      user: 'bigpipe',
      repo: this.name
    }
  }, function rendered(err, html) {
    if (err) return fn(err);

    fn(undefined, (source.html = html));
  });
};

/**
 * There are parts in this content that we don't really need. We should remove
 * these whole sections. We assume that these sections are separated by headers
 * of their same size.
 *
 * @param {Array} headers Sections that need to be removed
 * @returns {Source}
 * @api private
 */
Source.prototype.remove = function remove(headers) {
  var lines = this.content.split(/\n/g)
    , removal = Array(10).join('@_@-<3>-@_@')
    , indexes = {};

  //
  // First we're going to catalog all the locations/indexes of each header.
  //
  lines.forEach(function each(line, index) {
    line = line.trim();

    if (/^\#+/.test(line)) indexes[line.toLowerCase()] = index;
  });

  headers.forEach(function each(section) {
    section = section.toLowerCase();

    Object.keys(indexes).forEach(function each(header, index, all) {
      if (!~header.indexOf(section)) return;

      var last = indexes[all[index + 1]] || lines.length
        , start = indexes[header];

      while (start < last) {
        //
        // Don't move potential [name]: http://url lines or we will break URLS.
        //
        if (!/\^\[\w\]\:/.test(lines[start])) lines[start] = removal;
        start++;
      }
    });
  });

  this.content = lines.filter(function filter(line) {
    return line !== removal;
  }).join('\n');
};

/**
 * Generate a Table of contents if none is available.
 *
 * @returns {Source}
 * @api private
 */
Source.prototype.toc = function toc() {
  if (this.tableofcontents) return this;

  var navigation = lexer(this.content).filter(function filter(token) {
    return token.type === 'heading' && (token.depth === 2 || token.depth === 3);
  });

  var ticktoc = {}
    , currently;

  navigation.forEach(function forEach(token) {
    var name = token.text
      , id;

    id = name.replace(/[\.|\#]/g, '')     // Remove dots and others.
             .replace(/[^\w]+/g, '-')     // All none-words are now -'s>
             .replace(/[\-]+$/, '')       // Remove suffixed -'s.
             .toLowerCase();              // Always lowercase things.

    if (2 === token.depth) {
      ticktoc[id] = { name: name };
      currently = id;
    } else if (ticktoc[currently]) {
      (ticktoc[currently].sections = ticktoc[currently].sections || []).push({
        name: name,
        id: id
      });
    }
  });

  //
  // If we an table of contents, we should just use that.
  //
  if ('table-of-contents' in ticktoc) ticktoc = ticktoc['table-of-contents'];
  if (Object.keys(ticktoc).length) this.tableofcontents = ticktoc;

  return this;
};

/**
 * Expose a rendered set of our components.
 *
 * @type {Object}
 * @api private
 */
Source.components = {
  'bigpipe': new Source('bigpipe', ['license', 'testing', 'table of contents']),
  'pagelet': new Source('pagelet', ['installation', 'license', 'table of contents']),
  'client': new Source('pipe.js', ['installation', 'license', 'table of contents'])
};

/**
 * A general Source pagelet which will correctly render the README files.
 *
 * @type {Pagelet}
 * @api private
 */
Source.Pagelet = Pagelet.extend({
  view: 'project.ejs',
  css:  'project.styl',

  get: function get(next) {
    var project = Source.components[this.component]
      , pagelet = this;

    project.render(function render(err, html) {
      next(err, {
        README: html,
        project: project
      });
    });
  }
}).on(module);

//
// Things that should be exposed, should be called before `Source.Pagelet.on` so
// we can override the module.exports again.
//
module.exports = Source;
<commit_msg>[fix] Correctly test against urls.<commit_after>'use strict';

var Pagelet = require('bigpipe').Pagelet
  , read = require('fs').readFileSync
  , lexer = require('marked').lexer
  , renderme = require('renderme')
  , path = require('path');

/**
 * The representation of a single README source.
 *
 * @constructor
 * @param {String} name The name of module who's README.
 * @api private
 */
function Source(name, remove) {
  if (!(this instanceof Source)) return new Source(name, remove);

  remove = remove || [];
  var directory = path.dirname(require.resolve(name));

  this.json = require(path.join(directory, 'package.json'));
  this.file = path.join(directory, 'README.md');
  this.content = read(this.file, 'utf-8');
  this.tableofcontents = null;
  this.name = name;
  this.html = '';

  this.toc().remove(remove);
}

/**
 * Render the markdown file.
 *
 * @param {Function} fn
 * @api private
 */
Source.prototype.render = function render(fn) {
  if (this.html) return fn(undefined, this.html);

  var source = this;

  renderme({
    renderFilename: this.file,
    readme: this.content
  }, {
    limit: Infinity,
    github: {
      user: 'bigpipe',
      repo: this.name
    }
  }, function rendered(err, html) {
    if (err) return fn(err);

    fn(undefined, (source.html = html));
  });
};

/**
 * There are parts in this content that we don't really need. We should remove
 * these whole sections. We assume that these sections are separated by headers
 * of their same size.
 *
 * @param {Array} headers Sections that need to be removed
 * @returns {Source}
 * @api private
 */
Source.prototype.remove = function remove(headers) {
  var lines = this.content.split(/\n/g)
    , removal = Array(10).join('@_@-<3>-@_@')
    , indexes = {};

  //
  // First we're going to catalog all the locations/indexes of each header.
  //
  lines.forEach(function each(line, index) {
    line = line.trim();

    if (/^\#+/.test(line)) indexes[line.toLowerCase()] = index;
  });

  headers.forEach(function each(section) {
    section = section.toLowerCase();

    Object.keys(indexes).forEach(function each(header, index, all) {
      if (!~header.indexOf(section)) return;

      var last = indexes[all[index + 1]] || lines.length
        , start = indexes[header];

      while (start < last) {
        //
        // Don't move potential [name]: http://url lines or we will break URLS.
        //
        if (!/^\[\w+\]\:/.test(lines[start])) {
          lines[start] = removal;
        }

        start++;
      }
    });
  });

  this.content = lines.filter(function filter(line) {
    return line !== removal;
  }).join('\n');
};

/**
 * Generate a Table of contents if none is available.
 *
 * @returns {Source}
 * @api private
 */
Source.prototype.toc = function toc() {
  if (this.tableofcontents) return this;

  var navigation = lexer(this.content).filter(function filter(token) {
    return token.type === 'heading' && (token.depth === 2 || token.depth === 3);
  });

  var ticktoc = {}
    , currently;

  navigation.forEach(function forEach(token) {
    var name = token.text
      , id;

    id = name.replace(/[\.|\#]/g, '')     // Remove dots and others.
             .replace(/[^\w]+/g, '-')     // All none-words are now -'s>
             .replace(/[\-]+$/, '')       // Remove suffixed -'s.
             .toLowerCase();              // Always lowercase things.

    if (2 === token.depth) {
      ticktoc[id] = { name: name };
      currently = id;
    } else if (ticktoc[currently]) {
      (ticktoc[currently].sections = ticktoc[currently].sections || []).push({
        name: name,
        id: id
      });
    }
  });

  //
  // If we an table of contents, we should just use that.
  //
  if ('table-of-contents' in ticktoc) ticktoc = ticktoc['table-of-contents'];
  if (Object.keys(ticktoc).length) this.tableofcontents = ticktoc;

  return this;
};

/**
 * Expose a rendered set of our components.
 *
 * @type {Object}
 * @api private
 */
Source.components = {
  'bigpipe': new Source('bigpipe', ['license', 'testing', 'table of contents']),
  'pagelet': new Source('pagelet', ['installation', 'license', 'table of contents']),
  'client': new Source('pipe.js', ['installation', 'license', 'table of contents'])
};

/**
 * A general Source pagelet which will correctly render the README files.
 *
 * @type {Pagelet}
 * @api private
 */
Source.Pagelet = Pagelet.extend({
  view: 'project.ejs',
  css:  'project.styl',

  get: function get(next) {
    var project = Source.components[this.component]
      , pagelet = this;

    project.render(function render(err, html) {
      next(err, {
        README: html,
        project: project
      });
    });
  }
}).on(module);

//
// Things that should be exposed, should be called before `Source.Pagelet.on` so
// we can override the module.exports again.
//
module.exports = Source;
<|endoftext|>


<commit_before>import { Text } from './core'
import { CharacterDataAssembler } from './characterdata'

/**
 * Text DOM node assembler
 */
export class TextAssembler extends CharacterDataAssembler {
    /**
     * Remove all the adjacent Text nodes and set
     * the `wholeText` property value as a data of the node
     * @param {String} wholeText
     */
    set wholeText(wholeText) {
        let sibling = this.node
        while(sibling = sibling.previousSibling) {
            if(sibling instanceof Text) sibling.remove()
            else break
        }
        while(sibling = sibling.nextSibling) {
            if(sibling instanceof Text) sibling.remove()
            else break
        }
        this.data = wholeText
    }

    /**
     * Get the wholeText of the node
     * @returns {String}
     */
    get wholeText() {
        return this.node.wholeText
    }

    /**
     * Create the specified Text node
     * @param {String} data
     * @returns {Text}
     */
    static create({ data }) {
        return this.document.createTextNode(data)
    }
}

/**
 * Text assembler factory
 * @param {{}|Node|String|NodeAssembler|Array} [init]
 * @returns {TextAssembler}
 */
export function text(init) {
    return new TextAssembler(init)
}
<commit_msg>Fix hole<commit_after>import { Text } from './core'
import { CharacterDataAssembler } from './characterdata'

/**
 * Text DOM node assembler
 */
export class TextAssembler extends CharacterDataAssembler {
    /**
     * Remove all the adjacent Text nodes and set
     * the `wholeText` property value as a data of the node
     * @param {String} wholeText
     */
    set wholeText(wholeText) {
        let sibling = this.node
        while(sibling = sibling.previousSibling) {
            if(sibling instanceof Text) sibling.remove()
            else break
        }
        while(sibling = sibling.nextSibling) {
            if(sibling instanceof Text) sibling.remove()
            else break
        }
        this.data = wholeText
    }

    /**
     * Get the wholeText of the node
     * @returns {String}
     */
    get wholeText() {
        return this.node.wholeText
    }

    /**
     * Create the specified Text node
     * @param {String} data
     * @returns {Text}
     */
    static create({ data }) {
        return this.document.createTextNode(data)
    }
}

/**
 * Text assembler factory
 * @param {{}|Node|String|NodeAssembler|Array} [init]
 * @returns {TextAssembler}
 */
export function text(init) {
    return new TextAssembler(init)
}
<|endoftext|>


<commit_before>function retrieveRazonesSociales(idCliente){
	var k, n;
	var appendSection = $("#id-razon-social");
	appendSection.find("*").remove();

	$.ajax({
		url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/getRazonesSociales/"+idCliente,
		method: 'post',
		dataType: 'json',
		success: function(response){
			appendSection.append("<option value='-1'>Ninguna</option>");
			for(k=0, n=response.length; k<n; k++){
				appendSection.append("<option value='"+response[k].id+"'>"+response[k].razonSocial+"</option>");
			}
		},
		error: function(){
			alert("Ha ocurrido un error. Intente de nuevo, por favor.");
		}
	});
}

function retrieveCotizaciones(idRazonSocial){
	var k, n;
	var appendSection = $("#id-cotizacion");
	appendSection.find("*").remove();

	$.ajax({
		url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/getCotizaciones/"+idRazonSocial,
		method: 'post',
		dataType: 'json',
		success: function(response){
			appendSection.append("<option value='-1'>Ninguna</option>");
			for(k=0, n=response.length; k<n; k++){
				appendSection.append("<option value='"+response[k].id+"'>"+response[k].folio+"</option>");
			}
		},
		error: function(){
			alert("Ha ocurrido un error. Intente de nuevo, por favor.");
		}
	});
}

function retrieveClasificaciones(sender){
	var idServicio = sender.val();
	var appendSection = sender.closest(".clone-section-concepto").first().find("#clasificacion-concepto");

	$.ajax({
		url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/getClasificaciones",
		method: 'post',
		dataType: 'json',
		data: {'idServicio': idServicio},
		success: function(response){
			appendSection.find("option").remove();

			appendSection.append("<option value='-1'>Seleccione una opción</option>");
			for(k=0, n=response.length; k<n; k++){
				appendSection.append("<option value='"+response[k].id+"'>"+response[k].clave+"</option>");
			}
		},
		error: function(){
			alert("Ha ocurrido un error. Intente de nuevo, por favor.");
		}
	});
}

function revisarCamposObligatorios(){
	var message = "";
	var errores = 0;

	var folioCotizacion = $("#folio-cotizacion").val();
	var accountManager = $("#id_account_manager").val();
	var cerrador = $("#id_cerrador").val();

	var servicio = $("#append-section-concepto .servicio-concepto");
	var clasificacion = $("#append-section-concepto .clasificacion-concepto");

	var importe = $(".append-section-fecha-factura .importe-fecha-factura");

	if(folioCotizacion.trim() == ""){
		errores++;
		message = "El folio de la cotiación es un campo obligatorio";
	}else if(accountManager == "-1"){
		errores++;
		message = "Ingrese al account manager que llevará la cotización";
	}else if(cerrador == "-1"){
		errores++;
		message = "Ingrese al cerrador de la cotización";
	}

	servicio.each(function(index){
		if($(this).val() == "-1"){
			errores++;
			message = "Debe seleccionar el servicio correspondiente a cada concepto";
		}
	});

	clasificacion.each(function(index){
		if($(this).val() == "-1"){
			errores++;
			message = "Debe seleccionar la categoria correspondiente a cada concepto";
		}
	});

	importe.each(function(index){
		if($(this).val().trim() == ""){
			errores++;
			message = "Debe ingresar el importe correspondiente a cada fecha de facturación";
		}
	});

	if(errores > 0){
		alert(message);
		return false;
	}else return true;
}

$(function(){
	$("#id-cliente").change(function(event){
		event.preventDefault();

		retrieveRazonesSociales($(this).val());
	});

	$(".servicio-concepto").change(function(){
		retrieveClasificaciones($(this));
	});

	$("#btn-add-concepto").click(function(event){
		event.preventDefault();

		var appendSection = $("#append-section-concepto");
		var cloneSection = $("#clone-section-concepto").clone(true);

		cloneSection.attr("id", "clone-section-concepto-"+appendSection.find(".clone-section-concepto").size());
		cloneSection.show();

		cloneSection.find("#btn-add-fecha-factura").click(function(event){
			event.preventDefault();

			var sender = $(this);
			var parent_section = sender.closest(".clone-section-concepto").first();
			var append_section_fecha = parent_section.find("#append-section-fecha-factura");

			var clon = jCloneSection($("#clone-section-fecha-factura"), append_section_fecha);
			jInitDatepicker(clon.find("#fecha-factura"), clon.find("#fecha-factura-alt"), "dd/mm/yy", "yy-mm-dd");

			// Asociar evento de cambio de importe, para recalcular totales de concepto padre
			clon.find("#importe-fecha-factura").change(function(){
				var importes = append_section_fecha.find(".importe-fecha-factura");
				var importeSuma = 0;
				var totalSuma = 0;
				var padre = $(this).closest(".clone-section-concepto").first();
				var importeImp = padre.find("#importe-concepto");
				var totalImp = padre.find("#total-concepto");
				var iva = (parseFloat(padre.find("#iva").val()) / 100) + 1;
				var valor = 0;

				importes.each(function(i){
					valor = $(this).val();
					if(valor == "") valor = 0;
					else valor = parseFloat(valor);

					importeSuma += valor;
				});

				totalSuma = importeSuma * iva;
				importeImp.val(importeSuma.toFixed(2));
				totalImp.val(totalSuma.toFixed(2));
			});

			clon.find("#btn-destroy-fecha").click(function(){
				clon.remove();
			});
		});

		cloneSection.find("#iva, #importe-concepto").change(function(){
			var importe = cloneSection.find("#importe-concepto").val();
			var totalImp = cloneSection.find("#total-concepto");
			var iva = (parseFloat(cloneSection.find("#iva").val()) / 100) + 1;

			if(importe == "") importe = 0;
			else importe = parseFloat(importe);

			totalImp.val((importe*iva).toFixed(2));
		});

		cloneSection.find("#btn-destroy-concepto").click(function(){
			cloneSection.remove();
		});

		appendSection.append(cloneSection);
	});

	$("#id-cotizacion").change(function(){
		var cVal = $(this).val();

		if(cVal == -1){
			$("#folio-cotizacion").show();
		}else{
			$("#folio-cotizacion").hide();
		}
	});

	$("#btn-save-cotizacion").click(function(event){
		event.preventDefault();

		if(!revisarCamposObligatorios()) return false;

		var idCliente = $("#id-cliente").val();
		var folioCotizacion = $("#folio-cotizacion").val();
		var notaCotizacion  = $("#nota-cotizacion").val();
		var fechaJuntaArranque = $("#alt_fecha_junta_arranque").val();
		var fechaVenta = $("#alt_fecha_venta").val();
		var fechaInicioProyecto = $("#alt_fecha_inicio_proyecto").val();
		var fechaFinProyecto = $("#alt_fecha_fin_proyecto").val();
		var idCerrador = $("#id_cerrador").val();
		var accountManager = $("#id_account_manager").val();
		var tituloCotizacion = $("#titulo_cot").val();

		// Asociar los conceptos con sus fechas de facturación
		// array( array("concepto", array({FECHA_1}, ...)), ... )
		var conceptos = new Array();
		var sc_conceptos = $("#append-section-concepto .clone-section-concepto");
		var concepto, fechaFactura;
		var sc_fecha_factura;
		var current, currentFecha;
		var cConcepto;
		var i, k;

		sc_conceptos.each(function(index){
			current = $(this);

			concepto = {
				descripcion : current.find("#descripcion-concepto").val(),
				referencia : current.find("#referencia-concepto").val(),
				nota : current.find("#nota-concepto").val(),
				importe : current.find("#importe-concepto").val(),
				total : current.find("#total-concepto").val(),
				fechasFactura : new Array(),
				servicio: current.find("#servicio-concepto").val(),
				clasificacion: current.find("#clasificacion-concepto").val(),
				iva: current.find("#iva").val()
			};

			sc_fecha_factura = current.find("#append-section-fecha-factura .clone-section-fecha-factura");

			sc_fecha_factura.each(function(index){
				currentFecha = $(this);
				fecha_factura = {
					importe : currentFecha.find("#importe-fecha-factura").val(),
					referencia : currentFecha.find("#referencia-fecha-factura").val(),
					nota : currentFecha.find("#nota-fecha-factura").val(),
					fecha : currentFecha.find("input[name='fecha-factura-alt[]']").val()
				};

				concepto.fechasFactura.push(fecha_factura);
			});

			conceptos.push(concepto);
		});

		$.ajax({
			url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/guardarCotizacion",
			method: 'post',
			dataType: 'text',
			data: {"conceptos":JSON.stringify(conceptos),"idCliente":idCliente,"folioCotizacion":folioCotizacion,"notaCotizacion":notaCotizacion,"fechaJuntaArranque":fechaJuntaArranque,"fechaVenta":fechaVenta,"fechaInicioProyecto":fechaInicioProyecto,"fechaFinProyecto":fechaFinProyecto,"idCerrador":idCerrador,"accountManager":accountManager,"tituloCotizacion":tituloCotizacion},
			success: function(response){
				alert("Operación realizada con éxito");
				//window.location.replace(baseURL+"index.php/Panel_control_ctrl");
			},
			error: function(){
				alert("Ha ocurrido un error. Intente de nuevo, por favor.");
			}
		});
	});

	initDatepicker("#fecha_junta_arranque", "#alt_fecha_junta_arranque", "dd/mm/yy", "yy-mm-dd");
	initDatepicker("#fecha_venta", "#alt_fecha_venta", "dd/mm/yy", "yy-mm-dd");
	initDatepicker("#fecha_inicio_proyecto", "#alt_fecha_inicio_proyecto", "dd/mm/yy", "yy-mm-dd");
	initDatepicker("#fecha_fin_proyecto", "#alt_fecha_fin_proyecto", "dd/mm/yy", "yy-mm-dd");
});<commit_msg>Cambios<commit_after>function retrieveRazonesSociales(idCliente){
	var k, n;
	var appendSection = $("#id-razon-social");
	appendSection.find("*").remove();

	$.ajax({
		url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/getRazonesSociales/"+idCliente,
		method: 'post',
		dataType: 'json',
		success: function(response){
			appendSection.append("<option value='-1'>Ninguna</option>");
			for(k=0, n=response.length; k<n; k++){
				appendSection.append("<option value='"+response[k].id+"'>"+response[k].razonSocial+"</option>");
			}
		},
		error: function(){
			alert("Ha ocurrido un error. Intente de nuevo, por favor.");
		}
	});
}

function retrieveCotizaciones(idRazonSocial){
	var k, n;
	var appendSection = $("#id-cotizacion");
	appendSection.find("*").remove();

	$.ajax({
		url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/getCotizaciones/"+idRazonSocial,
		method: 'post',
		dataType: 'json',
		success: function(response){
			appendSection.append("<option value='-1'>Ninguna</option>");
			for(k=0, n=response.length; k<n; k++){
				appendSection.append("<option value='"+response[k].id+"'>"+response[k].folio+"</option>");
			}
		},
		error: function(){
			alert("Ha ocurrido un error. Intente de nuevo, por favor.");
		}
	});
}

function retrieveClasificaciones(sender){
	var idServicio = sender.val();
	var appendSection = sender.closest(".clone-section-concepto").first().find("#clasificacion-concepto");

	$.ajax({
		url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/getClasificaciones",
		method: 'post',
		dataType: 'json',
		data: {'idServicio': idServicio},
		success: function(response){
			appendSection.find("option").remove();

			appendSection.append("<option value='-1'>Seleccione una opción</option>");
			for(k=0, n=response.length; k<n; k++){
				appendSection.append("<option value='"+response[k].id+"'>"+response[k].clave+"</option>");
			}
		},
		error: function(){
			alert("Ha ocurrido un error. Intente de nuevo, por favor.");
		}
	});
}

function revisarCamposObligatorios(){
	var message = "";
	var errores = 0;

	var idCliente = $("#id-cliente").val();
	var folioCotizacion = $("#folio-cotizacion").val();
	var accountManager = $("#id_account_manager").val();
	var cerrador = $("#id_cerrador").val();

	var servicio = $("#append-section-concepto .servicio-concepto");
	var clasificacion = $("#append-section-concepto .clasificacion-concepto");

	var importe = $(".append-section-fecha-factura .importe-fecha-factura");

	if(idCliente.trim() == "-1"){
		errores++;
		message = "Debe seleccionar el proveedor al que le pertenece la cotización";
	}else if(folioCotizacion.trim() == ""){
		errores++;
		message = "El folio de la cotización es un campo obligatorio";
	}else if(accountManager == "-1"){
		errores++;
		message = "Ingrese al account manager que llevará la cotización";
	}else if(cerrador == "-1"){
		errores++;
		message = "Ingrese al cerrador de la cotización";
	}

	servicio.each(function(index){
		if($(this).val() == "-1"){
			errores++;
			message = "Debe seleccionar el servicio correspondiente a cada concepto";
		}
	});

	clasificacion.each(function(index){
		if($(this).val() == "-1"){
			errores++;
			message = "Debe seleccionar la categoria correspondiente a cada concepto";
		}
	});

	importe.each(function(index){
		if($(this).val().trim() == ""){
			errores++;
			message = "Debe ingresar el importe correspondiente a cada fecha de facturación";
		}
	});

	if(errores > 0){
		alert(message);
		return false;
	}else return true;
}

$(function(){
	$("#id-cliente").change(function(event){
		event.preventDefault();

		retrieveRazonesSociales($(this).val());
	});

	$(".servicio-concepto").change(function(){
		retrieveClasificaciones($(this));
	});

	$("#btn-add-concepto").click(function(event){
		event.preventDefault();

		var appendSection = $("#append-section-concepto");
		var cloneSection = $("#clone-section-concepto").clone(true);

		cloneSection.attr("id", "clone-section-concepto-"+appendSection.find(".clone-section-concepto").size());
		cloneSection.show();

		cloneSection.find("#btn-add-fecha-factura").click(function(event){
			event.preventDefault();

			var sender = $(this);
			var parent_section = sender.closest(".clone-section-concepto").first();
			var append_section_fecha = parent_section.find("#append-section-fecha-factura");

			var clon = jCloneSection($("#clone-section-fecha-factura"), append_section_fecha);
			jInitDatepicker(clon.find("#fecha-factura"), clon.find("#fecha-factura-alt"), "dd/mm/yy", "yy-mm-dd");

			// Asociar evento de cambio de importe, para recalcular totales de concepto padre
			clon.find("#importe-fecha-factura").change(function(){
				var importes = append_section_fecha.find(".importe-fecha-factura");
				var importeSuma = 0;
				var totalSuma = 0;
				var padre = $(this).closest(".clone-section-concepto").first();
				var importeImp = padre.find("#importe-concepto");
				var totalImp = padre.find("#total-concepto");
				var iva = (parseFloat(padre.find("#iva").val()) / 100) + 1;
				var valor = 0;

				importes.each(function(i){
					valor = $(this).val();
					if(valor == "") valor = 0;
					else valor = parseFloat(valor);

					importeSuma += valor;
				});

				totalSuma = importeSuma * iva;
				importeImp.val(importeSuma.toFixed(2));
				totalImp.val(totalSuma.toFixed(2));
			});

			clon.find("#btn-destroy-fecha").click(function(){
				clon.remove();
			});
		});

		cloneSection.find("#iva, #importe-concepto").change(function(){
			var importe = cloneSection.find("#importe-concepto").val();
			var totalImp = cloneSection.find("#total-concepto");
			var iva = (parseFloat(cloneSection.find("#iva").val()) / 100) + 1;

			if(importe == "") importe = 0;
			else importe = parseFloat(importe);

			totalImp.val((importe*iva).toFixed(2));
		});

		cloneSection.find("#btn-destroy-concepto").click(function(){
			cloneSection.remove();
		});

		appendSection.append(cloneSection);
	});

	$("#id-cotizacion").change(function(){
		var cVal = $(this).val();

		if(cVal == -1){
			$("#folio-cotizacion").show();
		}else{
			$("#folio-cotizacion").hide();
		}
	});

	$("#btn-save-cotizacion").click(function(event){
		event.preventDefault();

		if(!revisarCamposObligatorios()) return false;

		var idCliente = $("#id-cliente").val();
		var folioCotizacion = $("#folio-cotizacion").val();
		var notaCotizacion  = $("#nota-cotizacion").val();
		var fechaJuntaArranque = $("#alt_fecha_junta_arranque").val();
		var fechaVenta = $("#alt_fecha_venta").val();
		var fechaInicioProyecto = $("#alt_fecha_inicio_proyecto").val();
		var fechaFinProyecto = $("#alt_fecha_fin_proyecto").val();
		var idCerrador = $("#id_cerrador").val();
		var accountManager = $("#id_account_manager").val();
		var tituloCotizacion = $("#titulo_cot").val();

		// Asociar los conceptos con sus fechas de facturación
		// array( array("concepto", array({FECHA_1}, ...)), ... )
		var conceptos = new Array();
		var sc_conceptos = $("#append-section-concepto .clone-section-concepto");
		var concepto, fechaFactura;
		var sc_fecha_factura;
		var current, currentFecha;
		var cConcepto;
		var i, k;

		sc_conceptos.each(function(index){
			current = $(this);

			concepto = {
				descripcion : current.find("#descripcion-concepto").val(),
				referencia : current.find("#referencia-concepto").val(),
				nota : current.find("#nota-concepto").val(),
				importe : current.find("#importe-concepto").val(),
				total : current.find("#total-concepto").val(),
				fechasFactura : new Array(),
				servicio: current.find("#servicio-concepto").val(),
				clasificacion: current.find("#clasificacion-concepto").val(),
				iva: current.find("#iva").val()
			};

			sc_fecha_factura = current.find("#append-section-fecha-factura .clone-section-fecha-factura");

			sc_fecha_factura.each(function(index){
				currentFecha = $(this);
				fecha_factura = {
					importe : currentFecha.find("#importe-fecha-factura").val(),
					referencia : currentFecha.find("#referencia-fecha-factura").val(),
					nota : currentFecha.find("#nota-fecha-factura").val(),
					fecha : currentFecha.find("input[name='fecha-factura-alt[]']").val()
				};

				concepto.fechasFactura.push(fecha_factura);
			});

			conceptos.push(concepto);
		});

		$.ajax({
			url: baseURL+"index.php/Alta_conceptos_cotizacion_ctrl/guardarCotizacion",
			method: 'post',
			dataType: 'text',
			data: {"conceptos":JSON.stringify(conceptos),"idCliente":idCliente,"folioCotizacion":folioCotizacion,"notaCotizacion":notaCotizacion,"fechaJuntaArranque":fechaJuntaArranque,"fechaVenta":fechaVenta,"fechaInicioProyecto":fechaInicioProyecto,"fechaFinProyecto":fechaFinProyecto,"idCerrador":idCerrador,"accountManager":accountManager,"tituloCotizacion":tituloCotizacion},
			success: function(response){
				alert("Operación realizada con éxito");
				//window.location.replace(baseURL+"index.php/Panel_control_ctrl");
			},
			error: function(){
				alert("Ha ocurrido un error. Intente de nuevo, por favor.");
			}
		});
	});

	initDatepicker("#fecha_junta_arranque", "#alt_fecha_junta_arranque", "dd/mm/yy", "yy-mm-dd");
	initDatepicker("#fecha_venta", "#alt_fecha_venta", "dd/mm/yy", "yy-mm-dd");
	initDatepicker("#fecha_inicio_proyecto", "#alt_fecha_inicio_proyecto", "dd/mm/yy", "yy-mm-dd");
	initDatepicker("#fecha_fin_proyecto", "#alt_fecha_fin_proyecto", "dd/mm/yy", "yy-mm-dd");
});<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// @ts-check
'use strict';

var updateGrammar = require('vscode-grammar-updater');

function removeDom(grammar) {
	grammar.repository['support-objects'].patterns = grammar.repository['support-objects'].patterns.filter(pattern => {
		if (pattern.match && /\b(HTMLElement|ATTRIBUTE_NODE|stopImmediatePropagation)\b/g.test(pattern)) {
			return false;
		}
		return true;
	});
	return grammar;
}

function removeNodeTypes(grammar) {
	grammar.repository['support-objects'].patterns = grammar.repository['support-objects'].patterns.filter(pattern => {
		if (pattern.name) {
			if (pattern.name.startsWith('support.variable.object.node') || pattern.name.startsWith('support.class.node.')) {
				return false;
			}
		}
		if (pattern.captures) {
			if (Object.values(pattern.captures).some(capture =>
				capture.name && (capture.name.startsWith('support.variable.object.process')
					|| capture.name.startsWith('support.class.console'))
			)) {
				return false;
			}
		}
		return true;
	});
	return grammar;
}

function patchJsdoctype(grammar) {
	grammar.repository['jsdoctype'].patterns = grammar.repository['jsdoctype'].patterns.filter(pattern => {
		if (pattern.name && pattern.name.indexOf('illegal') >= -1) {
			return false;
		}
		return true;
	});
	return grammar;
}

function patchGrammar(grammar) {
	return removeNodeTypes(removeDom(patchJsdoctype(grammar)));
}

function adaptToJavaScript(grammar, replacementScope) {
	grammar.name = 'JavaScript (with React support)';
	grammar.fileTypes = ['.js', '.jsx', '.es6', '.mjs', '.cjs'];
	grammar.scopeName = `source${replacementScope}`;

	var fixScopeNames = function (rule) {
		if (typeof rule.name === 'string') {
			rule.name = rule.name.replace(/\.tsx/g, replacementScope);
		}
		if (typeof rule.contentName === 'string') {
			rule.contentName = rule.contentName.replace(/\.tsx/g, replacementScope);
		}
		for (var property in rule) {
			var value = rule[property];
			if (typeof value === 'object') {
				fixScopeNames(value);
			}
		}
	};

	var repository = grammar.repository;
	for (var key in repository) {
		fixScopeNames(repository[key]);
	}
}

var tsGrammarRepo = 'microsoft/TypeScript-TmLanguage';
updateGrammar.update(tsGrammarRepo, 'TypeScript.tmLanguage', './syntaxes/TypeScript.tmLanguage.json', grammar => patchGrammar(grammar));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', './syntaxes/TypeScriptReact.tmLanguage.json', grammar => patchGrammar(grammar));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', '../javascript/syntaxes/JavaScript.tmLanguage.json', grammar => adaptToJavaScript(patchGrammar(grammar), '.js'));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', '../javascript/syntaxes/JavaScriptReact.tmLanguage.json', grammar => adaptToJavaScript(patchGrammar(grammar), '.js.jsx'));
<commit_msg>Fix tested pattern<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// @ts-check
'use strict';

var updateGrammar = require('vscode-grammar-updater');

function removeDom(grammar) {
	grammar.repository['support-objects'].patterns = grammar.repository['support-objects'].patterns.filter(pattern => {
		if (pattern.match && /\b(HTMLElement|ATTRIBUTE_NODE|stopImmediatePropagation)\b/g.test(pattern.match)) {
			return false;
		}
		return true;
	});
	return grammar;
}

function removeNodeTypes(grammar) {
	grammar.repository['support-objects'].patterns = grammar.repository['support-objects'].patterns.filter(pattern => {
		if (pattern.name) {
			if (pattern.name.startsWith('support.variable.object.node') || pattern.name.startsWith('support.class.node.')) {
				return false;
			}
		}
		if (pattern.captures) {
			if (Object.values(pattern.captures).some(capture =>
				capture.name && (capture.name.startsWith('support.variable.object.process')
					|| capture.name.startsWith('support.class.console'))
			)) {
				return false;
			}
		}
		return true;
	});
	return grammar;
}

function patchJsdoctype(grammar) {
	grammar.repository['jsdoctype'].patterns = grammar.repository['jsdoctype'].patterns.filter(pattern => {
		if (pattern.name && pattern.name.indexOf('illegal') >= -1) {
			return false;
		}
		return true;
	});
	return grammar;
}

function patchGrammar(grammar) {
	return removeNodeTypes(removeDom(patchJsdoctype(grammar)));
}

function adaptToJavaScript(grammar, replacementScope) {
	grammar.name = 'JavaScript (with React support)';
	grammar.fileTypes = ['.js', '.jsx', '.es6', '.mjs', '.cjs'];
	grammar.scopeName = `source${replacementScope}`;

	var fixScopeNames = function (rule) {
		if (typeof rule.name === 'string') {
			rule.name = rule.name.replace(/\.tsx/g, replacementScope);
		}
		if (typeof rule.contentName === 'string') {
			rule.contentName = rule.contentName.replace(/\.tsx/g, replacementScope);
		}
		for (var property in rule) {
			var value = rule[property];
			if (typeof value === 'object') {
				fixScopeNames(value);
			}
		}
	};

	var repository = grammar.repository;
	for (var key in repository) {
		fixScopeNames(repository[key]);
	}
}

var tsGrammarRepo = 'microsoft/TypeScript-TmLanguage';
updateGrammar.update(tsGrammarRepo, 'TypeScript.tmLanguage', './syntaxes/TypeScript.tmLanguage.json', grammar => patchGrammar(grammar));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', './syntaxes/TypeScriptReact.tmLanguage.json', grammar => patchGrammar(grammar));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', '../javascript/syntaxes/JavaScript.tmLanguage.json', grammar => adaptToJavaScript(patchGrammar(grammar), '.js'));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', '../javascript/syntaxes/JavaScriptReact.tmLanguage.json', grammar => adaptToJavaScript(patchGrammar(grammar), '.js.jsx'));
<|endoftext|>


<commit_before>const mkdirp = require('mkdirp'),
    fs = require('fs'),
    Promise = require('bluebird'),
    async = require('async'),
    rimraf = require('rimraf'),
    winston = require('winston');

const servicesLogger = winston.loggers.get('services');

servicesLogger.info("Loading file utils");

exports.ensureExists = function (path) {
    return new Promise(function (resolve, reject) {
        mkdirp(path, function (err) {
            if (err) {
                if (err.code == 'EEXIST') return resolve(null);
                else return reject(err);
            } else return resolve(null);
        });
    });
};

exports.moveFile = function (originalPath, newPath) {
    return new Promise(function (resolve, reject) {
        var readStream = fs.createReadStream(originalPath);
        var writeStream = fs.createWriteStream(newPath);
        readStream.on('error', reject);
        writeStream.on('error', reject);
        readStream.on('close', function () {
            fs.unlink(originalPath, resolve);
        });
        readStream.pipe(writeStream);
    });
};

exports.listFiles = function (path) {
    return new Promise(function (resolve, reject) {
        exports.ensureExists(path).then(function () {
            fs.readdir(path, function (err, files) {
                if (err) return reject(err);
                else return resolve(files);
            });
        }, function (err) {
            return reject(err);
        });
    });
};

exports.deleteFile = function (path) {
    return new Promise(function (resolve, reject) {
        fs.unlink(path, function (err) {
            if (err) {
                if (err.code == 'ENOENT') return resolve();
                else return reject(err);
            }
            else return resolve();
        });
    });
};

exports.rmdirAsync = function (path) {
    return new Promise(function (resolve, reject) {
        rimraf(path, function (err) {
            if (err) return reject(err);
            else return resolve();
        })
    })
}

exports.writeFile = function (path, data, format) {
    format = format ? format : 'utf8';
    return new Promise((resolve, reject) => {
        fs.writeFile(path, data, format, (err) => {
            if (err) return reject(err);
            else return resolve();
        });
    });
};

exports.access = function(path) {
    return new Promise((resolve, reject) =>{
        fs.access(path, (err) => {
            if(err) return reject(err);
            else return resolve();
        })
    });
}

exports.init = function () {
    return exports.ensureExists('./logs').then(() => { return exports.ensureExists('./uploaded') });
}<commit_msg>Added readfile<commit_after>const mkdirp = require('mkdirp'),
    fs = require('fs'),
    Promise = require('bluebird'),
    async = require('async'),
    rimraf = require('rimraf'),
    winston = require('winston');

const servicesLogger = winston.loggers.get('services');

servicesLogger.info("Loading file utils");

exports.ensureExists = function (path) {
    return new Promise(function (resolve, reject) {
        mkdirp(path, function (err) {
            if (err) {
                if (err.code == 'EEXIST') return resolve(null);
                else return reject(err);
            } else return resolve(null);
        });
    });
};

exports.moveFile = function (originalPath, newPath) {
    return new Promise(function (resolve, reject) {
        var readStream = fs.createReadStream(originalPath);
        var writeStream = fs.createWriteStream(newPath);
        readStream.on('error', reject);
        writeStream.on('error', reject);
        readStream.on('close', function () {
            fs.unlink(originalPath, resolve);
        });
        readStream.pipe(writeStream);
    });
};

exports.listFiles = function (path) {
    return new Promise(function (resolve, reject) {
        exports.ensureExists(path).then(function () {
            fs.readdir(path, function (err, files) {
                if (err) return reject(err);
                else return resolve(files);
            });
        }, function (err) {
            return reject(err);
        });
    });
};

exports.deleteFile = function (path) {
    return new Promise(function (resolve, reject) {
        fs.unlink(path, function (err) {
            if (err) {
                if (err.code == 'ENOENT') return resolve();
                else return reject(err);
            }
            else return resolve();
        });
    });
};

exports.rmdirAsync = function (path) {
    return new Promise(function (resolve, reject) {
        rimraf(path, function (err) {
            if (err) return reject(err);
            else return resolve();
        })
    })
}

exports.readFile = function (path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, (err, data) => {
            if (err) return reject(err);
            else return resolve(data);
        })
    })
};

exports.writeFile = function (path, data, format) {
    format = format ? format : 'utf8';
    return new Promise((resolve, reject) => {
        fs.writeFile(path, data, format, (err) => {
            if (err) return reject(err);
            else return resolve();
        });
    });
};

exports.access = function(path) {
    return new Promise((resolve, reject) =>{
        fs.access(path, (err) => {
            if(err) return reject(err);
            else return resolve();
        })
    });
}

exports.init = function () {
    return exports.ensureExists('./logs').then(() => { return exports.ensureExists('./uploaded') });
}<|endoftext|>


<commit_before>"use strict";
angular.module('myApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/login', {
        controller: 'LoginCtrl',
        templateUrl: 'login/login.html'
      });
    }])

    .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', function($scope, Auth, $location, fbutil) {
      $scope.email = null;
      $scope.pass = null;

<<<<<<< HEAD
        // 1is6i5cuasOF7XleD4tq8gncGes2 -> aotten77@gmail.com
        // NxgwFr891rVvi1tsC528khKC1OO2 -> aotten.joinmedia@gmail.com

=======
>>>>>>> 4c2e891472db28e685fc29d1dd038c5368296d64
      $scope.login = function(email, pass) {
        Auth.$authWithOAuthPopup('google', {scope:'email'})
            .then(function (authObject) {
              console.log(authObject);
              var ref = fbutil.ref('users', authObject.uid);
              return fbutil.handler(function(cb) {
                ref.set({email: authObject.google.email, name: authObject.google.cachedUserProfile.name, online: 'true'}, cb);
              });
            })
            .then(function(/* user */) {
              // redirect to the account page
              var authdata = Auth.$getAuth();
              console.log('Login UID = '+authdata.uid);
              $location.path('/account');
            }, function(err) {
              $scope.err = errMessage(err);
            });
      };
    }]);<commit_msg>no message<commit_after>"use strict";
angular.module('myApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/login', {
        controller: 'LoginCtrl',
        templateUrl: 'login/login.html'
      });
    }])

    .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', function($scope, Auth, $location, fbutil) {
      $scope.email = null;
      $scope.pass = null;

      $scope.login = function(email, pass) {
        Auth.$authWithOAuthPopup('google', {scope:'email'})
            .then(function (authObject) {
              console.log(authObject);
              var ref = fbutil.ref('users', authObject.uid);
              return fbutil.handler(function(cb) {
                ref.set({email: authObject.google.email, name: authObject.google.cachedUserProfile.name, online: 'true'}, cb);
              });
            })
            .then(function(/* user */) {
              // redirect to the account page
              var authdata = Auth.$getAuth();
              console.log('Login UID = '+authdata.uid);
              $location.path('/account');
            }, function(err) {
              $scope.err = errMessage(err);
            });
      };
    }]);<|endoftext|>


<commit_before>// @flow weak
/* eslint-disable no-console */

import path from 'path';
import fse from 'fs-extra';

function copyFile(file) {
  const buildPath = path.resolve(__dirname, '../build/', path.basename(file));
  return new Promise((resolve) => {
    fse.copy(
      file,
      buildPath,
      (err) => {
        if (err) throw err;
        resolve();
      },
    );
  })
  .then(() => console.log(`Copied ${file} to ${buildPath}`));
}

function createPackageFile() {
  return new Promise((resolve) => {
    fse.readFile(path.resolve(__dirname, '../package.json'), 'utf8', (err, data) => {
      if (err) {
        throw err;
      }

      resolve(data);
    });
  })
  .then((data) => JSON.parse(data))
  .then((packageData) => {
    const {
      author,
      version,
      description,
      keywords,
      repository,
      license,
      bugs,
      homepage,
      peerDependencies,
      dependencies,
    } = packageData;

    const minimalPackage = {
      name: 'react-move',
      author,
      version,
      description,
      main: './index.js',
      module: './index.es.js',
      'jsnext:main': './index.es.js',
      keywords,
      repository,
      license,
      bugs,
      homepage,
      peerDependencies,
      dependencies,
    };

    return new Promise((resolve) => {
      const buildPath = path.resolve(__dirname, '../build/package.json');
      const data = JSON.stringify(minimalPackage, null, 2);
      fse.writeFile(buildPath, data, (err) => {
        if (err) throw (err);
        console.log(`Created package.json in ${buildPath}`);
        resolve();
      });
    });
  });
}

const files = [
  'README.md',
  'LICENSE',
];

Promise
  .all(files.map((file) => copyFile(file)))
  .then(() => createPackageFile());

<commit_msg>contributors to package.json<commit_after>// @flow weak
/* eslint-disable no-console */

import path from 'path';
import fse from 'fs-extra';

function copyFile(file) {
  const buildPath = path.resolve(__dirname, '../build/', path.basename(file));
  return new Promise((resolve) => {
    fse.copy(
      file,
      buildPath,
      (err) => {
        if (err) throw err;
        resolve();
      },
    );
  }).then(() => console.log(`Copied ${file} to ${buildPath}`));
}

function createPackageFile() {
  return new Promise((resolve) => {
    fse.readFile(path.resolve(__dirname, '../package.json'), 'utf8', (err, data) => {
      if (err) {
        throw err;
      }

      resolve(data);
    });
  }).then((data) => JSON.parse(data))
    .then((packageData) => {
      const {
        version,
        description,
        contributors,
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      } = packageData;

      const minimalPackage = {
        name: 'react-move',
        version,
        description,
        contributors,
        main: './index.js',
        module: './index.es.js',
        'jsnext:main': './index.es.js',
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      };

      return new Promise((resolve) => {
        const buildPath = path.resolve(__dirname, '../build/package.json');
        const data = JSON.stringify(minimalPackage, null, 2);
        fse.writeFile(buildPath, data, (err) => {
          if (err) throw (err);
          console.log(`Created package.json in ${buildPath}`);
          resolve();
        });
      });
    });
}

const files = [
  'README.md',
  'LICENSE',
];

Promise
  .all(files.map((file) => copyFile(file)))
  .then(() => createPackageFile());

<|endoftext|>