/* globals CodeMirror, challenge_Name */
// codeStorage
var codeStorageFactory = (function($, localStorage) {
var CodeStorageProps = {
version: 0.01,
keyVersion: 'saveVersion',
keyValue: null,
updateWait: 2000,
updateTimeoutId: null
};
var CodeStorage = {
hasSaved: function() {
return this.updateTimeoutId === null;
},
onSave: function(func) {
this.eventArray.push(func);
},
setSaveKey: function(key) {
this.keyValue = key + 'Val';
},
getStoredValue: function() {
return '' + localStorage.getItem(this.keyValue);
},
setEditor: function(editor) {
this.editor = editor;
},
isAlive: function() {
var val = this.getStoredValue();
return val !== 'null' &&
val !== 'undefined' &&
(val && val.length > 0);
},
updateStorage: function() {
if (typeof localStorage !== 'undefined') {
var value = this.editor.getValue();
localStorage.setItem(this.keyValue, value);
} else {
console.log('no web storage');
}
this.updateTimeoutId = null;
}
};
function codeStorageFactory(editor, challengeName) {
var codeStorage = Object.create(CodeStorage);
$.extend(codeStorage, CodeStorageProps);
codeStorage.setEditor(editor);
codeStorage.setSaveKey(challengeName);
return codeStorage;
}
var savedVersion = localStorage.getItem(CodeStorageProps.keyVersion);
if (savedVersion === null) {
localStorage.setItem(
CodeStorageProps.keyVersion,
CodeStorageProps.version
);
}
return codeStorageFactory;
}($, localStorage));
var isInitRun = false;
var initPreview = true;
var editor;
editor = CodeMirror.fromTextArea(document.getElementById('codeEditor'), {
lineNumbers: true,
mode: 'text',
theme: 'monokai',
runnable: true,
matchBrackets: true,
autoCloseBrackets: true,
scrollbarStyle: 'null',
lineWrapping: true,
gutters: ['CodeMirror-lint-markers']
});
var codeStorage = codeStorageFactory(editor, challenge_Name);
var myCodeMirror = editor;
editor.on('keyup', function() {
clearTimeout(codeStorage.updateTimeoutId);
codeStorage.updateTimeoutId = setTimeout(
codeStorage.updateStorage,
codeStorage.updateWait
);
});
var editorValue;
var challengeSeed = challengeSeed || null;
var tests = tests || [];
var allSeeds = '';
(function() {
challengeSeed.forEach(function(elem) {
allSeeds += elem + '\n';
});
})();
editor.setOption("extraKeys", {
Tab: function(cm) {
if (cm.somethingSelected()){
cm.indentSelection("add");
} else {
var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
cm.replaceSelection(spaces);
}
},
"Shift-Tab": function(cm) {
if (cm.somethingSelected()){
cm.indentSelection("subtract");
} else {
var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
cm.replaceSelection(spaces);
}
},
"Ctrl-Enter": function() {
bonfireExecute(true);
return false;
}
});
editor.setSize("100%", "auto");
var libraryIncludes = "" +
"" +
"" +
"" +
"" +
"" +
"" +
"" +
"";
var editorValueForIFrame;
var iFrameScript = "";
var delay;
// Initialize CodeMirror editor with a nice html5 canvas demo.
editor.on("keyup", function () {
clearTimeout(delay);
delay = setTimeout(updatePreview, 300);
});
function workerError(error){
var display = $('.runTimeError');
var housing = $('#testSuite');
if(display.html() != error){
display.remove();
housing.prepend("
" + error.replace(/j\$/gi, "$").replace(/jdocument/gi, "document").replace(/jjQuery/gi, "jQuery") + "
");
display.hide().fadeIn(function(){
setTimeout(function(){
display.fadeOut(function(){
display.remove();
});
}, 1000)
});
}
}
function scopejQuery(s){
return(s.replace(/\$/gi, "j$").replace(/document/gi, "jdocument").replace(/jQuery/gi, "jjQuery"));
}
function safeHTMLRun(test){
if(challengeType === "0"){
var previewFrame = document.getElementById('preview');
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
if(editor.getValue().match(/\'));
$('#testSuite').empty();
bonfireExecute(true);
codeStorage.updateStorage();
};
var attempts = 0;
if (attempts) {
attempts = 0;
}
if(challengeType !== "0") {
var codeOutput = CodeMirror.fromTextArea(document.getElementById("codeOutput"), {
lineNumbers: false,
mode: "text",
theme: 'monokai',
readOnly: 'nocursor',
lineWrapping: true
});
codeOutput.setValue('/**\n' +
' * Your output will go here.\n' + ' * Console.log() -type statements\n' +
' * will appear in your browser\'s\n' + ' * DevTools JavaScript console.\n' +
' */');
codeOutput.setSize("100%", "100%");
}
var info = editor.getScrollInfo();
var after = editor.charCoords({
line: editor.getCursor().line + 1,
ch: 0
}, "local").top;
if (info.top + info.clientHeight < after)
editor.scrollTo(null, after - info.clientHeight + 3);
var userTests;
var testSalt = Math.random();
var scrapeTests = function(userJavaScript) {
// insert tests from mongo
for (var i = 0; i < tests.length; i++) {
userJavaScript += '\n' + tests[i];
}
var counter = 0;
var regex = new RegExp(
/(expect(\s+)?\(.*\;)|(assert(\s+)?\(.*\;)|(assert\.\w.*\;)|(.*\.should\..*\;)/
);
var match = regex.exec(userJavaScript);
while (match != null) {
var replacement = '//' + counter + testSalt;
userJavaScript = userJavaScript.substring(0, match.index) + replacement +
userJavaScript.substring(match.index + match[0].length);
if (!userTests) {
userTests = [];
}
userTests.push({
"text": match[0],
"line": counter,
"err": null
});
counter++;
match = regex.exec(userJavaScript);
}
return userJavaScript;
};
function removeComments(userJavaScript) {
var regex = new RegExp(/(\/\*[^(\*\/)]*\*\/)|\/\/[^\n]*/g);
return userJavaScript.replace(regex, '');
}
function removeLogs(userJavaScript) {
return userJavaScript.replace(/(console\.[\w]+\s*\(.*\;)/g, '');
}
var pushed = false;
var createTestDisplay = function() {
if (pushed) {
userTests.pop();
}
for (var i = 0; i < userTests.length; i++) {
var test = userTests[i];
var testDoc = document.createElement("div");
if (test.err != null) {
console.log('Should be displaying bad tests');
$(testDoc)
.html(
"
" +
test.text + "
" +
test.err + "
")
.appendTo($('#testSuite'));
} else {
$(testDoc)
.html(
"")
.appendTo($('#testSuite'));
}
};
};
var expect = chai.expect;
var assert = chai.assert;
var should = chai.should();
var reassembleTest = function(test, data) {
var lineNum = test.line;
var regexp = new RegExp("\/\/" + lineNum + testSalt);
return data.input.replace(regexp, test.text);
};
var runTests = function(err, data) {
//userTests = userTests ? null : [];
var allTestsPassed = true;
pushed = false;
$('#testSuite').children().remove();
if (err && userTests.length > 0) {
userTests = [{
text: "Program Execution Failure",
err: "No user tests were run."
}];
createTestDisplay();
}
//Add blocks to test exploits here!
else if(editorValue.match(/if\s\(null\)\sconsole\.log\(1\);/gi)){
allTestsPassed = false;
userTests = [{
text: "Program Execution Failure",
err: "Invalid if (null) console.log(1); detected"
}];
createTestDisplay();
}
else if (userTests) {
userTests.push(false);
pushed = true;
userTests.forEach(function(chaiTestFromJSON, indexOfTestArray,
__testArray) {
try {
if (chaiTestFromJSON) {
var output = eval(reassembleTest(chaiTestFromJSON, data));
}
} catch (error) {
allTestsPassed = false;
__testArray[indexOfTestArray].err = error.message;
} finally {
if (!chaiTestFromJSON) {
createTestDisplay();
}
}
});
if (allTestsPassed) {
allTestsPassed = false;
showCompletion();
}
}
};
function bonfireExecute(test) {
initPreview = false;
goodTests = 0;
attempts++;
ga('send', 'event', 'Challenge', 'ran-code', challenge_Name);
userTests = null;
$('#testSuite').empty();
if(challengeType !== "0" && !editor.getValue().match(/\$\s*?\(\s*?\$\s*?\)/gi)){
var userJavaScript = myCodeMirror.getValue();
var failedCommentTest = false;
if (userJavaScript.match(/\/\*/gi) && userJavaScript.match(/\*\//gi) == null) {
failedCommentTest = true;
}
else if (!failedCommentTest && userJavaScript.match(/\/\*/gi) && userJavaScript.match(/\/\*/gi).length > userJavaScript.match(/\*\//gi).length) {
failedCommentTest = true;
}
userJavaScript = removeComments(userJavaScript);
userJavaScript = scrapeTests(userJavaScript);
// simple fix in case the user forgets to invoke their function
if(userJavaScript.match(/function/gi)){
if(userJavaScript.match(/function\s*?\(|function\s+\w+\s*?\(/gi)){
submit(userJavaScript, function (cls, message) {
if (failedCommentTest) {
myCodeMirror.setValue(myCodeMirror.getValue() + "*/");
console.log('Caught Unfinished Comment');
codeOutput.setValue("Unfinished multi-line comment");
failedCommentTest = false;
}
else if (cls) {
codeOutput.setValue(message.error);
if(test)
runTests('Error', null);
} else {
codeOutput.setValue(message.output);
codeOutput.setValue(codeOutput.getValue().replace(/\\\"/gi, ''));
message.input = removeLogs(message.input);
if(test)
runTests(null, message);
}
});
}
else{
codeOutput.setValue("Unsafe or Unfinished function declaration");
}
}
else{
submit(userJavaScript, function (cls, message) {
if (failedCommentTest) {
myCodeMirror.setValue(myCodeMirror.getValue() + "*/");
console.log('Caught Unfinished Comment');
codeOutput.setValue("Unfinished mulit-line comment");
failedCommentTest = false;
}
else if (cls) {
codeOutput.setValue(message.error);
if(test)
runTests('Error', null);
} else {
codeOutput.setValue(message.output);
codeOutput.setValue(codeOutput.getValue().replace(/\\\"/gi, ''));
message.input = removeLogs(message.input);
if(test)
runTests(null, message);
}
});
}
}
else {
editorValueForIFrame = editor.getValue();
if (failedCommentTest) {
editor.setValue(editor.getValue() + "-->");
editorValueForIFrame = editorValueForIFrame + "-->";
}
if(!editor.getValue().match(/\$\s*?\(\s*?\$\s*?\)/gi) && challengeType === "0") {
safeHTMLRun(test);
}
else{
workerError("Unsafe $($)");
}
}
setTimeout(function() {
var $marginFix = $('.innerMarginFix');
$marginFix.css('min-height', $marginFix.height());
}, 1000);
}
$('#submitButton').on('click', function() {
bonfireExecute(true);
});
$(document).ready(function() {
var $preview = $('#preview');
isInitRun = true;
editorValue = codeStorage.isAlive() ?
codeStorage.getStoredValue() :
allSeeds;
myCodeMirror.setValue(editorValue.replace(/fccss/gi, '"));
if (typeof $preview.html() !== 'undefined') {
$preview.load(function(){
if (initPreview) {
bonfireExecute(true);
}
});
} else{
bonfireExecute(true);
}
});