Skip to content

Instantly share code, notes, and snippets.

@sukima
Last active January 22, 2020 01:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sukima/6088546 to your computer and use it in GitHub Desktop.
Save sukima/6088546 to your computer and use it in GitHub Desktop.
A simple implementation of a javascript parser in javascript. (Used as a REPL implementation)
var Sandbox;
Sandbox = (function() {
function Sandbox() {}
Sandbox.prototype.alert = function(message) {
return console.log(message);
};
Sandbox.exec = function(code, sandbox, module) {
var func;
if (sandbox == null) {
sandbox = new Sandbox();
}
if (module == null) {
module = {};
}
func = new Function("module", "with(this){return(function(module,global,window){\"use strict\";return eval(\"" + code + "\");})(module,this,this)}");
return func.call(sandbox, module);
};
return Sandbox;
}).call(this);
describe "Sandbox", ->
beforeEach ->
@sandbox = new Sandbox()
@module = createSpyObj "module", [ "module_test_fn" ]
describe "#exec", ->
it "should provide access to context based globals", ->
spyOn @sandbox, "alert"
Sandbox.exec "alert('foobar');", @sandbox, @module
expect( @sandbox.alert ).toHaveBeenCalled()
it "should provide access to module", ->
Sandbox.exec "module.module_test_fn();", @sandbox, @module
expect( @module.module_test_fn ).toHaveBeenCalled()
it "should not leak variables to global scope", ->
try Sandbox.exec "variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module
try Sandbox.exec "this.variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module
try Sandbox.exec "global.variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module
try Sandbox.exec "window.variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module
try Sandbox.exec "var variable_should_not_be_global = 'variable_should_not_be_global';", @sandbox, @module
expect( global.variable_should_not_be_global ).not.toBeDefined()
it "should return output from code", ->
expect( Sandbox.exec("'return_value'", @sandbox, @module) ).toBe "return_value"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment