Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active August 29, 2015 13:57
Show Gist options
  • Save dfkaye/9451352 to your computer and use it in GitHub Desktop.
Save dfkaye/9451352 to your computer and use it in GitHub Desktop.
sketch of executable function context method ~ populates context props as vars into new scope ~ follows commonjs mod exports falafel
// context, scopeName, scopeFunction
// context, 'exports', fn
function exec(context, fn) {
var code = '"use strict";\n'; // need paranoid sandbox for non-strict runtimes
for (var k in context) {
if (context.hasOwnProperty(k)) {
code = code + 'var ' + k + ' = context[\'' + k + '\'];\n';
}
}
code = code + 'var exports = module.exports;\n';
// prevent context leakage
'context' in context || (code = code + 'var context = undefined;\n');
'exec' in context || (code = code + 'var exec = undefined;\n');
code = code + '(' + fn.toString() + ').call(exports)' + ';\n';
(Function('context', code))(context);
return context;
};
// Content Security Policy w/o "script-src 'self' 'unsafe-eval';"
function execWith(context, fn) {
// thnk that this has to be built specifically from command line
}
// module api - strings to protect from aggressive minifiers
//var deps = { 'module': { 'exports': { 'property': 'property value' } } };
//deps['exports'] = deps['module']['exports'];
//deps['famousFace'] = { id: 'famousFace' };
var deps = (function() {
var o = {
// own
'property': 'property value'
};
var s = {
'module': { 'exports': o }
};
// static
s['famousFace'] = { id: 'famousFace' };
return s;
}());
function M() {
// undecl = true; // use strict: ReferenceError: assignment to undeclared variable undecl
console.log(M); // this function
console.log('context: ' + context) // should be undefined
console.log('exec: ' + exec) // should be undefined
console.log('fn: ' + typeof fn) // should be undefined
console.log('code: ' + typeof code) // should be undefined
console.log('k: ' + typeof k) // should be undefined
// and finally the pay off
console.log(famousFace) // should be { id: 'famousFace' }
// commonjs api
console.log('module.exports...');
console.log(module.exports)
console.log('exports...');
console.log(exports);
console.log('this...');
console.log(this);
console.log('exports is this? ' + (exports === this)); // should be true
}
//console.log(exec.toString())
exec.call(deps['exports'], deps, M);
var errorTest = {
'module' : { 'exports' : {} },
'exec': 'test', 'context': 'test'
};
exec.call({}, errorTest, function () {
console.log('famousFace...');
console.log(exports);
console.log(typeof exec); // string
console.log(typeof context); // string
console.log(typeof famousFace); // undefined
//console.log(famousFace); // should throw, "ReferenceError: famousFace is not defined"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment