2015-08-28 14:45:39 -04:00
|
|
|
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
|
2015-09-14 18:59:09 -04:00
|
|
|
import {isPresent, global, StringWrapper} from 'angular2/src/core/facade/lang';
|
2015-08-28 14:45:39 -04:00
|
|
|
|
|
|
|
var evalCounter = 0;
|
|
|
|
|
2015-09-14 18:59:09 -04:00
|
|
|
function nextModuleId() {
|
2015-08-28 14:45:39 -04:00
|
|
|
return `evalScript${evalCounter++}`;
|
|
|
|
}
|
|
|
|
|
2015-09-14 18:59:09 -04:00
|
|
|
export function evalModule(moduleSource: string, imports: string[][], args: any[]): Promise<any> {
|
|
|
|
var moduleId = nextModuleId();
|
2015-08-28 14:45:39 -04:00
|
|
|
var moduleSourceWithImports = [];
|
|
|
|
var importModuleNames = [];
|
2015-09-14 18:59:09 -04:00
|
|
|
imports.forEach(sourceImport => {
|
2015-08-28 14:45:39 -04:00
|
|
|
var modName = sourceImport[0];
|
|
|
|
var modAlias = sourceImport[1];
|
|
|
|
importModuleNames.push(modName);
|
2015-09-02 23:58:02 -04:00
|
|
|
// Note: After transpilation to commonJS and loading this file in a browser
|
|
|
|
// using SystemJS, the loader might get confused by the presence of require,
|
|
|
|
// and attempt to load "+ modName +.js" !?!
|
|
|
|
// A simple string concat manages to prevent that, but that is one compiler
|
|
|
|
// optimaztion away from breaking again. Proceed with caution!
|
|
|
|
moduleSourceWithImports.push(`var ${modAlias} = require` + `('${modName}');`);
|
2015-08-28 14:45:39 -04:00
|
|
|
});
|
|
|
|
moduleSourceWithImports.push(moduleSource);
|
|
|
|
|
|
|
|
var moduleBody = new Function('require', 'exports', 'module', moduleSourceWithImports.join('\n'));
|
|
|
|
var System = global['System'];
|
|
|
|
if (isPresent(System) && isPresent(System.registerDynamic)) {
|
2015-09-14 18:59:09 -04:00
|
|
|
System.registerDynamic(moduleId, importModuleNames, false, moduleBody);
|
|
|
|
return <Promise<any>>System.import(moduleId).then((module) => module.run(args));
|
2015-08-28 14:45:39 -04:00
|
|
|
} else {
|
|
|
|
var exports = {};
|
|
|
|
moduleBody(require, exports, {});
|
|
|
|
return PromiseWrapper.resolve(exports['run'](args));
|
|
|
|
}
|
|
|
|
}
|