OLD | NEW |
(Empty) | |
| 1 let path = require("path"); |
| 2 let SandboxedModule = require("sandboxed-module"); |
| 3 |
| 4 let globals = { |
| 5 atob: data => new Buffer(data, "base64").toString("binary"), |
| 6 btoa: data => new Buffer(data, "binary").toString("base64"), |
| 7 Ci: {}, |
| 8 Cu: {import: () => { }}, |
| 9 navigator: {}, |
| 10 onShutdown: {add: () => { }}, |
| 11 Services: {obs: {addObserver: () => { }}}, |
| 12 XPCOMUtils: {generateQI: () => { }} |
| 13 }; |
| 14 |
| 15 function addExports(exports) |
| 16 { |
| 17 // Unfortunately there's not a way for a source transformer to know the name |
| 18 // of the module being transformed. This means we must add all extra exports |
| 19 // to all modules, not ideal! |
| 20 let code = "if (!('EXPORT' in exports))\n" + |
| 21 " Object.defineProperty(exports, 'EXPORT', {get: () => EXPORT});"; |
| 22 |
| 23 return src => src + "\n" + exports. |
| 24 map(name => code.replace(/EXPORT/g, name)).join("\n"); |
| 25 } |
| 26 |
| 27 function rewriteRequires(source) |
| 28 { |
| 29 // Taken from EasyPasswords |
| 30 // https://github.com/palant/easypasswords/blob/master/gulp-utils.js |
| 31 let modules = new Set(["events", "io"]); |
| 32 return source.replace(/(\brequire\(["'])([^"']+)/g, (match, prefix, request) =
> |
| 33 { |
| 34 if (modules.has(request)) |
| 35 return prefix + request + ".js"; |
| 36 return match; |
| 37 }); |
| 38 } |
| 39 |
| 40 function libPath(moduleId) |
| 41 { |
| 42 return path.resolve(__dirname, "..", "..", "lib", moduleId + ".js"); |
| 43 } |
| 44 |
| 45 exports.createSandbox = function(extraExports) |
| 46 { |
| 47 // Shared require cache for this sandbox |
| 48 let cache = {}; |
| 49 |
| 50 let options = { |
| 51 cache: cache, |
| 52 globals: globals, |
| 53 sourceTransformers: [rewriteRequires] |
| 54 }; |
| 55 if (extraExports) |
| 56 options.sourceTransformers.push(addExports(extraExports)); |
| 57 |
| 58 return (moduleId, exports) => |
| 59 { |
| 60 let key = libPath(moduleId); |
| 61 |
| 62 // Only load modules which aren't already cached for this sandbox |
| 63 if (!(key in cache)) |
| 64 cache[key] = SandboxedModule.require(moduleId, options); |
| 65 |
| 66 return cache[key]; |
| 67 }; |
| 68 }; |
OLD | NEW |