diff --git a/.gitignore b/.gitignore index c61bf1a..2b8db73 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules crlf.js *.log +interfaceWrapper/ru/framework.js diff --git a/dependencyInjection/ru/README.md b/dependencyInjection/ru/simple/README.md similarity index 100% rename from dependencyInjection/ru/README.md rename to dependencyInjection/ru/simple/README.md diff --git a/dependencyInjection/ru/application.js b/dependencyInjection/ru/simple/application.js similarity index 100% rename from dependencyInjection/ru/application.js rename to dependencyInjection/ru/simple/application.js diff --git a/dependencyInjection/ru/application.json b/dependencyInjection/ru/simple/application.json similarity index 100% rename from dependencyInjection/ru/application.json rename to dependencyInjection/ru/simple/application.json diff --git a/dependencyInjection/ru/component1.js b/dependencyInjection/ru/simple/component1.js similarity index 100% rename from dependencyInjection/ru/component1.js rename to dependencyInjection/ru/simple/component1.js diff --git a/dependencyInjection/ru/component1.json b/dependencyInjection/ru/simple/component1.json similarity index 100% rename from dependencyInjection/ru/component1.json rename to dependencyInjection/ru/simple/component1.json diff --git a/dependencyInjection/ru/component2.js b/dependencyInjection/ru/simple/component2.js similarity index 100% rename from dependencyInjection/ru/component2.js rename to dependencyInjection/ru/simple/component2.js diff --git a/dependencyInjection/ru/component2.json b/dependencyInjection/ru/simple/component2.json similarity index 100% rename from dependencyInjection/ru/component2.json rename to dependencyInjection/ru/simple/component2.json diff --git a/dependencyInjection/ru/component3.json b/dependencyInjection/ru/simple/component3.json similarity index 100% rename from dependencyInjection/ru/component3.json rename to dependencyInjection/ru/simple/component3.json diff --git a/dependencyInjection/ru/framework.js b/dependencyInjection/ru/simple/framework.js similarity index 100% rename from dependencyInjection/ru/framework.js rename to dependencyInjection/ru/simple/framework.js diff --git a/dependencyInjection/ru/package.json b/dependencyInjection/ru/simple/package.json similarity index 100% rename from dependencyInjection/ru/package.json rename to dependencyInjection/ru/simple/package.json diff --git a/interfaceWrapper/ru/application.js b/interfaceWrapper/ru/application.js index 90d20d9..2585873 100644 --- a/interfaceWrapper/ru/application.js +++ b/interfaceWrapper/ru/application.js @@ -1,10 +1,22 @@ // Вывод из глобального контекста модуля console.log('From application global context'); -// Объявляем функцию для события таймера -function timerEvent() { - console.log('From application timer event'); -} +var fileName = './README.md'; +var fileToWrite = './test.txt'; -// Устанавливаем функцию на таймер -setTimeout(timerEvent, 1000); +console.log('Application going to read ' + fileName); +fs.readFile(fileName, function(err, src) { + console.log('File ' + fileName + ' size ' + src.length); +}); + +var intervalID01 = setInterval(function () { + console.log('Application going to write ' + fileToWrite); + fs.appendFile(fileToWrite, 'some text\n', + function (err){ + if(err) throw err; + }); +}, 1000); + +setTimeout(function(){ + clearInterval(intervalID01); +}, 10000); \ No newline at end of file diff --git a/interfaceWrapper/ru/framework.js b/interfaceWrapper/ru/framework.js index 25b3fce..a16092d 100644 --- a/interfaceWrapper/ru/framework.js +++ b/interfaceWrapper/ru/framework.js @@ -1,32 +1,24 @@ // Пример оборачивания функции в песочнице var fs = require('fs'), - vm = require('vm'); +vm = require('vm'); +var callbacks = 0; // Объявляем хеш из которого сделаем контекст-песочницу var context = { module: {}, console: console, // Помещаем ссылку на fs API в песочницу - fs: fs, - // Оборачиваем функцию setTimeout в песочнице - setTimeout: function(callback, timeout) { - // Добавляем поведение при вызове setTimeout - console.log( - 'Call: setTimeout, ' + - 'callback function: ' + callback.name + ', ' + - 'timeout: ' + timeout - ); - setTimeout(function() { - // Добавляем поведение при срабатывании таймера - console.log('Event: setTimeout, before callback'); - // Вызываем функцию пользователя на событии таймера - callback(); - console.log('Event: setTimeout, after callback'); - }, timeout); - } + fs: wrap(fs), + setInterval: setInterval, + setTimeout: setTimeout, + clearInterval: clearInterval }; +setInterval(function() { + console.log("=========== Callbacks: " + callbacks + "=========="); +}, 5000); + // Преобразовываем хеш в контекст context.global = context; var sandbox = vm.createContext(context); @@ -38,3 +30,39 @@ fs.readFile(fileName, function(err, src) { var script = vm.createScript(src, fileName); script.runInNewContext(sandbox); }); + +function cloneInterface(anInterface) { + var clone = {}; + for (var key in anInterface) { + clone[key] = anInterface[key]; + //clone[key] = wrapFunction(key, anInterface[key]); + } + return clone; +} + +function wrapFunction(fnName, fn) { + return function wrapper() { + var args = []; + Array.prototype.push.apply(args, arguments); + console.log('Call: ' + fnName); + //console.log('Args length: ' + args.length); + console.dir(args); + + if (typeof args[args.length - 1] == "function") { + callbacks++; + args[args.length - 1] = wrapFunction('callback', args[args.length - 1]); + } + + return fn.apply(undefined, args); + } + } + + function wrap(module) { + var wrappedModule = cloneInterface(module); + for(var i in wrappedModule) { + if(typeof wrappedModule[i] === 'function') { + wrappedModule[i] = wrapFunction(i, wrappedModule[i]); + } + } + return wrappedModule; + } \ No newline at end of file diff --git a/sandboxedModule/ru/README.md b/sandboxedModule/ru/README.md index b6cb2ec..1a8c7d7 100644 --- a/sandboxedModule/ru/README.md +++ b/sandboxedModule/ru/README.md @@ -1,14 +1,7 @@ ## Описание -Цель: научиться создавать защищенные (экранированные) друг от друга контексты -для библиотек, разделять код на два слоя абстракци (прикладной и системный) и -запускать прикладной код в искуственной среде, меняя его поведение по принципу -IoC из системного кода. - -## Файлы - -* `framework.js` - небольшая часть фреймворка, необходимая для демонстрации IoC -* `application.js` - часть приложения для демонстрации IoC +`framework.js` - небольшая часть фреймворка, необходимая для демонстрации IoC +`application.js` - часть приложения для демонстрации IoC ## Запуск @@ -41,8 +34,8 @@ IoC из системного кода. 7. Экспортировать из приложения хеш с несколькими функциями и переменными и распечатать их список из фреймворка с указанием типов -8. Экспортировать из приложения функцию и вывести из вфреймворка исходник -функции и кол-во ее параметров +8. Экспортировать из приложения функцию и распечатать список ее параметров +из фреймворка (можно начать с вывода тела функции) 9. Распечатать из приложения список всего, что находится в его глобальном контексте (т.е. в песочнице приложения) с указанием типов данных diff --git a/sandboxedModule/ru/application.js b/sandboxedModule/ru/application.js index b66eff8..11a8619 100644 --- a/sandboxedModule/ru/application.js +++ b/sandboxedModule/ru/application.js @@ -5,7 +5,31 @@ // Вывод из глобального контекста модуля console.log('From application global context'); +for (var i in global){ + console.log(i +" "+ typeof global[i]); +} + +var path = require('path'); + +setTimeout(function(){ + console.log("Some message using setTimeout"); + util.log("Some message using util.log"); +}, 1000); + +var intervalID01 = setInterval(function(){ + console.log("Some message using setInterval"); +}, 1000); + +setTimeout(function(){ + clearInterval(intervalID01); +}, 3000); + +var exportedStr = 'str'; module.exports = function() { // Вывод из контекста экспортируемой функции + module.exports.exportedStr = exportedStr; + module.exports.exportedFunc = function(arg) { + return arguments.length; + }; console.log('From application exported function'); }; diff --git a/sandboxedModule/ru/console.txt b/sandboxedModule/ru/console.txt new file mode 100644 index 0000000..ca69e51 --- /dev/null +++ b/sandboxedModule/ru/console.txt @@ -0,0 +1,693 @@ +./application.js 13:1:16 From application global context +./application.js 13:1:17 Some message1 +./application.js 13:1:17 Some message3 +./application.js 13:1:18 Some message3 +./application.js 13:1:19 Some message3 +./application.js 13:1:20 Some message3 +./application.js 13:22:31 From application global context +13:22:31 path is required. +./application.js 13:22:32 Some message1 +./application.js 13:22:32 Some message3 +./application.js 13:22:33 Some message3 +./application.js 13:22:34 Some message3 +./application.js 13:22:35 Some message3 +13:23:32 path is required. +./application.js 13:24:57 From application global context +13:24:57 path is required. +./application.js 13:24:58 Some message1 +./application.js 13:24:58 Some message3 +./application.js 13:24:59 Some message3 +./application.js 13:25:0 Some message3 +./application.js 13:25:1 Some message3 +./application.js 14:32:20 From application global context +14:32:20 path is required. +./application.js 14:32:21 Some message1 +./application.js 14:32:21 Some message3 +./application.js 14:32:22 Some message3 +./application.js 14:32:23 Some message3 +./application.js 14:32:24 Some message3 +./application.js 14:34:40 From application global context +14:34:40 path is required. +./application.js 14:34:41 Some message3 +./application.js 14:34:41 Some message1 +./application.js 14:34:42 Some message3 +./application.js 14:34:43 Some message3 +./application.js 14:34:44 Some message3 +./application.js 14:40:6 From application global context +14:40:6 path is required. +./application.js 14:40:6 [object global] +./application.js 14:40:7 Some message1 +./application.js 14:40:7 Some message3 +./application.js 14:40:8 Some message3 +./application.js 14:40:9 Some message3 +./application.js 14:40:10 Some message3 +./application.js 14:49:49 From application global context +14:49:49 path is required. +./application.js 14:49:49 [object global] +./application.js 14:49:50 Some message1 +./application.js 14:49:50 Some message3 +./application.js 14:49:51 Some message3 +./application.js 14:49:52 Some message3 +./application.js 14:49:53 Some message3 +./application.js 14:50:5 From application global context +14:50:5 path is required. +./application.js 14:50:5 [object global] +./application.js 14:50:6 Some message1 +./application.js 14:50:6 Some message3 +./application.js 14:50:7 Some message3 +./application.js 14:50:8 Some message3 +./application.js 14:50:9 Some message3 +./application.js 14:50:19 From application global context +14:50:19 path is required. +./application.js 14:50:19 [object global] +./application.js 14:50:20 Some message1 +./application.js 14:50:20 Some message3 +./application.js 14:50:21 Some message3 +./application.js 14:52:54 From application global context +14:52:54 path is required. +./application.js 14:52:54 [object Object] +./application.js 14:52:54 [object Object] +./application.js 14:52:54 i +./application.js 14:52:54 [object Object] +./application.js 14:52:54 [object Object] +./application.js 14:52:54 function (callback, after) { + after *= 1; // coalesce to number or NaN + + if (!(after >= 1 && after <= TIMEOUT_MAX)) { + after = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(after); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + // fast cases + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + // slow case + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i++) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = ontimeout; + + if (process.domain) timer.domain = process.domain; + + exports.active(timer); + + return timer; +} +./application.js 14:52:54 function (timer) { + if (timer && timer._repeat) { + timer._repeat = null; + clearTimeout(timer); + } +} +./application.js 14:52:54 function (callback, repeat) { + repeat *= 1; // coalesce to number or NaN + + if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) { + repeat = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(repeat); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i += 1) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = wrapper; + timer._repeat = ontimeout; + + if (process.domain) timer.domain = process.domain; + exports.active(timer); + + return timer; + + function wrapper() { + timer._repeat(); + + // Timer might be closed - no point in restarting it + if (!timer._repeat) + return; + + // If timer is unref'd (or was - it's permanently removed from the list.) + if (this._handle) { + this._handle.start(repeat, 0); + } else { + timer._idleTimeout = repeat; + exports.active(timer); + } + } +} +./application.js 14:52:54 function (module) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + + console.log(time+" "+module+" is required."); + fs.appendFile("console.txt",time+" "+module+" is required.\n", + function (err){ + if(err) throw err; + }); + return require(module); +} +./application.js 14:52:54 [object Object] +./application.js 14:52:54 [object global] +./application.js 14:52:55 Some message1 +./application.js 14:52:55 Some message3 +./application.js 14:52:56 Some message3 +./application.js 14:54:20 From application global context +14:54:20 path is required. +./application.js 14:54:21 Some message3 +./application.js 14:54:21 Some message1 +./application.js 14:54:22 Some message3 +./application.js 14:54:24 [object Object] +./application.js 14:54:24 [object Object] +./application.js 14:54:24 [object Object] +./application.js 14:54:24 function (callback, repeat) { + repeat *= 1; // coalesce to number or NaN + + if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) { + repeat = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(repeat); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i += 1) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = wrapper; + timer._repeat = ontimeout; + + if (process.domain) timer.domain = process.domain; + exports.active(timer); + + return timer; + + function wrapper() { + timer._repeat(); + + // Timer might be closed - no point in restarting it + if (!timer._repeat) + return; + + // If timer is unref'd (or was - it's permanently removed from the list.) + if (this._handle) { + this._handle.start(repeat, 0); + } else { + timer._idleTimeout = repeat; + exports.active(timer); + } + } +} +./application.js 14:54:24 function (callback, after) { + after *= 1; // coalesce to number or NaN + + if (!(after >= 1 && after <= TIMEOUT_MAX)) { + after = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(after); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + // fast cases + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + // slow case + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i++) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = ontimeout; + + if (process.domain) timer.domain = process.domain; + + exports.active(timer); + + return timer; +} +./application.js 14:54:24 [object Object] +./application.js 14:54:24 function (timer) { + if (timer && timer._repeat) { + timer._repeat = null; + clearTimeout(timer); + } +} +./application.js 14:54:24 function (module) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + + console.log(time+" "+module+" is required."); + fs.appendFile("console.txt",time+" "+module+" is required.\n", + function (err){ + if(err) throw err; + }); + return require(module); +} +./application.js 14:54:24 [object Object] +./application.js 14:54:24 [object global] +./application.js 14:59:9 From application global context +14:59:9 path is required. +./application.js 14:59:10 Some message1 +./application.js 14:59:10 Some message3 +./application.js 14:59:11 Some message3 +./application.js 14:59:13 true +./application.js 14:59:13 4000 +./application.js 14:59:13 null +./application.js 14:59:13 null +./application.js 14:59:13 139 +./application.js 14:59:13 function (){ + for (var i in this){ + console.log(this[i]); + } +} +./application.js 14:59:13 null +./application.js 14:59:13 function () { + if (this._handle) { + this._handle.unref(); + } else if (typeof this._onTimeout === 'function') { + var now = Timer.now(); + if (!this._idleStart) this._idleStart = now; + var delay = this._idleStart + this._idleTimeout - now; + if (delay < 0) delay = 0; + + // Prevent running cb again when unref() is called during the same cb + if (this._called && !this._repeat) { + exports.unenroll(this); + return; + } + + var handle = reuse(this); + + this._handle = handle || new Timer(); + this._handle.owner = this; + this._handle[kOnTimeout] = unrefdHandle; + this._handle.start(delay, 0); + this._handle.domain = this.domain; + this._handle.unref(); + } + return this; +} +./application.js 14:59:13 function () { + if (this._handle) + this._handle.ref(); + return this; +} +./application.js 14:59:13 function () { + this._onTimeout = null; + if (this._handle) { + this._handle[kOnTimeout] = null; + this._handle.close(); + } else { + exports.unenroll(this); + } + return this; +} +./application.js 15:2:28 From application global context +./application.js 15:2:28 i +./application.js 15:2:28 undefined +./application.js 15:2:28 undefined +./application.js 15:2:28 [object Object] +./application.js 15:2:28 [object Object] +./application.js 15:2:28 function (callback, after) { + after *= 1; // coalesce to number or NaN + + if (!(after >= 1 && after <= TIMEOUT_MAX)) { + after = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(after); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + // fast cases + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + // slow case + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i++) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = ontimeout; + + if (process.domain) timer.domain = process.domain; + + exports.active(timer); + + return timer; +} +./application.js 15:2:28 function (callback, repeat) { + repeat *= 1; // coalesce to number or NaN + + if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) { + repeat = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(repeat); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i += 1) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = wrapper; + timer._repeat = ontimeout; + + if (process.domain) timer.domain = process.domain; + exports.active(timer); + + return timer; + + function wrapper() { + timer._repeat(); + + // Timer might be closed - no point in restarting it + if (!timer._repeat) + return; + + // If timer is unref'd (or was - it's permanently removed from the list.) + if (this._handle) { + this._handle.start(repeat, 0); + } else { + timer._idleTimeout = repeat; + exports.active(timer); + } + } +} +./application.js 15:2:28 function (timer) { + if (timer && timer._repeat) { + timer._repeat = null; + clearTimeout(timer); + } +} +./application.js 15:2:28 function (module) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + + console.log(time+" "+module+" is required."); + fs.appendFile("console.txt",time+" "+module+" is required.\n", + function (err){ + if(err) throw err; + }); + return require(module); +} +./application.js 15:2:28 [object Object] +./application.js 15:2:28 [object global] +15:2:28 path is required. +./application.js 15:2:29 Some message1 +./application.js 15:2:29 Some message3 +./application.js 15:2:30 Some message3 +./application.js 15:6:20 From application global context +./application.js 15:6:20 i +./application.js 15:6:20 path +./application.js 15:6:20 intervalID01 +./application.js 15:6:20 module +./application.js 15:6:20 console +./application.js 15:6:20 setTimeout +./application.js 15:6:20 setInterval +./application.js 15:6:20 clearInterval +./application.js 15:6:20 util +./application.js 15:6:20 require +./application.js 15:6:20 global +15:6:20 path is required. +./application.js 15:6:21 Some message1 +./application.js 15:6:21 Some message3 +./application.js 15:6:22 Some message3 +./application.js 15:7:6 From application global context +./application.js 15:7:6 i string i +./application.js 15:7:6 path undefined undefined +./application.js 15:7:6 intervalID01 undefined undefined +./application.js 15:7:6 module object [object Object] +./application.js 15:7:6 console object [object Object] +./application.js 15:7:6 setTimeout function function (callback, after) { + after *= 1; // coalesce to number or NaN + + if (!(after >= 1 && after <= TIMEOUT_MAX)) { + after = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(after); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + // fast cases + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + // slow case + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i++) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = ontimeout; + + if (process.domain) timer.domain = process.domain; + + exports.active(timer); + + return timer; +} +./application.js 15:7:6 setInterval function function (callback, repeat) { + repeat *= 1; // coalesce to number or NaN + + if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) { + repeat = 1; // schedule on next tick, follows browser behaviour + } + + var timer = new Timeout(repeat); + var length = arguments.length; + var ontimeout = callback; + switch (length) { + case 0: + case 1: + case 2: + break; + case 3: + ontimeout = () => callback.call(timer, arguments[2]); + break; + case 4: + ontimeout = () => callback.call(timer, arguments[2], arguments[3]); + break; + case 5: + ontimeout = + () => callback.call(timer, arguments[2], arguments[3], arguments[4]); + break; + default: + var args = new Array(length - 2); + for (var i = 2; i < length; i += 1) + args[i - 2] = arguments[i]; + ontimeout = () => callback.apply(timer, args); + break; + } + timer._onTimeout = wrapper; + timer._repeat = ontimeout; + + if (process.domain) timer.domain = process.domain; + exports.active(timer); + + return timer; + + function wrapper() { + timer._repeat(); + + // Timer might be closed - no point in restarting it + if (!timer._repeat) + return; + + // If timer is unref'd (or was - it's permanently removed from the list.) + if (this._handle) { + this._handle.start(repeat, 0); + } else { + timer._idleTimeout = repeat; + exports.active(timer); + } + } +} +./application.js 15:7:6 util object [object Object] +./application.js 15:7:6 require function function (module) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + + console.log(time+" "+module+" is required."); + fs.appendFile("console.txt",time+" "+module+" is required.\n", + function (err){ + if(err) throw err; + }); + return require(module); +} +./application.js 15:7:6 clearInterval function function (timer) { + if (timer && timer._repeat) { + timer._repeat = null; + clearTimeout(timer); + } +} +./application.js 15:7:6 global object [object global] +15:7:6 path is required. +./application.js 15:7:7 Some message1 +./application.js 15:7:7 Some message3 +./application.js 15:7:8 Some message3 +./application.js 15:8:22 From application global context +./application.js 15:8:22 i string +./application.js 15:8:22 path undefined +./application.js 15:8:22 intervalID01 undefined +./application.js 15:8:22 module object +./application.js 15:8:22 console object +./application.js 15:8:22 setTimeout function +./application.js 15:8:22 setInterval function +./application.js 15:8:22 util object +./application.js 15:8:22 clearInterval function +./application.js 15:8:22 require function +./application.js 15:8:22 global object +15:8:22 path is required. +./application.js 15:8:23 Some message1 +./application.js 15:8:23 Some message3 +./application.js 15:8:24 Some message3 +./application.js 15:10:51 From application global context +./application.js 15:10:51 i string +./application.js 15:10:51 path undefined +./application.js 15:10:51 intervalID01 undefined +./application.js 15:10:51 module object +./application.js 15:10:51 console object +./application.js 15:10:51 setTimeout function +./application.js 15:10:51 setInterval function +./application.js 15:10:51 clearInterval function +./application.js 15:10:51 util object +./application.js 15:10:51 require function +./application.js 15:10:51 global object +15:10:51 path is required. +./application.js 15:10:52 Some message1 +./application.js 15:10:52 Some message3 +./application.js 15:10:53 Some message3 +./application.js 15:11:44 From application global context +./application.js 15:11:44 i string +./application.js 15:11:44 path undefined +./application.js 15:11:44 intervalID01 undefined +./application.js 15:11:44 module object +./application.js 15:11:44 console object +./application.js 15:11:44 setTimeout function +./application.js 15:11:44 setInterval function +./application.js 15:11:44 clearInterval function +./application.js 15:11:44 util object +./application.js 15:11:44 require function +./application.js 15:11:44 global object +15:11:44 path is required. +./application.js 15:11:45 Some message1 +./application.js 15:11:45 Some message3 +./application.js 15:11:46 Some message3 diff --git a/sandboxedModule/ru/framework.js b/sandboxedModule/ru/framework.js index 03a0e99..3d936e2 100644 --- a/sandboxedModule/ru/framework.js +++ b/sandboxedModule/ru/framework.js @@ -1,26 +1,91 @@ -// Файл, демонстрирующий то, как фреймворк создает среду (песочницу) для +// Файл, демонстрирующий то, как фреймворк создает среду (песочницу) для // исполнения приложения, загружает приложение, передает ему песочницу в // качестве глобального контекста и получает ссылу на экспортируемый // приложением интерфейс. Читайте README.md в нем задания. // Фреймворк может явно зависеть от библиотек через dependency lookup var fs = require('fs'), - vm = require('vm'); +vm = require('vm'), +util = require('util'); + +var myConsole = {}; +myConsole.log = function (argument) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + + console.log(fileName+" "+time+" "+argument); + fs.appendFile("console.txt",fileName+" "+time+" "+argument+"\n", + function (err){ + if(err) throw err; + }); +} +/*var exlog = console.log; +console.log = function(argument) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + exlog(fileName+" "+time+" "+argument); +}*/ +// Чоздаем контекст-песочницу, которая станет глобальным контекстом приложения +var context = { module: {}, console: myConsole, +setTimeout: setTimeout, +setInterval: setInterval, +clearInterval: clearInterval, +util: util}; + +context.require = function (module) { + var date = new Date(); + var time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds(); + + console.log(time+" "+module+" is required."); + fs.appendFile("console.txt",time+" "+module+" is required.\n", + function (err){ + if(err) throw err; + }); + return require(module); +} + -// Создаем контекст-песочницу, которая станет глобальным контекстом приложения -var context = { module: {}, console: console }; context.global = context; var sandbox = vm.createContext(context); +var keysBefore = clone(sandbox.global); + // Читаем исходный код приложения из файла -var fileName = './application.js'; +var fileName = process.argv[2] || './application.js'; fs.readFile(fileName, function(err, src) { // Тут нужно обработать ошибки // Запускаем код приложения в песочнице var script = vm.createScript(src, fileName); script.runInNewContext(sandbox); - + + compareKeys(); + + sandbox.module.exports(); + for (var i in sandbox.module.exports) { + console.log(i + " " + typeof sandbox.module.exports[i]); + } + console.log(sandbox.module.exports.exportedFunc.toString()); + console.log("Number of arguments: "+ + sandbox.module.exports.exportedFunc(2,3,3)); // Забираем ссылку из sandbox.module.exports, можем ее исполнить, // сохранить в кеш, вывести на экран исходный код приложения и т.д. }); + +function clone(obj) { + if (null == obj || "object" != typeof obj) return obj; + var copy = obj.constructor(); + for (var attr in obj) { + if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; + } + return copy; +} + +function compareKeys(){ + for(var i in keysBefore){ + if(!(i in sandbox.global)) console.log("Deleted: "+i); + } + for(var i in sandbox.global){ + if(!(i in keysBefore)) console.log("Added: "+i); + } +} \ No newline at end of file