<commit_before>// require ./extensor

var
    esPhinx,
    Extensor,
    Iterator;

// IIFE
esPhinx = (function () {
    "use strict";

    return function esPhinx (selector, context) {

        var
            $ = esPhinx,
            mainReference = this,
            collection = [];

        if (!(mainReference instanceof $)) {
            return new $(selector, context);
        }

        if (!context || context.constructor === Text) {
            context = document;
        } else {
            if (typeof context === "string") {
                context = esPhinx(context);
            } else if (!(context instanceof $)) {
                if (!(context instanceof Node)) {
                    throw new Error("An invalid or illegal context was specified.");
                }
            }
        }

        if (selector) {
            // recognize tagName
            // ([^<][^ >]+)
            // to get attributes?
            // selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
            // get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
            if (selector instanceof $) {
                return selector;
            } else if (typeof selector === "function") {
                return document
                    .addEventListener("DOMContentLoaded", function (e) {
                    selector.call($, e);
                });
            } else if (typeof selector === "string") {
                // recognize a Element
                if (/([\n ]*((<((([a-zA-Z]+)( +(\w|\w+-+\w*)+ *= *(( *(\w|\w+-+\w*)+ *)|((") *.+ *("))|((') *.+ *('))|(\\" *.+ *\\")|(\\' *.+ *\\')))* *((\/)|(>([ \n]|.)*<\/[a-zA-Z]+)))|(!--([ \n]|.)*--))>)([\n ]*<((([a-zA-Z]+)( +(\w|\w+-+\w*)+ *= *(( *(\w|\w+-+\w*)+ *)|((") *.+ *("))|((') *.+ *('))|(\\" *.+ *\\")|(\\' *.+ *\\')))* *((\/)|(>([ \n]|.)*<\/[a-zA-Z]+)))|(!--([ \n]|.)*--))>)*)[\n ]*$)/gy
                    .test(selector)) {
                    collection = Array.from((new DOMParser())
                        .parseFromString(selector, "text/html").body
                        .childNodes);
                } else {
                    if (Iterator.isIterable(context)) {
                        Array.from(context).forEach(function (node) {
                            collection = collection.concat(Array
                                .from(node.querySelectorAll(selector)))
                                .flatten();
                        });
                    } else {
                        // test if is a css element selector
                        if (/( *(((([a-zA-Z]+)|([.#](\w|\w+-+\w*)+)|(:(\w+(-\w+)+)(\([a-zA-Z0-9]+\))?)|(:{2}(\w+(-\w+)+))|(\*))(\[ *\w+ *(([\^$|~*]?= *)?((\w|\w+-+\w*)+|((\\') *.+ *(\\'))|((\\") *.+ *(\\"))|((') *.+ *('))|((") *.+ *("))))?( *\]))*)|(\[ *\w+ *(([\^$|~*]?= *)?((\w|\w+-+\w*)+|((\\') *.+ *(\\'))|((\\") *.+ *(\\"))|((') *.+ *('))|((") *.+ *("))))?( *\]))+)((([a-zA-Z]+)|([.#](\w|\w+-+\w*)+)|(:(\w+(-\w+)+)(\([a-zA-Z0-9]+\))?)|(:{2}(\w+(-\w+)+))|(\*))*(( +|( *[,~>+] *))(((([a-zA-Z]+)|([.#](\w|\w+-+\w*)+)|(:(\w+(-\w+)+)(\([a-zA-Z0-9]+\))?)|(:{2}(\w+(-\w+)+))|(\*))(\[ *\w+ *(([\^$|~*]?= *)?((\w|\w+-+\w*)+|((\\') *.+ *(\\'))|((\\") *.+ *(\\"))|(' *.+ *')|((") *.+ *("))))?( *\]))*)|(\[ *\w+ *(([\^$|~*]?= *)?((\w|\w+-+\w*)+|((\\') *.+ *(\\'))|((\\") *.+ *(\\"))|((') *.+ *('))|((") *.+ *("))))?( *\]))+))*)* *(?!.))/gy
                            .test(selector)) {
                            collection = Array
                                .from(context.querySelectorAll(selector));
                        } else {
                            collection = [document.createTextNode(selector)];
                        }
                    }
                }
            } else if (selector instanceof Node) {
                collection = [selector];
            } else if (selector instanceof Object) {
                collection = Array.from(selector);

                if (selector.constructor !== HTMLCollection) {
                    mainReference[0] = selector;

                    if (selector == window) {
                        collection = [];
                    }
                }
            }

            if (collection.length) {
                Object.assign(mainReference, collection);
            }
        }

        Object.defineProperties(mainReference, {
            splice: {
                value: Array.prototype.splice
            }
        });
        Iterator.toIterable(mainReference);

        return mainReference;
    };
}());

(function ($module) {

    Extensor.new($module, {
        extend: function () {
            Extensor.new(this, arguments[0]);
        }
    });

})(esPhinx);

(function ($) {

    $.extend({

        // each: function (enumerable, callback, recursive = false) {
        each: function (enumerable, callback, recursive) {
            if (typeof recursive !== "boolean") { recursive = false; }

            Iterator.each(enumerable, recursive, function (v, i) {
                callback.call(enumerable, v, i);
            });

            return this;
        }

    });

}(esPhinx));
<commit_msg>refactor the css selector pattern<commit_after>// require ./extensor

var
    esPhinx,
    Extensor,
    Iterator;

// IIFE
esPhinx = (function () {
    "use strict";

    return function esPhinx (selector, context) {

        var
            $ = esPhinx,
            mainReference = this,
            collection = [];

        if (!(mainReference instanceof $)) {
            return new $(selector, context);
        }

        if (!context || context.constructor === Text) {
            context = document;
        } else {
            if (typeof context === "string") {
                context = esPhinx(context);
            } else if (!(context instanceof $)) {
                if (!(context instanceof Node)) {
                    throw new Error("An invalid or illegal context was specified.");
                }
            }
        }

        if (selector) {
            // recognize tagName
            // ([^<][^ >]+)
            // to get attributes?
            // selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
            // get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
            if (selector instanceof $) {
                return selector;
            } else if (typeof selector === "function") {
                return document
                    .addEventListener("DOMContentLoaded", function (e) {
                    selector.call($, e);
                });
            } else if (typeof selector === "string") {
                // recognize a Element
                if (/([\n ]*((<((([a-zA-Z]+)( +(\w|\w+-+\w*)+ *= *(( *(\w|\w+-+\w*)+ *)|((") *.+ *("))|((') *.+ *('))|(\\" *.+ *\\")|(\\' *.+ *\\')))* *((\/)|(>([ \n]|.)*<\/[a-zA-Z]+)))|(!--([ \n]|.)*--))>)([\n ]*<((([a-zA-Z]+)( +(\w|\w+-+\w*)+ *= *(( *(\w|\w+-+\w*)+ *)|((") *.+ *("))|((') *.+ *('))|(\\" *.+ *\\")|(\\' *.+ *\\')))* *((\/)|(>([ \n]|.)*<\/[a-zA-Z]+)))|(!--([ \n]|.)*--))>)*)[\n ]*$)/gy
                    .test(selector)) {
                    collection = Array.from((new DOMParser())
                        .parseFromString(selector, "text/html").body
                        .childNodes);
                } else {
                    if (Iterator.isIterable(context)) {
                        Array.from(context).forEach(function (node) {
                            collection = collection.concat(Array
                                .from(node.querySelectorAll(selector)))
                                .flatten();
                        });
                    } else {
                        // test if is a css element selector
                        if (/( *((?:[a-zA-Z]+)|(?:[.#]\w+(?:-+\w*)*)+|(?::\w+(?:-\w+)*(?:\([a-zA-Z0-9]+\))?)+|(?::{2}\w+(?:-\w+)*)+|(?:\*)|(?:\w*\[ *\w+(?:-+\w*)* *(?:(?:[\^$|~*]?= *)?(?:(?:\w+(?:-+\w*)*)|(?:\\' *.+ *\\')|(?:\\" *.+ *\\")|(?:' *.+ *')|(?:" *.+ *")))?(?: *\]))+)(?:(?: *(?:[,~>+] *)?(?:(?:[.#]\w+(?:-+\w*)*)+|(?::\w+(?:-\w+)*(?:\([a-zA-Z0-9]+\))?)+|(?::{2}\w+(?:-\w+)*)+|(?:\w*\[ *\w+(?:-+\w*)* *(?:(?:[\^$|~*]?= *)?(?:(?:\w+(?:-+\w*)*)|(?:\\' *.+ *\\')|(?:\\" *.+ *\\")|(?:' *.+ *')|(?:" *.+ *")))?(?: *\]))+)*)|(?:(?:(?: *[,~>+] *)| +)(?:(?:[a-zA-Z]+)|\*))+)* *(?!.))/gy
                            .test(selector)) {
                            collection = Array
                                .from(context.querySelectorAll(selector));
                        } else {
                            collection = [document.createTextNode(selector)];
                        }
                    }
                }
            } else if (selector instanceof Node) {
                collection = [selector];
            } else if (selector instanceof Object) {
                collection = Array.from(selector);

                if (selector.constructor !== HTMLCollection) {
                    mainReference[0] = selector;

                    if (selector == window) {
                        collection = [];
                    }
                }
            }

            if (collection.length) {
                Object.assign(mainReference, collection);
            }
        }

        Object.defineProperties(mainReference, {
            splice: {
                value: Array.prototype.splice
            }
        });
        Iterator.toIterable(mainReference);

        return mainReference;
    };
}());

(function ($module) {

    Extensor.new($module, {
        extend: function () {
            Extensor.new(this, arguments[0]);
        }
    });

})(esPhinx);

(function ($) {

    $.extend({

        // each: function (enumerable, callback, recursive = false) {
        each: function (enumerable, callback, recursive) {
            if (typeof recursive !== "boolean") { recursive = false; }

            Iterator.each(enumerable, recursive, function (v, i) {
                callback.call(enumerable, v, i);
            });

            return this;
        }

    });

}(esPhinx));
<|endoftext|>


<commit_before>// require ./extensor

var
    esPhinx,
    Extensor,
    Iterator;

// IIFE
esPhinx = (function () {
    "use strict";

    return function esPhinx (selector, context) {

        var
            $ = esPhinx,
            mainReference = this,
            collection = [],

            removeBreakLine = function (text) {
                return text.replace(/(?!>)\n+/g, "");
            };

        if (!(mainReference instanceof $)) {
            return new $(selector, context);
        }

        if (!context || context.constructor === Text) {
            context = document;
        } else {
            if (typeof context === "string") {
                context = esPhinx(context);
            } else if (!(context instanceof $)) {
                if (!(context instanceof Node)) {
                    throw new Error("An invalid or illegal context was specified.");
                }
            }
        }

        if (selector) {
            // recognize tagName
            // ([^<][^ >]+)
            // attributes
            // selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
            // get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
            if (selector instanceof $) {
                return selector;
            } else if (typeof selector === "function") {
                return document
                    .addEventListener("DOMContentLoaded", function (e) {
                    selector.call($, e);
                });
            } else if (typeof selector === "string") {
                // recognize a tag
                if (/ *<{1}[a-zA-Z]+( +(\w+|\w+-+\w+)+ *={1} *((\\"{1} *\w+ *(\w+|#)+ *\\"{1})|(\\'{1} *\w+( *\w+|#) *\\'{1})|(\w+|#)))* *((\/){1}|(>{1}.*<{1}\/[a-zA-Z]+){1})(>{1} *$)/gy.test(selector)) {
                    collection = Array.from((new DOMParser())
                        .parseFromString(removeBreakLine(selector), "text/html")
                        .body.childNodes);
                } else {
                    if (Iterator.isIterable(context)) {
                        Array.from(context).forEach(function (node) {
                            collection = collection.concat(Array
                                .from(node.querySelectorAll(selector)))
                                .flatten();
                        });
                    } else {
                        if (//gy.test(selector)) {
                            collection = Array
                                .from(context.querySelectorAll(selector));
                        }

                        if (!collection.length) {
                            collection = [document.createTextNode(selector)];
                        }
                    }
                }
            } else if (selector instanceof Node) {
                collection = [selector];
            } else if (selector instanceof Object) {
                collection = Array.from(selector);

                if (selector.constructor !== HTMLCollection) {
                    mainReference[0] = selector;

                    if (selector == window) {
                        collection = [];
                    }
                }
            }

            if (collection.length) {
                Object.assign(mainReference, collection);
            }
        }

        Object.defineProperties(mainReference, {
            splice: {
                value: Array.prototype.splice
            }
        });
        Iterator.toIterable(mainReference);

        return mainReference;
    };
}());

(function ($module) {

    Extensor.new($module, {
        extend: function () {
            Extensor.new(this, arguments[0]);
        }
    });

})(esPhinx);

(function ($) {

    $.extend({

        // each: function (enumerable, callback, recursive = false) {
        each: function (enumerable, callback, recursive) {
            if (typeof recursive !== "boolean") { recursive = false; }

            Iterator.each(enumerable, recursive, function (v, i) {
                callback.call(enumerable, v, i);
            });

            return this;
        }

    });

}(esPhinx));

// caso necessite usar
// (?![#\^\[\]+ ~>,|*:.\\’()$-])\W

// flags gy

//=> .text, .text.text, text.text, text.text text, #text, :text, ::text
// siblings, childrens and multiple heritage.
// está aceitando mais de um atributo, isso é correto?
// ( *((((([.#]{1}|\:{1,2})?\w+)|\*{1})(\[{1} *\w+ *(([\^$|~*]?={1} *)?(\w+|#|((\\'){1}(\w+|#)(\\'){1})|((\\"){1}(\w+|#)(\\"){1})|('{1}(\w+|#)'{1})))?( *\]{1}))*)|(\[{1} *\w+(([\^$|~*]?={1} *)?(\w+|#|((\\'){1}(\w+|#)(\\'){1})|((\\"){1}(\w+|#)(\\"){1})|('{1}(\w+|#)'{1})))?(\]{1}))+)((([.#]{1}|\:{1,2})\w+)*(( +|( *[,~>+]{1} *))((((([.#]{1}|\:{1,2})?\w+)|\*{1})(\[{1}\w+(([\^$|~*]?={1} *)?(\w+|#|((\\'){1}(\w+|#)(\\'){1})|((\\"){1}(\w+|#)(\\"){1})|('{1}(\w+|#)'{1})))?(\]{1}))*)|(\[{1}\w+(([\^$|~*]?={1} *)?(\w+|#|((\\'){1}(\w+|#)(\\'){1})|((\\"){1}(\w+|#)(\\"){1})|('{1}(\w+|#)'{1})))?(\]{1}))+))*)* *(?!.))

// (\[{1}\w+(([\^$|~*]?={1})?(\w+|((\\'){1}(\w+|#)(\\'){1})|((\\"){1}(\w+|#)(\\"){1})|('{1}(\w+|#)'{1})))?(\]{1}))+<commit_msg>add support to # as value<commit_after>// require ./extensor

var
    esPhinx,
    Extensor,
    Iterator;

// IIFE
esPhinx = (function () {
    "use strict";

    return function esPhinx (selector, context) {

        var
            $ = esPhinx,
            mainReference = this,
            collection = [],

            removeBreakLine = function (text) {
                return text.replace(/(?!>)\n+/g, "");
            };

        if (!(mainReference instanceof $)) {
            return new $(selector, context);
        }

        if (!context || context.constructor === Text) {
            context = document;
        } else {
            if (typeof context === "string") {
                context = esPhinx(context);
            } else if (!(context instanceof $)) {
                if (!(context instanceof Node)) {
                    throw new Error("An invalid or illegal context was specified.");
                }
            }
        }

        if (selector) {
            // recognize tagName
            // ([^<][^ >]+)
            // attributes
            // selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
            // get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
            if (selector instanceof $) {
                return selector;
            } else if (typeof selector === "function") {
                return document
                    .addEventListener("DOMContentLoaded", function (e) {
                    selector.call($, e);
                });
            } else if (typeof selector === "string") {
                // recognize a tag
                if (/ *<{1}[a-zA-Z]+( +(\w+|\w+-+\w+)+ *={1} *((\\"{1} *\w+ * *(\w+|#) *+ *\\"{1})|(\\'{1} *\w+( *\w+|#) *\\'{1})| *(\w+|#) *))* *((\/){1}|(>{1}.*<{1}\/[a-zA-Z]+){1})(>{1} *$)/gy.test(selector)) {
                    collection = Array.from((new DOMParser())
                        .parseFromString(removeBreakLine(selector), "text/html")
                        .body.childNodes);
                } else {
                    if (Iterator.isIterable(context)) {
                        Array.from(context).forEach(function (node) {
                            collection = collection.concat(Array
                                .from(node.querySelectorAll(selector)))
                                .flatten();
                        });
                    } else {
                        if (//gy.test(selector)) {
                            collection = Array
                                .from(context.querySelectorAll(selector));
                        }

                        if (!collection.length) {
                            collection = [document.createTextNode(selector)];
                        }
                    }
                }
            } else if (selector instanceof Node) {
                collection = [selector];
            } else if (selector instanceof Object) {
                collection = Array.from(selector);

                if (selector.constructor !== HTMLCollection) {
                    mainReference[0] = selector;

                    if (selector == window) {
                        collection = [];
                    }
                }
            }

            if (collection.length) {
                Object.assign(mainReference, collection);
            }
        }

        Object.defineProperties(mainReference, {
            splice: {
                value: Array.prototype.splice
            }
        });
        Iterator.toIterable(mainReference);

        return mainReference;
    };
}());

(function ($module) {

    Extensor.new($module, {
        extend: function () {
            Extensor.new(this, arguments[0]);
        }
    });

})(esPhinx);

(function ($) {

    $.extend({

        // each: function (enumerable, callback, recursive = false) {
        each: function (enumerable, callback, recursive) {
            if (typeof recursive !== "boolean") { recursive = false; }

            Iterator.each(enumerable, recursive, function (v, i) {
                callback.call(enumerable, v, i);
            });

            return this;
        }

    });

}(esPhinx));

// caso necessite usar
// (?![#\^\[\]+ ~>,|*:.\\’()$-])\W

// flags gy

//=> .text, .text.text, text.text, text.text text, #text, :text, ::text
// siblings, childrens and multiple heritage.
// só falta suporte a aspas duplas depois do =
// ( *((((([.#]{1}|\:{1,2})?\w+)|\*{1})(\[{1} *\w+ *(([\^$|~*]?={1} *)?(\w+|#|((\\'){1} *(\w+|#) *(\\'){1})|((\\"){1} *(\w+|#) *(\\"){1})|(('{1}) *(\w+|#) *('{1}))))?( *\]{1}))*)|(\[{1} *\w+ *(([\^$|~*]?={1} *)?(\w+|#|((\\'){1} *(\w+|#) *(\\'){1})|((\\"){1} *(\w+|#) *(\\"){1})|(('{1}) *(\w+|#) *('{1}))))?( *\]{1}))+)((([.#]{1}|\:{1,2})\w+)*(( +|( *[,~>+]{1} *))((((([.#]{1}|\:{1,2})?\w+)|\*{1})(\[{1} *\w+ *(([\^$|~*]?={1} *)?(\w+|#|((\\'){1} *(\w+|#) *(\\'){1})|((\\"){1} *(\w+|#) *(\\"){1})|('{1} *(\w+|#) *'{1})))?( *\]{1}))*)|(\[{1} *\w+ *(([\^$|~*]?={1} *)?(\w+|#|((\\'){1} *(\w+|#) *(\\'){1})|((\\"){1} *(\w+|#) *(\\"){1})|(('{1}) *(\w+|#) *('{1}))))?( *\]{1}))+))*)* *(?!.))

// (\[{1}\w+(([\^$|~*]?={1})?(\w+|((\\'){1} *(\w+|#) *(\\'){1})|((\\"){1} *(\w+|#) *(\\"){1})|('{1} *(\w+|#) *'{1})))?(\]{1}))+<|endoftext|>


<commit_before>'use babel';

export const apmEq    = amount => current => current.apm   >   amount

export const scoreEq  = amount => current => current.score === amount

export const keyCombo = combo  => current => {
  const keys = current.commands.slice(0, combo.length).reverse().join('')
  return keys === combo.join('')
}

export const cumulativeGroupCount = (rate, group) => current => {
  const triggered = group.includes(current.latest.command)
  const count     = current.counts[current.latest.command]
  return triggered && count === rate
}

export const cumulativeGroupRate = (rate, group) => current => {
  const triggered = group.includes(current.latest.command)
  const count     = current.counts[current.latest.command]
  return triggered && (count % rate) === 0
}
<commit_msg>minor name change<commit_after>'use babel';

export const apmEq    = amount => current => current.apm   >   amount

export const scoreEq  = amount => current => current.score === amount

export const keyCombo = combo  => current => {
  const keys = current.commands.slice(0, combo.length).reverse().join('')
  return keys === combo.join('')
}

export const cumulativeGroupCount = (amount, group) => current => {
  const triggered = group.includes(current.latest.command)
  const count     = current.counts[current.latest.command]
  return triggered && count === amount
}

export const cumulativeGroupRate = (rate, group) => current => {
  const triggered = group.includes(current.latest.command)
  const count     = current.counts[current.latest.command]
  return triggered && (count % rate) === 0
}
<|endoftext|>


<commit_before>mini.Module(
	"basic/interactionhandlerbuilder"
)
.requires(
	"basic/interactionhandler",
	"basic/utils",
	"basic/shapebuilder"
)
.defines(function(InteractionHandler, Utils, ShapeBuilder) {
	var Builder = {
		buildDragBodyInWorld: function(layer, world) {
			return new InteractionHandler()
			.name("DRAG_BODY")
			.context({
				body: {},
				pmId: -1
			})
			.onPressed(function() {
				env.camera.pushLayer(layer);
				// create force callback
				this.drag = Utils.Function.bind(function drag(body) {
					var mousePositionInWorldCoordinates = env.camera.screenToWorldCoordinates(env.input.mouse);
					var pointMass = body.pointMasses[this.pmId];
					var diff = Jello.VectorTools.calculateSpringForceVelAVelB(
						pointMass.Position,
						pointMass.Velocity,
						mousePositionInWorldCoordinates,
						Jello.Vector2.Zero.copy(), // velB,
						0.0, // springD,
						100.0, // springK,
						10.0 // damping
					);
					pointMass.Force.addSelf(diff);
				}, this);

				var answer = world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
				this.body = world.getBody(answer.bodyId);
				this.body.addExternalForce(this.drag);
				this.pmId = answer.pointMassId;
				env.camera.popLayer();
			})
			.onReleased(function() {
				if(typeof this.body.removeExternalForce == "function")
					this.body.removeExternalForce(this.drag);
			});
		},
		buildSpawnCubeInWorld: function(layer, world) {
			return new InteractionHandler()
			.name("SPAWN_CUBE")
			.onPressed(function() {
				env.camera.pushLayer(layer);
				Jello.BodyFactory.createBluePrint(Jello.SpringBody)
					.world(world)
					.shape(ShapeBuilder.Shapes.Cube)
					.pointMasses(1)
					.translate(env.camera.screenToWorldCoordinates(env.input.mouse))
					.rotate(0)
					.scale(Jello.Vector2.One.copy())
					.isKinematic(false)
					.edgeSpringK(300.0)
					.edgeSpringDamp(5.0)
					.shapeSpringK(150.0)
					.shapeSpringDamp(5.0)
					.addInternalSpring(0, 2, 300, 10)
					.addInternalSpring(1, 3, 300, 10)
					.build();
				env.camera.popLayer();
			});
		},
		buildSelectBodyInWorld: function(layer, world) {
			return new InteractionHandler()
			.name("SELECT_BODY")
			.onPressed(function() {
				env.camera.pushLayer(layer);
				var answer = world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
				env.camera.popLayer();
				var body = world.getBody(answer.bodyId);
				console.log(body.aName);
			});
		}
	};

	return Builder;
});
<commit_msg>removed InteractionHandlerBuilder<commit_after><|endoftext|>


<commit_before>'use strict';

var dataURLToBlob = function(base64) {
  // 兼容 dataURL
  if (base64.split(',')[0] && base64.split(',')[0].indexOf('base64') >= 0) {
    base64 = base64.split(',')[1];
  }
  return new Buffer(base64, 'base64').toString('utf8');
};

module.exports = dataURLToBlob;
<commit_msg>[bugfix] upload base64 do not need to encode UTF8.<commit_after>'use strict';

var dataURLToBlob = function(base64) {
  // 兼容 dataURL
  if (base64.split(',')[0] && base64.split(',')[0].indexOf('base64') >= 0) {
    base64 = base64.split(',')[1];
  }
  return new Buffer(base64, 'base64');
};

module.exports = dataURLToBlob;
<|endoftext|>


<commit_before>'use strict';

const log = require('intel').getLogger('browsertime.chrome');
const { promisify } = require('util');
const { Type } = require('selenium-webdriver').logging;
const get = require('lodash.get');
const harBuilder = require('../../support/har/');
const perflogParser = require('chrome-har');
const fs = require('fs');
const { parseCpuTrace } = require('../cpu');
const webdriver = require('selenium-webdriver');
const util = require('../../support/util');
const zlib = require('zlib');
const traceCategoriesParser = require('../traceCategoriesParser');
const pathToFolder = require('../../support/pathToFolder');
const path = require('path');
const CDP = require('chrome-remote-interface');

const unlink = promisify(fs.unlink);

const { createAndroidConnection } = require('../../android');

const CHROME_NAME_AND_VERSION_JS = `return (function() {
  var match = navigator.userAgent.match(/(Chrom(e|ium))\\/(([0-9]+\\.?)*)/);

  if (match)
    return {
      'name': match[1],
      'version': match[3]
    };
  else
    return {};
})();`;

class ChromeDelegate {
  constructor(storageManager, options) {
    this.options = options;
    this.chrome = options.chrome || {};
    this.skipHar = options.skipHar || false;
    this.logPerfEntries = !!this.chrome.collectPerfLog;
    this.collectTracingEvents =
      this.chrome.traceCategories || this.chrome.timeline;
    this.baseDir = storageManager.directory;
    this.storageManager = storageManager;
    // We keep track of all alias and URLs
    this.aliasAndUrl = {};
    this.isTracing = false;

    this.chromeTraceCategories = this.chrome.traceCategories
      ? this.chrome.traceCategories.split(',')
      : [
          '-*',
          'disabled-by-default-lighthouse',
          'v8',
          'v8.execute',
          'blink.user_timing',
          'devtools.timeline',
          'disabled-by-default-devtools.timeline',
          'disabled-by-default-devtools.timeline.stack'
        ];
    if (this.chrome.enableTraceScreenshots) {
      this.chromeTraceCategories.push(
        'disabled-by-default-devtools.screenshot'
      );
    }

    if (this.chrome.traceCategories) {
      log.info('Use Chrome trace categories: %s', this.chrome.traceCategories);
    }
  }

  async _startTrace() {
    this.events = [];
    this.cdpClient.Tracing.dataCollected(({ value }) => {
      this.events.push(...value);
    });

    this.isTracing = true;
    return this.cdpClient.Tracing.start({
      traceConfig: {
        recordMode: 'recordAsMuchAsPossible',
        includedCategories: this.chromeTraceCategories
      }
    });
  }
  async onStart() {
    this.hars = [];
    this.events = [];
    if (this.chrome.android) {
      this.android = createAndroidConnection(this.options);
      return this.android.initConnection();
    }
  }

  async afterBrowserStart() {
    // We create the cdp as early as possibble so it can be used in scripts
    // https://bugs.chromium.org/p/chromium/issues/detail?id=824626
    // https://github.com/cyrus-and/chrome-remote-interface/issues/332
    if (this.chrome.android) {
      this.cdpClient = await CDP({
        local: true,
        port: this.options.devToolsPort
      });
    } else {
      this.cdpClient = await CDP({});
    }

    return this.cdpClient.Page.enable();
  }

  async onStartIteration(runner) {
    // enable getting extra performance metrics
    if (this.chrome.cdp && this.chrome.cdp.performance === true) {
      await this.cdpClient.Performance.enable();
    }

    if (this.options.injectJs) {
      await this.cdpClient.Page.addScriptToEvaluateOnNewDocument({
        source: this.options.injectJs
      });
    }

    if (this.options.requestheader) {
      const headersArray = util.toArray(this.options.requestheader);
      const headers = {};
      for (let header of headersArray) {
        const parts = header.split(':');
        headers[parts[0]] = parts[1];
      }
      await this.cdpClient.Network.enable();
      await this.cdpClient.Network.setExtraHTTPHeaders({
        headers
      });
    }

    if (this.chrome.collectLongTasks) {
      const source = `
      !function() {
        let lt = window.__bt_longtask={e:[]};
        lt.o = new PerformanceObserver(function(a) {
          lt.e=lt.e.concat(a.getEntries());
        });
        lt.o.observe({entryTypes:['longtask']});
      }();`;

      await this.cdpClient.Page.addScriptToEvaluateOnNewDocument({ source });
    }

    if (this.chrome.CPUThrottlingRate && this.chrome.CPUThrottlingRate > 1) {
      log.info('Using CPUThrottlingRate: %s', this.chrome.CPUThrottlingRate);
      await this.cdpClient.Emulation.setCPUThrottlingRate({
        rate: this.chrome.CPUThrottlingRate
      });
    }

    // Make sure we clear the console log
    // Hopefully one time is enough?
    await runner.getLogs(Type.BROWSER);

    // remove irrelevant entries from performance log
    // and since Chromedriver 2.29 there's a bug
    // https://bugs.chromium.org/p/chromedriver/issues/detail?id=1811
    // that can be fixed by emptying the logs twice :|
    await runner.getLogs(Type.PERFORMANCE);
    await runner.getLogs(Type.PERFORMANCE);

    if (this.skipHar) {
      return;
    }
  }

  async clear(runner) {
    await runner.getLogs(Type.PERFORMANCE);
    await runner.getLogs(Type.PERFORMANCE);
  }

  async onStopIteration() {
    if (this.chrome.collectNetLog && !this.chrome.android) {
      const netlog = `${this.baseDir}/chromeNetlog.json`;
      return unlink(netlog);
    }
  }

  async beforeEachURL() {
    if (this.collectTracingEvents && !this.isTracing) {
      return this._startTrace();
    }
  }

  async beforeCollect() {
    if (this.collectTracingEvents) {
      // We are ready and can stop collecting events
      await this.cdpClient.Tracing.end();
      this.isTracing = false;
      return this.cdpClient.Tracing.tracingComplete();
    }
  }

  async onCollect(runner, index, result) {
    if (this.chrome.collectNetLog && !this.chrome.android) {
      await this.storageManager.createSubDataDir(
        path.join(pathToFolder(result.url, this.options))
      );

      const gzip = zlib.createGzip();
      const netlog = `${this.baseDir}/chromeNetlog.json`;
      const input = fs.createReadStream(netlog);
      const out = fs.createWriteStream(
        path.join(
          this.baseDir,
          pathToFolder(result.url, this.options),
          `chromeNetlog-${index}.json.gz`
        )
      );
      out.on('finish', function() {
        // return unlink(netlog);
      });
      out.on('error', function(e) {
        log.error('Could not gzip the Chrome net log', e);
      });
      input.pipe(gzip).pipe(out);
    }

    if (this.chrome.collectConsoleLog) {
      result.extraJson[`console-${index}.json`] = await runner.getLogs(
        webdriver.logging.Type.BROWSER
      );
    }

    const rawCDPMetrics = await this.cdpClient.Performance.getMetrics();

    const cleanedMetrics = {};
    for (let m of rawCDPMetrics.metrics) {
      if (
        m.name === 'FirstMeaningfulPaint' ||
        m.name === 'DomContentLoaded' ||
        m.name === 'Timestamp' ||
        m.name === 'NavigationStart'
      ) {
        // skip
      } else {
        if (m.name.indexOf('Duration') > -1) {
          cleanedMetrics[m.name] = m.value * 1000;
        } else {
          cleanedMetrics[m.name] = m.value;
        }
      }
    }

    result.cdp = { performance: cleanedMetrics };

    if (this.chrome.collectNetLog && this.chrome.android) {
      // THIS needs to be unique per page
      await this.android.pullNetLog(
        path.join(
          this.baseDir,
          pathToFolder(result.url, this.options),
          `chromeNetlog-${index}.json.gz`
        )
      );
    }

    if (this.skipHar) {
      return;
    }

    log.debug('Getting performance logs from Chrome');

    const logs = await runner.getLogs(Type.PERFORMANCE);
    const messages = logs.map(entry => JSON.parse(entry.message).message);

    if (this.logPerfEntries) {
      result.extraJson[`chromePerflog-${index}.json`] = messages;
    }
    if (this.collectTracingEvents) {
      const trace = traceCategoriesParser.parse(this.events, result.url);
      result.extraJson[`trace-${index}.json`] = trace;
      const cpu = await parseCpuTrace(trace, result.url);
      result.cpu = cpu;
    }

    // lets take the time and format the CPU long tasks
    if (
      result.browserScripts.pageinfo &&
      result.browserScripts.pageinfo.longTask
    ) {
      let totalDurationFirstPaint = 0;
      let totalDurationFirstContentFulPaint = 0;
      let totalDurationAfterLoadEventEnd = 0;
      let totalDuration = 0;
      const firstPaint = get(
        result,
        'browserScripts.timings.paintTiming.first-paint'
      );
      const firstContentfulPaint = get(
        result,
        'browserScripts.timings.paintTiming.first-contentful-paint'
      );

      const loadEventEnd = get(result, 'browserScripts.timings.loadEventEnd');

      let longTasksBeforeFirstPaint = 0;
      let longTasksBeforeFirstContentfulPaint = 0;
      let longTasksAfterLoadEventEnd = 0;

      for (let longTask of result.browserScripts.pageinfo.longTask) {
        totalDuration += longTask.duration;
        if (firstPaint && longTask.startTime < firstPaint) {
          longTasksBeforeFirstPaint++;
          totalDurationFirstPaint += longTask.duration;
        }
        if (firstContentfulPaint && longTask.startTime < firstContentfulPaint) {
          longTasksBeforeFirstContentfulPaint++;
          totalDurationFirstContentFulPaint += longTask.duration;
        }
        if (loadEventEnd && longTask.startTime > loadEventEnd) {
          longTasksAfterLoadEventEnd++;
          totalDurationAfterLoadEventEnd += longTask.duration;
        }
      }
      const cpu = {
        longTasks: {
          tasks: result.browserScripts.pageinfo.longTask.length,
          totalDuration,
          beforeFirstPaint: {
            tasks: longTasksBeforeFirstPaint,
            totalDuration: totalDurationFirstPaint
          },
          beforeFirstContentfulPaint: {
            tasks: longTasksBeforeFirstContentfulPaint,
            totalDuration: totalDurationFirstContentFulPaint
          },
          afterLoadEventEnd: {
            tasks: longTasksAfterLoadEventEnd,
            totalDuration: totalDurationAfterLoadEventEnd
          }
        }
      };

      if (result.cpu) {
        result.cpu.longTasks = cpu.longTasks;
      } else {
        result.cpu = cpu;
      }
    }

    // CLEANUP since Chromedriver 2.29 there's a bug
    // https://bugs.chromium.org/p/chromedriver/issues/detail?id=1811
    await runner.getLogs(Type.PERFORMANCE);

    const har = perflogParser.harFromMessages(messages);

    if (this.chrome.includeResponseBodies === 'html') {
      const resourceTree = await this.cdpClient.Page.getResourceTree();
      const url = resourceTree.frameTree.frame.url;
      try {
        const html = await this.cdpClient.Page.getResourceContent({
          frameId: resourceTree.frameTree.frame.id,
          url: resourceTree.frameTree.frame.url
        });

        for (let entry of har.log.entries) {
          if (entry.request.url === url) {
            entry.response.content.text = html.content;
          }
        }
      } catch (e) {
        log.error('Could not find a matching resource to get the HTML', e);
      }
    }

    const info = await runner.runScript(
      CHROME_NAME_AND_VERSION_JS,
      'CHROME_NAME_AND_VERSION_JS'
    );
    if (this.chrome.mobileEmulation) {
      info.name = `Chrome Emulated ${this.chrome.mobileEmulation.deviceName}`;
    }
    harBuilder.addBrowser(har, info.name, info.version);

    if (har.log.pages.length > 0) {
      har.log.pages[0].title = `${result.url} run ${index}`;
      // Hack to add the URL from a SPA
      if (result.alias && !this.aliasAndUrl[result.alias]) {
        this.aliasAndUrl[result.alias] = result.url;
        har.log.pages[0]._url = result.url;
      } else if (result.alias && this.aliasAndUrl[result.alias]) {
        har.log.pages[0]._url = this.aliasAndUrl[result.alias];
      } else {
        har.log.pages[0]._url = result.url;
      }
    }

    this.hars.push(har);
  }

  async sendAndGetDevToolsCommand(cmd, params = {}) {
    return this.cdpClient.send(cmd, params);
  }
  async sendDevToolsCommand(cmd, params = {}) {
    return this.cdpClient.send(cmd, params);
  }

  failing(url) {
    if (this.skipHar) {
      return;
    }
    this.hars.push(harBuilder.getEmptyHAR(url, 'Chrome'));
  }

  async onStop() {
    if (this.cdpClient) {
      await this.cdpClient.close();
    }
    if (this.chrome.android) {
      await this.android.removeFw();
    }
    if (!this.skipHar) {
      return { har: harBuilder.mergeHars(this.hars) };
    } else return {};
  }
}

module.exports = ChromeDelegate;
<commit_msg>Smarter check that request headers are set ok (#875)<commit_after>'use strict';

const log = require('intel').getLogger('browsertime.chrome');
const { promisify } = require('util');
const { Type } = require('selenium-webdriver').logging;
const get = require('lodash.get');
const harBuilder = require('../../support/har/');
const perflogParser = require('chrome-har');
const fs = require('fs');
const { parseCpuTrace } = require('../cpu');
const webdriver = require('selenium-webdriver');
const util = require('../../support/util');
const zlib = require('zlib');
const traceCategoriesParser = require('../traceCategoriesParser');
const pathToFolder = require('../../support/pathToFolder');
const path = require('path');
const CDP = require('chrome-remote-interface');

const unlink = promisify(fs.unlink);

const { createAndroidConnection } = require('../../android');

const CHROME_NAME_AND_VERSION_JS = `return (function() {
  var match = navigator.userAgent.match(/(Chrom(e|ium))\\/(([0-9]+\\.?)*)/);

  if (match)
    return {
      'name': match[1],
      'version': match[3]
    };
  else
    return {};
})();`;

class ChromeDelegate {
  constructor(storageManager, options) {
    this.options = options;
    this.chrome = options.chrome || {};
    this.skipHar = options.skipHar || false;
    this.logPerfEntries = !!this.chrome.collectPerfLog;
    this.collectTracingEvents =
      this.chrome.traceCategories || this.chrome.timeline;
    this.baseDir = storageManager.directory;
    this.storageManager = storageManager;
    // We keep track of all alias and URLs
    this.aliasAndUrl = {};
    this.isTracing = false;

    this.chromeTraceCategories = this.chrome.traceCategories
      ? this.chrome.traceCategories.split(',')
      : [
          '-*',
          'disabled-by-default-lighthouse',
          'v8',
          'v8.execute',
          'blink.user_timing',
          'devtools.timeline',
          'disabled-by-default-devtools.timeline',
          'disabled-by-default-devtools.timeline.stack'
        ];
    if (this.chrome.enableTraceScreenshots) {
      this.chromeTraceCategories.push(
        'disabled-by-default-devtools.screenshot'
      );
    }

    if (this.chrome.traceCategories) {
      log.info('Use Chrome trace categories: %s', this.chrome.traceCategories);
    }
  }

  async _startTrace() {
    this.events = [];
    this.cdpClient.Tracing.dataCollected(({ value }) => {
      this.events.push(...value);
    });

    this.isTracing = true;
    return this.cdpClient.Tracing.start({
      traceConfig: {
        recordMode: 'recordAsMuchAsPossible',
        includedCategories: this.chromeTraceCategories
      }
    });
  }
  async onStart() {
    this.hars = [];
    this.events = [];
    if (this.chrome.android) {
      this.android = createAndroidConnection(this.options);
      return this.android.initConnection();
    }
  }

  async afterBrowserStart() {
    // We create the cdp as early as possibble so it can be used in scripts
    // https://bugs.chromium.org/p/chromium/issues/detail?id=824626
    // https://github.com/cyrus-and/chrome-remote-interface/issues/332
    if (this.chrome.android) {
      this.cdpClient = await CDP({
        local: true,
        port: this.options.devToolsPort
      });
    } else {
      this.cdpClient = await CDP({});
    }

    return this.cdpClient.Page.enable();
  }

  async onStartIteration(runner) {
    // enable getting extra performance metrics
    if (this.chrome.cdp && this.chrome.cdp.performance === true) {
      await this.cdpClient.Performance.enable();
    }

    if (this.options.injectJs) {
      await this.cdpClient.Page.addScriptToEvaluateOnNewDocument({
        source: this.options.injectJs
      });
    }

    if (this.options.requestheader) {
      // Our cli don't validate parameters
      // so -run will become -r etc
      if (
        this.options.requestheader.indexOf &&
        this.options.requestheader.indexOf(':') > -1
      ) {
        const headersArray = util.toArray(this.options.requestheader);
        const headers = {};
        for (let header of headersArray) {
          const parts = header.split(':');
          headers[parts[0]] = parts[1];
        }
        await this.cdpClient.Network.enable();
        await this.cdpClient.Network.setExtraHTTPHeaders({
          headers
        });
      } else {
        log.error(
          'Request headers need to be of the format key:value not ' +
            this.options.requestheader
        );
      }
    }

    if (this.chrome.collectLongTasks) {
      const source = `
      !function() {
        let lt = window.__bt_longtask={e:[]};
        lt.o = new PerformanceObserver(function(a) {
          lt.e=lt.e.concat(a.getEntries());
        });
        lt.o.observe({entryTypes:['longtask']});
      }();`;

      await this.cdpClient.Page.addScriptToEvaluateOnNewDocument({ source });
    }

    if (this.chrome.CPUThrottlingRate && this.chrome.CPUThrottlingRate > 1) {
      log.info('Using CPUThrottlingRate: %s', this.chrome.CPUThrottlingRate);
      await this.cdpClient.Emulation.setCPUThrottlingRate({
        rate: this.chrome.CPUThrottlingRate
      });
    }

    // Make sure we clear the console log
    // Hopefully one time is enough?
    await runner.getLogs(Type.BROWSER);

    // remove irrelevant entries from performance log
    // and since Chromedriver 2.29 there's a bug
    // https://bugs.chromium.org/p/chromedriver/issues/detail?id=1811
    // that can be fixed by emptying the logs twice :|
    await runner.getLogs(Type.PERFORMANCE);
    await runner.getLogs(Type.PERFORMANCE);

    if (this.skipHar) {
      return;
    }
  }

  async clear(runner) {
    await runner.getLogs(Type.PERFORMANCE);
    await runner.getLogs(Type.PERFORMANCE);
  }

  async onStopIteration() {
    if (this.chrome.collectNetLog && !this.chrome.android) {
      const netlog = `${this.baseDir}/chromeNetlog.json`;
      return unlink(netlog);
    }
  }

  async beforeEachURL() {
    if (this.collectTracingEvents && !this.isTracing) {
      return this._startTrace();
    }
  }

  async beforeCollect() {
    if (this.collectTracingEvents) {
      // We are ready and can stop collecting events
      await this.cdpClient.Tracing.end();
      this.isTracing = false;
      return this.cdpClient.Tracing.tracingComplete();
    }
  }

  async onCollect(runner, index, result) {
    if (this.chrome.collectNetLog && !this.chrome.android) {
      await this.storageManager.createSubDataDir(
        path.join(pathToFolder(result.url, this.options))
      );

      const gzip = zlib.createGzip();
      const netlog = `${this.baseDir}/chromeNetlog.json`;
      const input = fs.createReadStream(netlog);
      const out = fs.createWriteStream(
        path.join(
          this.baseDir,
          pathToFolder(result.url, this.options),
          `chromeNetlog-${index}.json.gz`
        )
      );
      out.on('finish', function() {
        // return unlink(netlog);
      });
      out.on('error', function(e) {
        log.error('Could not gzip the Chrome net log', e);
      });
      input.pipe(gzip).pipe(out);
    }

    if (this.chrome.collectConsoleLog) {
      result.extraJson[`console-${index}.json`] = await runner.getLogs(
        webdriver.logging.Type.BROWSER
      );
    }

    const rawCDPMetrics = await this.cdpClient.Performance.getMetrics();

    const cleanedMetrics = {};
    for (let m of rawCDPMetrics.metrics) {
      if (
        m.name === 'FirstMeaningfulPaint' ||
        m.name === 'DomContentLoaded' ||
        m.name === 'Timestamp' ||
        m.name === 'NavigationStart'
      ) {
        // skip
      } else {
        if (m.name.indexOf('Duration') > -1) {
          cleanedMetrics[m.name] = m.value * 1000;
        } else {
          cleanedMetrics[m.name] = m.value;
        }
      }
    }

    result.cdp = { performance: cleanedMetrics };

    if (this.chrome.collectNetLog && this.chrome.android) {
      // THIS needs to be unique per page
      await this.android.pullNetLog(
        path.join(
          this.baseDir,
          pathToFolder(result.url, this.options),
          `chromeNetlog-${index}.json.gz`
        )
      );
    }

    if (this.skipHar) {
      return;
    }

    log.debug('Getting performance logs from Chrome');

    const logs = await runner.getLogs(Type.PERFORMANCE);
    const messages = logs.map(entry => JSON.parse(entry.message).message);

    if (this.logPerfEntries) {
      result.extraJson[`chromePerflog-${index}.json`] = messages;
    }
    if (this.collectTracingEvents) {
      const trace = traceCategoriesParser.parse(this.events, result.url);
      result.extraJson[`trace-${index}.json`] = trace;
      const cpu = await parseCpuTrace(trace, result.url);
      result.cpu = cpu;
    }

    // lets take the time and format the CPU long tasks
    if (
      result.browserScripts.pageinfo &&
      result.browserScripts.pageinfo.longTask
    ) {
      let totalDurationFirstPaint = 0;
      let totalDurationFirstContentFulPaint = 0;
      let totalDurationAfterLoadEventEnd = 0;
      let totalDuration = 0;
      const firstPaint = get(
        result,
        'browserScripts.timings.paintTiming.first-paint'
      );
      const firstContentfulPaint = get(
        result,
        'browserScripts.timings.paintTiming.first-contentful-paint'
      );

      const loadEventEnd = get(result, 'browserScripts.timings.loadEventEnd');

      let longTasksBeforeFirstPaint = 0;
      let longTasksBeforeFirstContentfulPaint = 0;
      let longTasksAfterLoadEventEnd = 0;

      for (let longTask of result.browserScripts.pageinfo.longTask) {
        totalDuration += longTask.duration;
        if (firstPaint && longTask.startTime < firstPaint) {
          longTasksBeforeFirstPaint++;
          totalDurationFirstPaint += longTask.duration;
        }
        if (firstContentfulPaint && longTask.startTime < firstContentfulPaint) {
          longTasksBeforeFirstContentfulPaint++;
          totalDurationFirstContentFulPaint += longTask.duration;
        }
        if (loadEventEnd && longTask.startTime > loadEventEnd) {
          longTasksAfterLoadEventEnd++;
          totalDurationAfterLoadEventEnd += longTask.duration;
        }
      }
      const cpu = {
        longTasks: {
          tasks: result.browserScripts.pageinfo.longTask.length,
          totalDuration,
          beforeFirstPaint: {
            tasks: longTasksBeforeFirstPaint,
            totalDuration: totalDurationFirstPaint
          },
          beforeFirstContentfulPaint: {
            tasks: longTasksBeforeFirstContentfulPaint,
            totalDuration: totalDurationFirstContentFulPaint
          },
          afterLoadEventEnd: {
            tasks: longTasksAfterLoadEventEnd,
            totalDuration: totalDurationAfterLoadEventEnd
          }
        }
      };

      if (result.cpu) {
        result.cpu.longTasks = cpu.longTasks;
      } else {
        result.cpu = cpu;
      }
    }

    // CLEANUP since Chromedriver 2.29 there's a bug
    // https://bugs.chromium.org/p/chromedriver/issues/detail?id=1811
    await runner.getLogs(Type.PERFORMANCE);

    const har = perflogParser.harFromMessages(messages);

    if (this.chrome.includeResponseBodies === 'html') {
      const resourceTree = await this.cdpClient.Page.getResourceTree();
      const url = resourceTree.frameTree.frame.url;
      try {
        const html = await this.cdpClient.Page.getResourceContent({
          frameId: resourceTree.frameTree.frame.id,
          url: resourceTree.frameTree.frame.url
        });

        for (let entry of har.log.entries) {
          if (entry.request.url === url) {
            entry.response.content.text = html.content;
          }
        }
      } catch (e) {
        log.error('Could not find a matching resource to get the HTML', e);
      }
    }

    const info = await runner.runScript(
      CHROME_NAME_AND_VERSION_JS,
      'CHROME_NAME_AND_VERSION_JS'
    );
    if (this.chrome.mobileEmulation) {
      info.name = `Chrome Emulated ${this.chrome.mobileEmulation.deviceName}`;
    }
    harBuilder.addBrowser(har, info.name, info.version);

    if (har.log.pages.length > 0) {
      har.log.pages[0].title = `${result.url} run ${index}`;
      // Hack to add the URL from a SPA
      if (result.alias && !this.aliasAndUrl[result.alias]) {
        this.aliasAndUrl[result.alias] = result.url;
        har.log.pages[0]._url = result.url;
      } else if (result.alias && this.aliasAndUrl[result.alias]) {
        har.log.pages[0]._url = this.aliasAndUrl[result.alias];
      } else {
        har.log.pages[0]._url = result.url;
      }
    }

    this.hars.push(har);
  }

  async sendAndGetDevToolsCommand(cmd, params = {}) {
    return this.cdpClient.send(cmd, params);
  }
  async sendDevToolsCommand(cmd, params = {}) {
    return this.cdpClient.send(cmd, params);
  }

  failing(url) {
    if (this.skipHar) {
      return;
    }
    this.hars.push(harBuilder.getEmptyHAR(url, 'Chrome'));
  }

  async onStop() {
    if (this.cdpClient) {
      await this.cdpClient.close();
    }
    if (this.chrome.android) {
      await this.android.removeFw();
    }
    if (!this.skipHar) {
      return { har: harBuilder.mergeHars(this.hars) };
    } else return {};
  }
}

module.exports = ChromeDelegate;
<|endoftext|>


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

// This is where all phases, related to Chromium checkout and build should live.
// Interfacing with ninja, gclient, git cl? This is gthe spot.

var phase = require('../../core/phase-register');
var types = require('../../core/types');

var options = require('./chromium-options');
var Executable = require('./executable');

module.exports.buildChromium = phase({input: types.string, output: types.string, arity: '1:1', async: true},
  function(data, tags, cb) {
    var ninja = new Executable(options.path, 'ninja', [ '-C', 'out/' + options.buildConfig, options.buildTarget ]);
    return ninja.run().then(function(code) {
      if (code) {
        var errorMessage = '"' + ninja + '" returned a non-zero exit code "' + code + '".\nThis is likely a Chromium build error.';
        throw new Error(errorMessage);
      }
      return data;
    });
  });

module.exports.chromeBinary = phase({input: types.string, output: types.string, arity: '1:1', async: true},
    function(data, tags, cb) {
      var opts = this.phaseBase.runtime.options;
      var args = ['chrome-binary.py', '-v', opts.version, '-d', opts.chromium, '-a', opts.platform];
      var chromeBinary = new Executable(__dirname, 'python', args);

      return chromeBinary.run().then(function(code) {
        if (code)
          throw new Error('ChromeBinary returned a non-zero exit code' + chromeBinary.stderr);
        tags.tag('chromeBinary', chromeBinary.stdout);
        console.log('chromeBinary unzipped at ' + chromeBinary.stdout);
        return data;
      })

    }, {
      version: "323860",
      chromium: "~/chromium/src",
      platform: "linux"
    });
<commit_msg>Fix import error in chromium-phases.js<commit_after>/*
  Copyright 2015 Google Inc. All Rights Reserved.
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

// This is where all phases, related to Chromium checkout and build should live.
// Interfacing with ninja, gclient, git cl? This is gthe spot.

var phase = require('../../core/register').phase;
var types = require('../../core/types');

var options = require('./chromium-options');
var Executable = require('./executable');

module.exports.buildChromium = phase({input: types.string, output: types.string, arity: '1:1', async: true},
  function(data, tags, cb) {
    var ninja = new Executable(options.path, 'ninja', [ '-C', 'out/' + options.buildConfig, options.buildTarget ]);
    return ninja.run().then(function(code) {
      if (code) {
        var errorMessage = '"' + ninja + '" returned a non-zero exit code "' + code + '".\nThis is likely a Chromium build error.';
        throw new Error(errorMessage);
      }
      return data;
    });
  });

module.exports.chromeBinary = phase({input: types.string, output: types.string, arity: '1:1', async: true},
    function(data, tags, cb) {
      var opts = this.phaseBase.runtime.options;
      var args = ['chrome-binary.py', '-v', opts.version, '-d', opts.chromium, '-a', opts.platform];
      var chromeBinary = new Executable(__dirname, 'python', args);

      return chromeBinary.run().then(function(code) {
        if (code)
          throw new Error('ChromeBinary returned a non-zero exit code' + chromeBinary.stderr);
        tags.tag('chromeBinary', chromeBinary.stdout);
        console.log('chromeBinary unzipped at ' + chromeBinary.stdout);
        return data;
      })

    }, {
      version: "323860",
      chromium: "~/chromium/src",
      platform: "linux"
    });
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Row, Col } from 'react-bootstrap'

import DateTimePreview from '../form/date-time-preview'
import DefaultMap from '../map/default-map'
import LocationField from '../form/location-field'
import PlanTripButton from '../form/plan-trip-button'
import SettingsPreview from '../form/settings-preview'
import SwitchButton from '../form/switch-button'

import MobileContainer from './container'
import MobileNavigationBar from './navigation-bar'

import { MobileScreens, setMobileScreen } from '../../actions/ui'

class MobileSearchScreen extends Component {
  static propTypes = {
    icons: PropTypes.object,
    map: PropTypes.element,

    setMobileScreen: PropTypes.func
  }

  _fromFieldClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_FROM_LOCATION)
  }

  _toFieldClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_TO_LOCATION)
  }

  _expandDateTimeClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_DATETIME)
  }

  _expandOptionsClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_OPTIONS)
  }

  _planTripClicked = () => {
    this.props.setMobileScreen(MobileScreens.RESULTS_SUMMARY)
  }

  render () {
    const { icons } = this.props

    return (
      <MobileContainer>
        <MobileNavigationBar headerText='Plan Your Trip' />

          <LocationField
            type='from'
            onClick={this._fromFieldClicked}
            showClearButton={false}
          />
          <LocationField
            type='to'
            onClick={this._toFieldClicked}
            showClearButton={false}
          />

          {/*

            <SwitchButton content={} />

*/}

          <Row>
            <Col xs={6} style={{ borderRight: '2px solid #ccc' }}>
              <DateTimePreview
                onClick={this._expandDateTimeClicked}
                compressed
              />
            </Col>
            <Col xs={6}>
              <SettingsPreview
                onClick={this._expandOptionsClicked}
                icons={icons}
                compressed
              />
            </Col>
          </Row>

          <PlanTripButton onClick={this._planTripClicked} />

          <DefaultMap />

      </MobileContainer>
    )
  }
}

// connect to the redux store

const mapStateToProps = (state, ownProps) => {
  return { }
}

const mapDispatchToProps = {
  setMobileScreen
}

export default connect(mapStateToProps, mapDispatchToProps)(MobileSearchScreen)
<commit_msg>feat(mobile): Re-enable switch button on mobile<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Row, Col } from 'react-bootstrap'

import DateTimePreview from '../form/date-time-preview'
import DefaultMap from '../map/default-map'
import LocationField from '../form/location-field'
import PlanTripButton from '../form/plan-trip-button'
import SettingsPreview from '../form/settings-preview'
import SwitchButton from '../form/switch-button'

import MobileContainer from './container'
import MobileNavigationBar from './navigation-bar'

import { MobileScreens, setMobileScreen } from '../../actions/ui'

class MobileSearchScreen extends Component {
  static propTypes = {
    icons: PropTypes.object,
    map: PropTypes.element,

    setMobileScreen: PropTypes.func
  }

  _fromFieldClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_FROM_LOCATION)
  }

  _toFieldClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_TO_LOCATION)
  }

  _expandDateTimeClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_DATETIME)
  }

  _expandOptionsClicked = () => {
    this.props.setMobileScreen(MobileScreens.SET_OPTIONS)
  }

  _planTripClicked = () => {
    this.props.setMobileScreen(MobileScreens.RESULTS_SUMMARY)
  }

  render () {
    const { icons } = this.props

    return (
      <MobileContainer>
        <MobileNavigationBar headerText='Plan Your Trip' />

          <LocationField
            type='from'
            onClick={this._fromFieldClicked}
            showClearButton={false}
          />
          <LocationField
            type='to'
            onClick={this._toFieldClicked}
            showClearButton={false}
          />

            <SwitchButton content={} />

          <Row>
            <Col xs={6} style={{ borderRight: '2px solid #ccc' }}>
              <DateTimePreview
                onClick={this._expandDateTimeClicked}
                compressed
              />
            </Col>
            <Col xs={6}>
              <SettingsPreview
                onClick={this._expandOptionsClicked}
                icons={icons}
                compressed
              />
            </Col>
          </Row>

          <PlanTripButton onClick={this._planTripClicked} />

          <DefaultMap />

      </MobileContainer>
    )
  }
}

// connect to the redux store

const mapStateToProps = (state, ownProps) => {
  return { }
}

const mapDispatchToProps = {
  setMobileScreen
}

export default connect(mapStateToProps, mapDispatchToProps)(MobileSearchScreen)
<|endoftext|>


<commit_before>var IncomingCallBack = require('../constructors/callback');
var NameSpace = require('../constructors/namespace');
var routeController = require('./routeController');

var core;

var incomingCallbacks = {};
var outgoingCallbacks = {};
var nameSpaces = {};

var executionController = {

    initialize: function(samsaaraCore) {
        core = samsaaraCore;

        nameSpaces.core = new NameSpace('core', {});
        nameSpaces.internal = new NameSpace('internal', {
            callItBack: callItBack,
            callItBackError: callItBackError
        });
    },

    // Outgoing Execution

    execute: function(channel, route, executorArray, namespaceName, funcName, args) {

        var packet = {
            func: funcName,
            ns: namespaceName || 'core',
            args: args
        };

        if (typeof args[args.length - 1] === 'function') {
            packet.args = Array.prototype.slice.call(args);
            createCallBack(packet.args.pop(), executorArray, packet);
        }

        routeController.routeOutgoingPacket(channel, route, packet);
    },

    executeRaw: function(channel, route, executorArray, packet, callBack) {

        if (typeof callBack === 'function') {
            createCallBack(callBack, executorArray, packet);
        }

        routeController.routeOutgoingPacket(channel, route, packet);
    },

    // Incoming Execution

    executeFunction: function(executor, context, incomingPacket, callBackGenerator) {

        var functionName = incomingPacket.func;
        var namespaceName = incomingPacket.ns || 'core';
        var namespace = this.nameSpace(namespaceName);
        var namespaceMethods;
        var messageArgs;
        var theCallBack;
        var callbackID;

        if (namespace !== undefined) {

            namespaceMethods = namespace.methods;

            if (typeof namespaceMethods[functionName] === 'function') {

                messageArgs = incomingPacket.args || [];

                callBackGenerator = callBackGenerator || generateOutgoingCallBackClosure;
                callbackID = incomingPacket.callBack;

                if (typeof callbackID === 'string' && callbackID.match(/^([a-zA-Z0-9\.]+)$/)) {
                    theCallBack = outgoingCallbacks[callbackID] = callBackGenerator(callbackID, executor);
                    messageArgs.push(theCallBack);
                }

                namespaceMethods[functionName].apply(context, messageArgs);

            } else {
                console.error('Samsaara Method Execution ERROR: Call by:', executor.id, ':', functionName, 'is not an exposed Samsaara Object that can be executed.');
            }

        } else {
            console.error('Samsaara Method Execution ERROR: Call by:', executor.id, ':', namespaceName, 'is not valid namespace.');
        }
    },

    // Exported to Core

    createNamespace: function(namespaceName, methods) {

        var nameSpace = null;

        if (namespaceName !== 'core' && namespaceName !== 'internal') {
            nameSpace = new NameSpace(namespaceName, methods);
            nameSpaces[namespaceName] = nameSpace;
        }

        return core;
    },

    nameSpace: function(namespaceName) {
        return nameSpaces[namespaceName];
    },

    expose: function(set) {
        this.nameSpace('core').expose(set);
        return core;
    }
};

// a method to process a packet for multiple executors
// args is initially an arguments object
function processPacket(executorArray, packet, args) {

    if (typeof args[args.length - 1] === 'function') {
        args = Array.prototype.slice.call(args);
        createCallBack(args.pop(), executorArray, packet);
    }

    packet.args = args;

    return packet;
}

// Incoming CallBack Generator
// Creates an expected Callback method, whose index is sent to clients.
// The callback will expect a certain number of processes/clients to execute before getting deleted/set to undefined.
function createCallBack(theCallBack, executorArray, packet) {

    var incomingCallback = new IncomingCallBack(theCallBack, executorArray, destroyCallBack);
    var callbackID = incomingCallback.callbackID;

    incomingCallbacks[callbackID] = incomingCallback;
    packet.callBack = callbackID;

    return incomingCallback;
}

function destroyCallBack(callbackID) {
    incomingCallbacks[callbackID] = undefined;
}

// Outgoing CallBack Generator
// Returns a function to send a message answering a callBack request sent from the client
function generateOutgoingCallBackClosure(callbackID, executor) {

    var theCallBack = function() {
        var args = Array.prototype.slice.call(arguments),
            packet = {
                ns: 'internal',
                func: 'callItBack',
                args: [callbackID, args]
            },
            aCallBack;

        if (typeof args[args.length - 1] !== 'function') {
            executor.executeRaw(packet);
        } else {
            aCallBack = args.pop();
            executor.executeRaw(packet, aCallBack);
        }

        delete outgoingCallbacks[callbackID];
    };

    return theCallBack;
}

// Exposed CallBack Execution Method
// Allows the client to execute an indexed method that was stored for callback
function callItBack(callbackID, args) {

    var executor = this;
    var executorID = executor.id;
    var theCallBack = incomingCallbacks[callbackID];

    if (theCallBack !== undefined && args instanceof Array) {

        if (typeof arguments[arguments.length - 1] === 'function') {
            args.push(arguments[arguments.length - 1]);
        }

        theCallBack.executeCallBack(executorID, executor, args);
    }
}

// Exposed CallBack Execution Error Method
// Allows the client to execute an indexed method that was stored for callback
function callItBackError(callbackID, args) {

    var executor = this;
    var executorID = executor.id;
    var theCallBack = incomingCallbacks[callbackID];

    if (theCallBack !== undefined) {
        theCallBack.callBackError(executorID, executor, args);
    }
}

module.exports = executionController;
<commit_msg>Always convert args to array before sending.<commit_after>var IncomingCallBack = require('../constructors/callback');
var NameSpace = require('../constructors/namespace');
var routeController = require('./routeController');

var core;

var incomingCallbacks = {};
var outgoingCallbacks = {};
var nameSpaces = {};

var executionController = {

    initialize: function(samsaaraCore) {
        core = samsaaraCore;

        nameSpaces.core = new NameSpace('core', {});
        nameSpaces.internal = new NameSpace('internal', {
            callItBack: callItBack,
            callItBackError: callItBackError
        });
    },

    // Outgoing Execution

    execute: function(channel, route, executorArray, namespaceName, funcName, args) {

        var packet = {
            func: funcName,
            ns: namespaceName || 'core',
            args: Array.prototype.slice.call(args)
        };

        if (typeof args[args.length - 1] === 'function') {
            createCallBack(packet.args.pop(), executorArray, packet);
        }

        routeController.routeOutgoingPacket(channel, route, packet);
    },

    executeRaw: function(channel, route, executorArray, packet, callBack) {

        if (typeof callBack === 'function') {
            createCallBack(callBack, executorArray, packet);
        }

        routeController.routeOutgoingPacket(channel, route, packet);
    },

    // Incoming Execution

    executeFunction: function(executor, context, incomingPacket, callBackGenerator) {

        var functionName = incomingPacket.func;
        var namespaceName = incomingPacket.ns || 'core';
        var namespace = this.nameSpace(namespaceName);
        var namespaceMethods;
        var messageArgs;
        var theCallBack;
        var callbackID;

        if (namespace !== undefined) {

            namespaceMethods = namespace.methods;

            if (typeof namespaceMethods[functionName] === 'function') {

                messageArgs = incomingPacket.args || [];

                callBackGenerator = callBackGenerator || generateOutgoingCallBackClosure;
                callbackID = incomingPacket.callBack;

                if (typeof callbackID === 'string' && callbackID.match(/^([a-zA-Z0-9\.]+)$/)) {
                    theCallBack = outgoingCallbacks[callbackID] = callBackGenerator(callbackID, executor);
                    messageArgs.push(theCallBack);
                }

                namespaceMethods[functionName].apply(context, messageArgs);

            } else {
                console.error('Samsaara Method Execution ERROR: Call by:', executor.id, ':', functionName, 'is not an exposed Samsaara Object that can be executed.');
            }

        } else {
            console.error('Samsaara Method Execution ERROR: Call by:', executor.id, ':', namespaceName, 'is not valid namespace.');
        }
    },

    // Exported to Core

    createNamespace: function(namespaceName, methods) {

        var nameSpace = null;

        if (namespaceName !== 'core' && namespaceName !== 'internal') {
            nameSpace = new NameSpace(namespaceName, methods);
            nameSpaces[namespaceName] = nameSpace;
        }

        return core;
    },

    nameSpace: function(namespaceName) {
        return nameSpaces[namespaceName];
    },

    expose: function(set) {
        this.nameSpace('core').expose(set);
        return core;
    }
};

// a method to process a packet for multiple executors
// args is initially an arguments object
function processPacket(executorArray, packet, args) {

    if (typeof args[args.length - 1] === 'function') {
        args = Array.prototype.slice.call(args);
        createCallBack(args.pop(), executorArray, packet);
    }

    packet.args = args;

    return packet;
}

// Incoming CallBack Generator
// Creates an expected Callback method, whose index is sent to clients.
// The callback will expect a certain number of processes/clients to execute before getting deleted/set to undefined.
function createCallBack(theCallBack, executorArray, packet) {

    var incomingCallback = new IncomingCallBack(theCallBack, executorArray, destroyCallBack);
    var callbackID = incomingCallback.callbackID;

    incomingCallbacks[callbackID] = incomingCallback;
    packet.callBack = callbackID;

    return incomingCallback;
}

function destroyCallBack(callbackID) {
    incomingCallbacks[callbackID] = undefined;
}

// Outgoing CallBack Generator
// Returns a function to send a message answering a callBack request sent from the client
function generateOutgoingCallBackClosure(callbackID, executor) {

    var theCallBack = function() {
        var args = Array.prototype.slice.call(arguments),
            packet = {
                ns: 'internal',
                func: 'callItBack',
                args: [callbackID, args]
            },
            aCallBack;

        if (typeof args[args.length - 1] !== 'function') {
            executor.executeRaw(packet);
        } else {
            aCallBack = args.pop();
            executor.executeRaw(packet, aCallBack);
        }

        delete outgoingCallbacks[callbackID];
    };

    return theCallBack;
}

// Exposed CallBack Execution Method
// Allows the client to execute an indexed method that was stored for callback
function callItBack(callbackID, args) {

    var executor = this;
    var executorID = executor.id;
    var theCallBack = incomingCallbacks[callbackID];

    if (theCallBack !== undefined && args instanceof Array) {

        if (typeof arguments[arguments.length - 1] === 'function') {
            args.push(arguments[arguments.length - 1]);
        }

        theCallBack.executeCallBack(executorID, executor, args);
    }
}

// Exposed CallBack Execution Error Method
// Allows the client to execute an indexed method that was stored for callback
function callItBackError(callbackID, args) {

    var executor = this;
    var executorID = executor.id;
    var theCallBack = incomingCallbacks[callbackID];

    if (theCallBack !== undefined) {
        theCallBack.callBackError(executorID, executor, args);
    }
}

module.exports = executionController;
<|endoftext|>


<commit_before>'use strict';

const RESERVED_WORDS = {
  JHIPSTER: ['ACCOUNT'],
  JAVA: ['ABSTRACT', 'CONTINUE', 'FOR', 'NEW', 'SWITCH', 'ASSERT', 'DEFAULT', 'GOTO', 'PACKAGE', 'SYNCHRONIZED', 'BOOLEAN', 'DO', 'IF', 'PRIVATE', 'THIS', 'BREAK', 'DOUBLE', 'IMPLEMENTS', 'PROTECTED', 'THROW', 'BYTE', 'ELSE', 'IMPORT', 'PUBLIC', 'THROWS', 'CASE', 'ENUM', 'INSTANCEOF', 'RETURN', 'TRANSIENT', 'CATCH', 'EXTENDS', 'INT', 'SHORT', 'TRY', 'CHAR', 'FINAL', 'INTERFACE', 'STATIC', 'VOID', 'CLASS', 'FINALLY', 'LONG', 'STRICTFP', 'VOLATILE', 'CONST', 'FLOAT', 'NATIVE', 'SUPER', 'WHILE'],
  MYSQL: ['ACCESSIBLE', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MASTER_SSL_VERIFY_SERVER_CERT', 'MATCH', 'MAXVALUE', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE', 'PURGE', 'RANGE', 'READ', 'READS', 'READ_WRITE', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE', 'REQUIRE', 'RESIGNAL', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SIGNAL', 'SMALLINT', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL', 'GENERAL', 'IGNORE_SERVER_IDS', 'MASTER_HEARTBEAT_PERIOD', 'MAXVALUE', 'RESIGNAL', 'SIGNAL', 'SLOW'],
  POSTGRESQL: ['ALL', 'ANALYSE', 'ANALYZE', 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASYMMETRIC', 'AUTHORIZATION', 'BINARY', 'BOTH', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLLATION', 'COLUMN', 'CONCURRENTLY', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'DEFAULT', 'DEFERRABLE', 'DESC', 'DISTINCT', 'DO', 'ELSE', 'END', 'EXCEPT', 'FALSE', 'FETCH', 'FOR', 'FOREIGN', 'FROM', 'FULL', 'GRANT', 'GROUP', 'HAVING', 'ILIKE', 'IN', 'INITIALLY', 'INNER', 'INTERSECT', 'INTO', 'IS', 'ISNULL', 'JOIN', 'LATERAL', 'LEADING', 'LEFT', 'LIKE', 'LIMIT', 'LOCALTIME', 'LOCALTIMESTAMP', 'NATURAL', 'NOT', 'NOTNULL', 'NULL', 'OFFSET', 'ON', 'ONLY', 'OR', 'ORDER', 'OUTER', 'OVERLAPS', 'PLACING', 'PRIMARY', 'REFERENCES', 'RETURNING', 'RIGHT', 'SELECT', 'SESSION_USER', 'SIMILAR', 'SOME', 'SYMMETRIC', 'TABLE', 'THEN', 'TO', 'TRAILING', 'TRUE', 'UNION', 'UNIQUE', 'USER', 'USING', 'VARIADIC', 'VERBOSE', 'WHEN', 'WHERE', 'WINDOW', 'WITH'],
  CASSANDRA: ['ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'APPLY', 'AS', 'ASC', 'ASCII', 'AUTHORIZE', 'BATCH', 'BEGIN', 'BIGINT', 'BLOB', 'BOOLEAN', 'BY', 'CLUSTERING', 'COLUMNFAMILY', 'COMPACT', 'CONSISTENCY', 'COUNT', 'COUNTER', 'CREATE', 'DECIMAL', 'DELETE', 'DESC', 'DOUBLE', 'DROP', 'EACH_QUORUM', 'FLOAT', 'FROM', 'GRANT', 'IN', 'INDEX', 'CUSTOM', 'INSERT', 'INT', 'INTO', 'KEY', 'KEYSPACE', 'LEVEL', 'LIMIT', 'LOCAL_ONE', 'LOCAL_QUORUM', 'MODIFY', 'NORECURSIVE', 'NOSUPERUSER', 'OF', 'ON', 'ONE', 'ORDER', 'PASSWORD', 'PERMISSION', 'PERMISSIONS', 'PRIMARY', 'QUORUM', 'REVOKE', 'SCHEMA', 'SELECT', 'SET', 'STORAGE', 'SUPERUSER', 'TABLE', 'TEXT', 'TIMESTAMP', 'TIMEUUID', 'THREE', 'TOKEN', 'TRUNCATE', 'TTL', 'TWO', 'TYPE', 'UPDATE', 'USE', 'USER', 'USERS', 'USING', 'UUID', 'VALUES', 'VARCHAR', 'VARINT', 'WHERE', 'WITH', 'WRITETIME', 'DISTINCT', 'BYTE', 'SMALLINT', 'COMPLEX', 'ENUM', 'DATE', 'INTERVAL', 'MACADDR', 'BITSTRING'],
  ORACLE: ['ACCESS', 'ACCOUNT', 'ACTIVATE', 'ADD', 'ADMIN', 'ADVISE', 'AFTER', 'ALL', 'ALL_ROWS', 'ALLOCATE', 'ALTER', 'ANALYZE', 'AND', 'ANY', 'ARCHIVE', 'ARCHIVELOG', 'ARRAY', 'AS', 'ASC', 'AT', 'AUDIT', 'AUTHENTICATED', 'AUTHORIZATION', 'AUTOEXTEND', 'AUTOMATIC', 'BACKUP', 'BECOME', 'BEFORE', 'BEGIN', 'BETWEEN', 'BFILE', 'BITMAP', 'BLOB', 'BLOCK', 'BODY', 'BY', 'CACHE', 'CACHE_INSTANCES', 'CANCEL', 'CASCADE', 'CAST', 'CFILE', 'CHAINED', 'CHANGE', 'CHAR', 'CHAR_CS', 'CHARACTER', 'CHECK', 'CHECKPOINT', 'CHOOSE', 'CHUNK', 'CLEAR', 'CLOB', 'CLONE', 'CLOSE', 'CLOSE_CACHED_OPEN_CURSORS', 'CLUSTER', 'COALESCE', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPATIBILITY', 'COMPILE', 'COMPLETE', 'COMPOSITE_LIMIT', 'COMPRESS', 'COMPUTE', 'CONNECT', 'CONNECT_TIME', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENTS', 'CONTINUE', 'CONTROLFILE', 'CONVERT', 'COST', 'CPU_PER_CALL', 'CPU_PER_SESSION', 'CREATE', 'CURRENT', 'CURRENT_SCHEMA', 'CURREN_USER', 'CURSOR', 'CYCLE', ' ', 'DANGLING', 'DATABASE', 'DATAFILE', 'DATAFILES', 'DATAOBJNO', 'DATE', 'DBA', 'DBHIGH', 'DBLOW', 'DBMAC', 'DEALLOCATE', 'DEBUG', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DEGREE', 'DELETE', 'DEREF', 'DESC', 'DIRECTORY', 'DISABLE', 'DISCONNECT', 'DISMOUNT', 'DISTINCT', 'DISTRIBUTED', 'DML', 'DOUBLE', 'DROP', 'DUMP', 'EACH', 'ELSE', 'ENABLE', 'END', 'ENFORCE', 'ENTRY', 'ESCAPE', 'EXCEPT', 'EXCEPTIONS', 'EXCHANGE', 'EXCLUDING', 'EXCLUSIVE', 'EXECUTE', 'EXISTS', 'EXPIRE', 'EXPLAIN', 'EXTENT', 'EXTENTS', 'EXTERNALLY', 'FAILED_LOGIN_ATTEMPTS', 'FALSE', 'FAST', 'FILE', 'FIRST_ROWS', 'FLAGGER', 'FLOAT', 'FLOB', 'FLUSH', 'FOR', 'FORCE', 'FOREIGN', 'FREELIST', 'FREELISTS', 'FROM', 'FULL', 'FUNCTION', 'GLOBAL', 'GLOBALLY', 'GLOBAL_NAME', 'GRANT', 'GROUP', 'GROUPS', 'HASH', 'HASHKEYS', 'HAVING', 'HEADER', 'HEAP', 'IDENTIFIED', 'IDGENERATORS', 'IDLE_TIME', 'IF', 'IMMEDIATE', 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDEXED', 'INDEXES', 'INDICATOR', 'IND_PARTITION', 'INITIAL', 'INITIALLY', 'INITRANS', 'INSERT', 'INSTANCE', 'INSTANCES', 'INSTEAD', 'INT', 'INTEGER', 'INTERMEDIATE', 'INTERSECT', 'INTO', 'IS', 'ISOLATION', 'ISOLATION_LEVEL', 'KEEP', 'KEY', 'KILL', 'LABEL', 'LAYER', 'LESS', 'LEVEL', 'LIBRARY', 'LIKE', 'LIMIT', 'LINK', 'LIST', 'LOB', 'LOCAL', 'LOCK', 'LOCKED', 'LOG', 'LOGFILE', 'LOGGING', 'LOGICAL_READS_PER_CALL', 'LOGICAL_READS_PER_SESSION', 'LONG', 'MANAGE', 'MASTER', 'MAX', 'MAXARCHLOGS', 'MAXDATAFILES', 'MAXEXTENTS', 'MAXINSTANCES', 'MAXLOGFILES', 'MAXLOGHISTORY', 'MAXLOGMEMBERS', 'MAXSIZE', 'MAXTRANS', 'MAXVALUE', 'MIN', 'MEMBER', 'MINIMUM', 'MINEXTENTS', 'MINUS', 'MINVALUE', 'MLSLABEL', 'MLS_LABEL_FORMAT', 'MODE', 'MODIFY', 'MOUNT', 'MOVE', 'MTS_DISPATCHERS', 'MULTISET', 'NATIONAL', 'NCHAR', 'NCHAR_CS', 'NCLOB', 'NEEDED', 'NESTED', 'NETWORK', 'NEW', 'NEXT', 'NOARCHIVELOG', 'NOAUDIT', 'NOCACHE', 'NOCOMPRESS', 'NOCYCLE', 'NOFORCE', 'NOLOGGING', 'NOMAXVALUE', 'NOMINVALUE', 'NONE', 'NOORDER', 'NOOVERRIDE', 'NOPARALLEL', 'NOPARALLEL', 'NOREVERSE', 'NORMAL', 'NOSORT', 'NOT', 'NOTHING', 'NOWAIT', 'NULL', 'NUMBER', 'NUMERIC', 'NVARCHAR2', 'OBJECT', 'OBJNO', 'OBJNO_REUSE', 'OF', 'OFF', 'OFFLINE', 'OID', 'OIDINDEX', 'OLD', 'ON', 'ONLINE', 'ONLY', 'OPCODE', 'OPEN', 'OPTIMAL', 'OPTIMIZER_GOAL', 'OPTION', 'OR', 'ORDER', 'ORGANIZATION', 'OSLABEL', 'OVERFLOW', 'OWN', 'PACKAGE', 'PARALLEL', 'PARTITION', 'PASSWORD', 'PASSWORD_GRACE_TIME', 'PASSWORD_LIFE_TIME', 'PASSWORD_LOCK_TIME', 'PASSWORD_REUSE_MAX', 'PASSWORD_REUSE_TIME', 'PASSWORD_VERIFY_FUNCTION', 'PCTFREE', 'PCTINCREASE', 'PCTTHRESHOLD', 'PCTUSED', 'PCTVERSION', 'PERCENT', 'PERMANENT', 'PLAN', 'PLSQL_DEBUG', 'POST_TRANSACTION', 'PRECISION', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVATE', 'PRIVATE_SGA', 'PRIVILEGE', 'PRIVILEGES', 'PROCEDURE', 'PROFILE', 'PUBLIC', 'PURGE', 'QUEUE', 'QUOTA', 'RANGE', 'RAW', 'RBA', 'READ', 'READUP', 'REAL', 'REBUILD', 'RECOVER', 'RECOVERABLE', 'RECOVERY', 'REF', 'REFERENCES', 'REFERENCING', 'REFRESH', 'RENAME', 'REPLACE', 'RESET', 'RESETLOGS', 'RESIZE', 'RESOURCE', 'RESTRICTED', 'RETURN', 'RETURNING', 'REUSE', 'REVERSE', 'REVOKE', 'ROLE', 'ROLES', 'ROLLBACK', 'ROW', 'ROWID', 'ROWNUM', 'ROWS', 'RULE', 'SAMPLE', 'SAVEPOINT', 'SB4', 'SCAN_INSTANCES', 'SCHEMA', 'SCN', 'SCOPE', 'SD_ALL', 'SD_INHIBIT', 'SD_SHOW', 'SEGMENT', 'SEG_BLOCK', 'SEG_FILE', 'SELECT', 'SEQUENCE', 'SERIALIZABLE', 'SESSION', 'SESSION_CACHED_CURSORS', 'SESSIONS_PER_USER', 'SET', 'SHARE', 'SHARED', 'SHARED_POOL', 'SHRINK', 'SIZE', 'SKIP', 'SKIP_UNUSABLE_INDEXES', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SORT', 'SPECIFICATION', 'SPLIT', 'SQL_TRACE', 'STANDBY', 'START', 'STATEMENT_ID', 'STATISTICS', 'STOP', 'STORAGE', 'STORE', 'STRUCTURE', 'SUCCESSFUL', 'SWITCH', 'SYS_OP_ENFORCE_NOT_NULL$', 'SYS_OP_NTCIMG$', 'SYNONYM', 'SYSDATE', 'SYSDBA', 'SYSOPER', 'SYSTEM', 'TABLE', 'TABLES', 'TABLESPACE', 'TABLESPACE_NO', 'TABNO', 'TEMPORARY', 'THAN', 'THE', 'THEN', 'THREAD', 'TIMESTAMP', 'TIME', 'TO', 'TOPLEVEL', 'TRACE', 'TRACING', 'TRANSACTION', 'TRANSITIONAL', 'TRIGGER', 'TRIGGERS', 'TRUE', 'TRUNCATE', 'TX', 'TYPE', 'UB2', 'UBA', 'UID', 'UNARCHIVED', 'UNDO', 'UNION', 'UNIQUE', 'UNLIMITED', 'UNLOCK', 'UNRECOVERABLE', 'UNTIL', 'UNUSABLE', 'UNUSED', 'UPDATABLE', 'UPDATE', 'USAGE', 'USE', 'USER', 'USING', 'VALIDATE', 'VALIDATION', 'VALUE', 'VALUES', 'VARCHAR', 'VARCHAR2', 'VARYING', 'VIEW', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITEDOWN', 'WRITEUP', 'XID', 'YEAR', 'ZONE'],
  MONGODB: ['DOCUMENT']
};

function isReserved(keyword, type) {
  return keyword != null && type != null && RESERVED_WORDS[type.toUpperCase()] != null
      && RESERVED_WORDS[type.toUpperCase()].indexOf(keyword.toUpperCase()) !== -1;

}

function isReservedClassName(keyword) {
  return isReserved(keyword, 'JHIPSTER') || isReserved(keyword, 'JAVA');
}

function isReservedTableName(keyword, databaseType) {
  return (databaseType.toUpperCase() === 'SQL')
      ? isReserved(keyword, 'MYSQL') || isReserved(keyword, 'POSTGRESQL') || isReserved(keyword, 'ORACLE')
      : isReserved(keyword, databaseType);
}

function isReservedFieldName(keyword, databaseType) {
  return isReserved(keyword, 'JAVA') || isReservedTableName(keyword, databaseType);
}

module.exports = {
  isReserved: isReserved,
  isReservedClassName: isReservedClassName,
  isReservedTableName: isReservedTableName,
  isReservedFieldName: isReservedFieldName,
  JHIPSTER: RESERVED_WORDS.JHIPSTER,
  JAVA: RESERVED_WORDS.JAVA,
  MYSQL: RESERVED_WORDS.MYSQL,
  POSTGRESQL: RESERVED_WORDS.POSTGRESQL,
  CASSANDRA: RESERVED_WORDS.CASSANDRA,
  ORACLE: RESERVED_WORDS.ORACLE,
  MONGODB: RESERVED_WORDS.MONGODB
};
<commit_msg>add reserved words for mariadb fix https://github.com/jhipster/jhipster-core/issues/66<commit_after>'use strict';

const MYSQL_RESERVED_WORDS = ['ACCESSIBLE', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MASTER_SSL_VERIFY_SERVER_CERT', 'MATCH', 'MAXVALUE', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE', 'PURGE', 'RANGE', 'READ', 'READS', 'READ_WRITE', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE', 'REQUIRE', 'RESIGNAL', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SIGNAL', 'SMALLINT', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL', 'GENERAL', 'IGNORE_SERVER_IDS', 'MASTER_HEARTBEAT_PERIOD', 'MAXVALUE', 'RESIGNAL', 'SIGNAL', 'SLOW'];

const RESERVED_WORDS = {
  JHIPSTER: ['ACCOUNT'],
  JAVA: ['ABSTRACT', 'CONTINUE', 'FOR', 'NEW', 'SWITCH', 'ASSERT', 'DEFAULT', 'GOTO', 'PACKAGE', 'SYNCHRONIZED', 'BOOLEAN', 'DO', 'IF', 'PRIVATE', 'THIS', 'BREAK', 'DOUBLE', 'IMPLEMENTS', 'PROTECTED', 'THROW', 'BYTE', 'ELSE', 'IMPORT', 'PUBLIC', 'THROWS', 'CASE', 'ENUM', 'INSTANCEOF', 'RETURN', 'TRANSIENT', 'CATCH', 'EXTENDS', 'INT', 'SHORT', 'TRY', 'CHAR', 'FINAL', 'INTERFACE', 'STATIC', 'VOID', 'CLASS', 'FINALLY', 'LONG', 'STRICTFP', 'VOLATILE', 'CONST', 'FLOAT', 'NATIVE', 'SUPER', 'WHILE'],
  MYSQL: MYSQL_RESERVED_WORDS,
  MARIADB: MYSQL_RESERVED_WORDS,
  POSTGRESQL: ['ALL', 'ANALYSE', 'ANALYZE', 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASYMMETRIC', 'AUTHORIZATION', 'BINARY', 'BOTH', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLLATION', 'COLUMN', 'CONCURRENTLY', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'DEFAULT', 'DEFERRABLE', 'DESC', 'DISTINCT', 'DO', 'ELSE', 'END', 'EXCEPT', 'FALSE', 'FETCH', 'FOR', 'FOREIGN', 'FROM', 'FULL', 'GRANT', 'GROUP', 'HAVING', 'ILIKE', 'IN', 'INITIALLY', 'INNER', 'INTERSECT', 'INTO', 'IS', 'ISNULL', 'JOIN', 'LATERAL', 'LEADING', 'LEFT', 'LIKE', 'LIMIT', 'LOCALTIME', 'LOCALTIMESTAMP', 'NATURAL', 'NOT', 'NOTNULL', 'NULL', 'OFFSET', 'ON', 'ONLY', 'OR', 'ORDER', 'OUTER', 'OVERLAPS', 'PLACING', 'PRIMARY', 'REFERENCES', 'RETURNING', 'RIGHT', 'SELECT', 'SESSION_USER', 'SIMILAR', 'SOME', 'SYMMETRIC', 'TABLE', 'THEN', 'TO', 'TRAILING', 'TRUE', 'UNION', 'UNIQUE', 'USER', 'USING', 'VARIADIC', 'VERBOSE', 'WHEN', 'WHERE', 'WINDOW', 'WITH'],
  CASSANDRA: ['ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'APPLY', 'AS', 'ASC', 'ASCII', 'AUTHORIZE', 'BATCH', 'BEGIN', 'BIGINT', 'BLOB', 'BOOLEAN', 'BY', 'CLUSTERING', 'COLUMNFAMILY', 'COMPACT', 'CONSISTENCY', 'COUNT', 'COUNTER', 'CREATE', 'DECIMAL', 'DELETE', 'DESC', 'DOUBLE', 'DROP', 'EACH_QUORUM', 'FLOAT', 'FROM', 'GRANT', 'IN', 'INDEX', 'CUSTOM', 'INSERT', 'INT', 'INTO', 'KEY', 'KEYSPACE', 'LEVEL', 'LIMIT', 'LOCAL_ONE', 'LOCAL_QUORUM', 'MODIFY', 'NORECURSIVE', 'NOSUPERUSER', 'OF', 'ON', 'ONE', 'ORDER', 'PASSWORD', 'PERMISSION', 'PERMISSIONS', 'PRIMARY', 'QUORUM', 'REVOKE', 'SCHEMA', 'SELECT', 'SET', 'STORAGE', 'SUPERUSER', 'TABLE', 'TEXT', 'TIMESTAMP', 'TIMEUUID', 'THREE', 'TOKEN', 'TRUNCATE', 'TTL', 'TWO', 'TYPE', 'UPDATE', 'USE', 'USER', 'USERS', 'USING', 'UUID', 'VALUES', 'VARCHAR', 'VARINT', 'WHERE', 'WITH', 'WRITETIME', 'DISTINCT', 'BYTE', 'SMALLINT', 'COMPLEX', 'ENUM', 'DATE', 'INTERVAL', 'MACADDR', 'BITSTRING'],
  ORACLE: ['ACCESS', 'ACCOUNT', 'ACTIVATE', 'ADD', 'ADMIN', 'ADVISE', 'AFTER', 'ALL', 'ALL_ROWS', 'ALLOCATE', 'ALTER', 'ANALYZE', 'AND', 'ANY', 'ARCHIVE', 'ARCHIVELOG', 'ARRAY', 'AS', 'ASC', 'AT', 'AUDIT', 'AUTHENTICATED', 'AUTHORIZATION', 'AUTOEXTEND', 'AUTOMATIC', 'BACKUP', 'BECOME', 'BEFORE', 'BEGIN', 'BETWEEN', 'BFILE', 'BITMAP', 'BLOB', 'BLOCK', 'BODY', 'BY', 'CACHE', 'CACHE_INSTANCES', 'CANCEL', 'CASCADE', 'CAST', 'CFILE', 'CHAINED', 'CHANGE', 'CHAR', 'CHAR_CS', 'CHARACTER', 'CHECK', 'CHECKPOINT', 'CHOOSE', 'CHUNK', 'CLEAR', 'CLOB', 'CLONE', 'CLOSE', 'CLOSE_CACHED_OPEN_CURSORS', 'CLUSTER', 'COALESCE', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPATIBILITY', 'COMPILE', 'COMPLETE', 'COMPOSITE_LIMIT', 'COMPRESS', 'COMPUTE', 'CONNECT', 'CONNECT_TIME', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENTS', 'CONTINUE', 'CONTROLFILE', 'CONVERT', 'COST', 'CPU_PER_CALL', 'CPU_PER_SESSION', 'CREATE', 'CURRENT', 'CURRENT_SCHEMA', 'CURREN_USER', 'CURSOR', 'CYCLE', ' ', 'DANGLING', 'DATABASE', 'DATAFILE', 'DATAFILES', 'DATAOBJNO', 'DATE', 'DBA', 'DBHIGH', 'DBLOW', 'DBMAC', 'DEALLOCATE', 'DEBUG', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DEGREE', 'DELETE', 'DEREF', 'DESC', 'DIRECTORY', 'DISABLE', 'DISCONNECT', 'DISMOUNT', 'DISTINCT', 'DISTRIBUTED', 'DML', 'DOUBLE', 'DROP', 'DUMP', 'EACH', 'ELSE', 'ENABLE', 'END', 'ENFORCE', 'ENTRY', 'ESCAPE', 'EXCEPT', 'EXCEPTIONS', 'EXCHANGE', 'EXCLUDING', 'EXCLUSIVE', 'EXECUTE', 'EXISTS', 'EXPIRE', 'EXPLAIN', 'EXTENT', 'EXTENTS', 'EXTERNALLY', 'FAILED_LOGIN_ATTEMPTS', 'FALSE', 'FAST', 'FILE', 'FIRST_ROWS', 'FLAGGER', 'FLOAT', 'FLOB', 'FLUSH', 'FOR', 'FORCE', 'FOREIGN', 'FREELIST', 'FREELISTS', 'FROM', 'FULL', 'FUNCTION', 'GLOBAL', 'GLOBALLY', 'GLOBAL_NAME', 'GRANT', 'GROUP', 'GROUPS', 'HASH', 'HASHKEYS', 'HAVING', 'HEADER', 'HEAP', 'IDENTIFIED', 'IDGENERATORS', 'IDLE_TIME', 'IF', 'IMMEDIATE', 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDEXED', 'INDEXES', 'INDICATOR', 'IND_PARTITION', 'INITIAL', 'INITIALLY', 'INITRANS', 'INSERT', 'INSTANCE', 'INSTANCES', 'INSTEAD', 'INT', 'INTEGER', 'INTERMEDIATE', 'INTERSECT', 'INTO', 'IS', 'ISOLATION', 'ISOLATION_LEVEL', 'KEEP', 'KEY', 'KILL', 'LABEL', 'LAYER', 'LESS', 'LEVEL', 'LIBRARY', 'LIKE', 'LIMIT', 'LINK', 'LIST', 'LOB', 'LOCAL', 'LOCK', 'LOCKED', 'LOG', 'LOGFILE', 'LOGGING', 'LOGICAL_READS_PER_CALL', 'LOGICAL_READS_PER_SESSION', 'LONG', 'MANAGE', 'MASTER', 'MAX', 'MAXARCHLOGS', 'MAXDATAFILES', 'MAXEXTENTS', 'MAXINSTANCES', 'MAXLOGFILES', 'MAXLOGHISTORY', 'MAXLOGMEMBERS', 'MAXSIZE', 'MAXTRANS', 'MAXVALUE', 'MIN', 'MEMBER', 'MINIMUM', 'MINEXTENTS', 'MINUS', 'MINVALUE', 'MLSLABEL', 'MLS_LABEL_FORMAT', 'MODE', 'MODIFY', 'MOUNT', 'MOVE', 'MTS_DISPATCHERS', 'MULTISET', 'NATIONAL', 'NCHAR', 'NCHAR_CS', 'NCLOB', 'NEEDED', 'NESTED', 'NETWORK', 'NEW', 'NEXT', 'NOARCHIVELOG', 'NOAUDIT', 'NOCACHE', 'NOCOMPRESS', 'NOCYCLE', 'NOFORCE', 'NOLOGGING', 'NOMAXVALUE', 'NOMINVALUE', 'NONE', 'NOORDER', 'NOOVERRIDE', 'NOPARALLEL', 'NOPARALLEL', 'NOREVERSE', 'NORMAL', 'NOSORT', 'NOT', 'NOTHING', 'NOWAIT', 'NULL', 'NUMBER', 'NUMERIC', 'NVARCHAR2', 'OBJECT', 'OBJNO', 'OBJNO_REUSE', 'OF', 'OFF', 'OFFLINE', 'OID', 'OIDINDEX', 'OLD', 'ON', 'ONLINE', 'ONLY', 'OPCODE', 'OPEN', 'OPTIMAL', 'OPTIMIZER_GOAL', 'OPTION', 'OR', 'ORDER', 'ORGANIZATION', 'OSLABEL', 'OVERFLOW', 'OWN', 'PACKAGE', 'PARALLEL', 'PARTITION', 'PASSWORD', 'PASSWORD_GRACE_TIME', 'PASSWORD_LIFE_TIME', 'PASSWORD_LOCK_TIME', 'PASSWORD_REUSE_MAX', 'PASSWORD_REUSE_TIME', 'PASSWORD_VERIFY_FUNCTION', 'PCTFREE', 'PCTINCREASE', 'PCTTHRESHOLD', 'PCTUSED', 'PCTVERSION', 'PERCENT', 'PERMANENT', 'PLAN', 'PLSQL_DEBUG', 'POST_TRANSACTION', 'PRECISION', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVATE', 'PRIVATE_SGA', 'PRIVILEGE', 'PRIVILEGES', 'PROCEDURE', 'PROFILE', 'PUBLIC', 'PURGE', 'QUEUE', 'QUOTA', 'RANGE', 'RAW', 'RBA', 'READ', 'READUP', 'REAL', 'REBUILD', 'RECOVER', 'RECOVERABLE', 'RECOVERY', 'REF', 'REFERENCES', 'REFERENCING', 'REFRESH', 'RENAME', 'REPLACE', 'RESET', 'RESETLOGS', 'RESIZE', 'RESOURCE', 'RESTRICTED', 'RETURN', 'RETURNING', 'REUSE', 'REVERSE', 'REVOKE', 'ROLE', 'ROLES', 'ROLLBACK', 'ROW', 'ROWID', 'ROWNUM', 'ROWS', 'RULE', 'SAMPLE', 'SAVEPOINT', 'SB4', 'SCAN_INSTANCES', 'SCHEMA', 'SCN', 'SCOPE', 'SD_ALL', 'SD_INHIBIT', 'SD_SHOW', 'SEGMENT', 'SEG_BLOCK', 'SEG_FILE', 'SELECT', 'SEQUENCE', 'SERIALIZABLE', 'SESSION', 'SESSION_CACHED_CURSORS', 'SESSIONS_PER_USER', 'SET', 'SHARE', 'SHARED', 'SHARED_POOL', 'SHRINK', 'SIZE', 'SKIP', 'SKIP_UNUSABLE_INDEXES', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SORT', 'SPECIFICATION', 'SPLIT', 'SQL_TRACE', 'STANDBY', 'START', 'STATEMENT_ID', 'STATISTICS', 'STOP', 'STORAGE', 'STORE', 'STRUCTURE', 'SUCCESSFUL', 'SWITCH', 'SYS_OP_ENFORCE_NOT_NULL$', 'SYS_OP_NTCIMG$', 'SYNONYM', 'SYSDATE', 'SYSDBA', 'SYSOPER', 'SYSTEM', 'TABLE', 'TABLES', 'TABLESPACE', 'TABLESPACE_NO', 'TABNO', 'TEMPORARY', 'THAN', 'THE', 'THEN', 'THREAD', 'TIMESTAMP', 'TIME', 'TO', 'TOPLEVEL', 'TRACE', 'TRACING', 'TRANSACTION', 'TRANSITIONAL', 'TRIGGER', 'TRIGGERS', 'TRUE', 'TRUNCATE', 'TX', 'TYPE', 'UB2', 'UBA', 'UID', 'UNARCHIVED', 'UNDO', 'UNION', 'UNIQUE', 'UNLIMITED', 'UNLOCK', 'UNRECOVERABLE', 'UNTIL', 'UNUSABLE', 'UNUSED', 'UPDATABLE', 'UPDATE', 'USAGE', 'USE', 'USER', 'USING', 'VALIDATE', 'VALIDATION', 'VALUE', 'VALUES', 'VARCHAR', 'VARCHAR2', 'VARYING', 'VIEW', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITEDOWN', 'WRITEUP', 'XID', 'YEAR', 'ZONE'],
  MONGODB: ['DOCUMENT']
};

function isReserved(keyword, type) {
  return keyword != null && type != null && RESERVED_WORDS[type.toUpperCase()] != null
      && RESERVED_WORDS[type.toUpperCase()].indexOf(keyword.toUpperCase()) !== -1;

}

function isReservedClassName(keyword) {
  return isReserved(keyword, 'JHIPSTER') || isReserved(keyword, 'JAVA');
}

function isReservedTableName(keyword, databaseType) {
  return (databaseType.toUpperCase() === 'SQL')
      ? isReserved(keyword, 'MYSQL') || isReserved(keyword, 'POSTGRESQL') || isReserved(keyword, 'ORACLE')
      : isReserved(keyword, databaseType);
}

function isReservedFieldName(keyword, databaseType) {
  return isReserved(keyword, 'JAVA') || isReservedTableName(keyword, databaseType);
}

module.exports = {
  isReserved: isReserved,
  isReservedClassName: isReservedClassName,
  isReservedTableName: isReservedTableName,
  isReservedFieldName: isReservedFieldName,
  JHIPSTER: RESERVED_WORDS.JHIPSTER,
  JAVA: RESERVED_WORDS.JAVA,
  MYSQL: RESERVED_WORDS.MYSQL,
  POSTGRESQL: RESERVED_WORDS.POSTGRESQL,
  CASSANDRA: RESERVED_WORDS.CASSANDRA,
  ORACLE: RESERVED_WORDS.ORACLE,
  MONGODB: RESERVED_WORDS.MONGODB
};
<|endoftext|>