Giter Club home page Giter Club logo

node-sandboxed-module's Introduction

sandboxed-module

Build Status

A sandboxed node.js module loader that lets you inject dependencies into your modules.

Installation

npm install sandboxed-module

Usage

var SandboxedModule = require('sandboxed-module');
var user = SandboxedModule.require('./user', {
  requires: {'mysql': {fake: 'mysql module'}},
  globals: {myGlobal: 'variable'},
  locals: {myLocal: 'other variable'},
});

What to do with this

This module is intended to ease dependency injection for unit testing. However, feel free to use it for whatever crimes you can think of.

API

SandboxedModule.load(moduleId, [options])

Returns a new SandboxedModule where moduleId is a regular module path / id as you would normally pass into require(). The new module will be loaded in its own v8 context, but otherwise have access to the normal node.js environment.

options is an optional object that can be used to inject any of the following:

  • requires: An object containing moduleIds and the values to inject for them when required by the sandboxed module. This does not affect children of the sandboxed module.
  • globals: An object of global variables to inject into the sandboxed module.
  • locals: An object of local variables to inject into the sandboxed module.
  • sourceTransformers: An object of named functions to transform the source code of the sandboxed module's file (e.g. transpiler language, code coverage).
  • singleOnly: If false, modules that are required by the sandboxed module will not be sandboxed. By default all modules required by the sandboxedModule will be sandboxed using the same options that were used for the original sandboxed module.
  • sourceTransformersSingleOnly: If false, the source transformers will not be run against modules required by the sandboxed module. By default it will take the same value as singleOnly.

SandboxedModule.require(moduleId, [options])

Identical to SandboxedModule.load(), but returns sandboxedModule.exports directly.

SandboxedModule.configure(options)

Sets options globally across all uses of SandboxedModule.load() and SandboxedModule.require(). This way, a commonly needed require, global, local, or sourceTransformer can be specified once across all sandboxed modules.

SandboxedModule.registerBuiltInSourceTransformer(name)

Enables a built-in source transformer by name. Currently, SandboxedModule ships with two built in source transformers:

  • "coffee" - Compiles source with CoffeeScript [Enabled by default for backwards compatibility]. Be sure to run require('coffee-script').register() or require('coffee-script/register') as well.
  • "istanbul" - Instruments sources via istanbul when istanbul code coverage is running.

For example, if you'd like to use SandboxedModule in conjunction with istanbul, just run SandboxedModule.registerBuiltInSourceTransformer('istanbul').

sandboxedModule.filename

The full path to the module.

sandboxedModule.module

The underlaying node.js Module instance.

sandboxedModule.exports

A getter returning the sandboxedModule.module.exports object.

sandboxedModule.globals

The global object of the v8 context this module was loaded in. Modifications to this object will be reflected in the sandboxed module.

sandboxedModule.locals

The local variables injected into the sandboxed module using a closure. Modifying this object has no effect on the state of the sandbox.

sandboxedModule.required

An object holding a list of all module required by the sandboxed module itself. The keys are the moduleIds used for the require calls.

sandboxedModule.sourceTransformers

An object of named functions which will transform the source code required with SandboxedModule.require. For example, CoffeeScript & istanbul support is implemented with built-in sourceTransformer functions (see #registerBuiltInSourceTransformer).

A source transformer receives the source (as it's been transformed thus far) and must return the transformed source (whether it's changed or unchanged).

An example source transformer to change all instances of the number "3" to "5" would look like this:

SandboxedModule.require('../fixture/baz', {
  sourceTransformers: {
    turn3sInto5s: function(source) {
      return source.replace(/3/g,'5');
    }
  }
})

License

sandboxed-module is licensed under the MIT license.

node-sandboxed-module's People

Contributors

alonbardavid avatar ctavan avatar domenic avatar felixge avatar helloiampau avatar klamping avatar mminder avatar oroce avatar robrich avatar searls avatar svi3c avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-sandboxed-module's Issues

Sandboxed-module error after upgrading node module from 6.x.x to 10.x.x

Getting TypeError: callSite.getFileName is not a function error after upgrading node version from 6.14.3 to 10.x.x.

I did check this with express community ( expressjs/express#3919 ) but it seems to be a bug in the https://www.npmjs.com/package/sandboxed-module.

Could you provide the solution to fix this.

var file = callSite.getFileName() || ''

                  ^

TypeError: callSite.getFileName is not a function

at callSiteLocation (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\body-parser\node_modules\depd\index.js:252:23)

at depd (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\body-parser\node_modules\depd\index.js:111:14)

at Object.<anonymous> (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\body-parser\index.js:14:32)

at SandboxedModule._compile (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\sandboxed-module\lib\sandboxed_module.js:251:19)

at createInnerSandboxedModule (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\sandboxed-module\lib\sandboxed_module.js:183:23)

at SandboxedModule.RecursiveRequireProxy (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\sandboxed-module\lib\sandboxed_module.js:214:27)

at Object.<anonymous> (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\express\lib\express.js:15:18)

at SandboxedModule._compile (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\sandboxed-module\lib\sandboxed_module.js:251:19)

at createInnerSandboxedModule (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\sandboxed-module\lib\sandboxed_module.js:183:23)

at SandboxedModule.RecursiveRequireProxy (C:\MMS_Github\MMS Upgrade 10\ManageMyStaff\node_modules\sandboxed-module\lib\sandboxed_module.js:214:27)

npm ERR! Test failed. See above for more details.

Sharing the sample application with you on below path.

https://github.com/Ashish131989/depd-module-Issues

Having trouble with new version

I've always used 0.3.0 in the past, so maybe there's just some upgrade thing I'm missing, but using 1.0.1, some (at least) of my stubs are not working. I'm using this wrapper:

SandboxedModule = require('sandboxed-module')

global.requireSubject = (path, requires, globals) ->
  console.log requires
  SandboxedModule.require("./../../#{path}",  {requires, globals})

This is in spec/helpers, so the path part isn't the problem (it does try to load the module), but then it throws [Error: Cannot find module 'ftoggleDir/.ftoggle.config'] code: 'MODULE_NOT_FOUND', but the console.log in the code above is logging (amongst other things):

'ftoggleDir/.ftoggle.config': 
   { environments: [ 'production' ],
     configDir: 'config',
     production: { path: 'ftoggle.json' } }

This is a json file, and I see that some of the recent improvements are around json files. I have tried it also with .json on the end. Is there something else I need to do to get 1.0.1 working?

Node v0.6.x compatibility

Error: require.paths is removed. Use node_modules folders, or the NODE_PATH environment variable instead.
    at Function.<anonymous> (module.js:376:11)
....

Maybe I can try to adress this during the weekend...

Support for JSCoverage

I'm computing code coverage using the lcov reporter in nodeunit with code instrumented with jscoverage. If I load the module with the standard require it correctly computes code coverage but not when the module is Sandboxed.

Any plans to support code coverage? I see there is some support for istanbul.

nyc builtin source transformer

Related to #25.

It'd be nice if the istanbul transformer also supported nyc, which in turn supports subprocesses. I got this working with the following voodoo, but I wasn't sure whether this was the supported mechanism per https://github.com/istanbuljs/nyc. Thoughts? Is this in scope?

function maybeCoverage() {
  return Object.keys(require.cache).some((path) => /node_modules\/nyc/.test(path));
}

SandboxedModule.require('.../index.js', {
  // Voodoo magic to support nyc.
  sourceTransformers: maybeCoverage() ? {
    nyc(source) {
      const Instrumenter = require('nyc/lib/instrumenters/istanbul'),
        instrumenter = Instrumenter(process.cwd(), {}),
        instrumentMethod = instrumenter.instrumentSync.bind(instrumenter);
      return instrumentMethod(source, this.filename);
    }
  } : {}
});

Problem using with chai-supertest

with sandboxed-module

var SandboxedModule = require('sandboxed-module');
global.app = SandboxedModule.require('./../app', {
  requires: {'somemodule': {}}
});
global.user = request(app).agent();

Continuously getting error: Error: listen EADDRINUSE

without sandboxed-module

global.app = require('./../app');
global.user = request(app).agent();

works fine

Error with transitive dependencies when using ES6 transfomer

I have written an ES6 transformer. The source gets transformed just fine, but when I have transitive (nested) ES6 dependencies, I get an error.

❯ node main.js
SyntaxError: Unexpected reserved word
    at SandboxedModule._compile (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:236:28)
    at createInnerSandboxedModule (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:173:23)
    at SandboxedModule.RecursiveRequireProxy (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:204:27)
    at SandboxedModule.requireInterceptor (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:217:9)
    at Object.<anonymous> (/Users/Oliver/Development/tmp/sandbox-es6-require/foo.js:9:30)
    at SandboxedModule._compile (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:241:19)
    at Function.SandboxedModule.load (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:30:19)
    at Function.SandboxedModule.require (/Users/Oliver/Development/tmp/sandbox-es6-require/node_modules/sandboxed-module/lib/sandboxed_module.js:36:15)
    at sandboxEs6Require (/Users/Oliver/Development/tmp/sandbox-es6-require/main.js:13:26)
    at Object.<anonymous> (/Users/Oliver/Development/tmp/sandbox-es6-require/main.js:15:11)

You can see my isolated test case at https://gist.github.com/4f8b74153a2f7fdb9f70.

In my example, the dependency tree is: main > foo > bar. main requires foo as a sandboxed module, applying the ES6 source transformer. foo requires bar (using ES6 import syntax).

It seems like the ES6 source transformer does not get applied to the transitive dependency (bar).

Istanbul source transformer and node_modules

I have been using the Istanbul source transformer and it works great. I have a small issue though that it doesn't ignore the node_modules folder and am getting code_coverage for these (i.e. underscore). I have written a work-around to get around this locally. Could we get this or someway to ignore files and paths included?

Will happily send you a push request if you think its worth it.

Globals don't propagate to required modules

I was trying very hard to do

var domify = sandboxedModule.require("domify", { globals: { document: myFakeDocument } });

But domify resolves to /node_modules/domify/index.js, which is just

module.exports = require('./lib/domify');

But if I insert a console.log(document) at the top of /node_modules/domify/lib/domify.js, it fails, indicating the document global didn't make it through the dependency chain.

Latest on NPM?

Has the latest version of this been pushed to NPM?

npm install sandboxed-module

has a different package.json (alhto same version) as master, and doesn't seem to include coffeescript support

coffee-script support

It seems that this module doesn't play nice with coffee-script files. However, if I compile the coffee to js it executes nicely.

I'm using node v.0.6.9 with sandboxed module 0.1.2, coffee-script v 1.2.0.

instanceof Function broken inside of sandboxed module

I have a sandboxed module with the following contents:

var foo = function () {}
console.log(1, typeof foo);
console.log(2, foo instanceof Function);
// => 1 'function'
// => 2 false

foo instanceof Function should return true, but it returns false.

json3 dosn't run in VM

Hay, i have a little problem.

I cant use json3 (socket.io, btw. socket.io-client) inside the node js VM.
When i run it i become this error: "TypeError: Cannot read property 'prototype' of undefined"
(https://github.com/bestiejs/json3)

/home/marc/NetBeansProjects/Project/node_modules/socket.io-client/node_modules/json3/lib/json3.js:50
var objectProto = Object.prototype,
^
TypeError: Cannot read property 'prototype' of undefined
at runInContext (/home/marc/NetBeansProjects/Project/node_modules/socket.io-client/node_modules/json3/lib/json3.js:50:29)

See other issue on: socketio/socket.io#2381 (comment)

Mocks and node-sandboxed-module

After using node-sandboxed-module for a while, I realised that I have to mock cretain Node.js modules more than the others.

For example, fs module is used in a number of my modules and I mock it for the unit tests. Rather than repeating it on each of those unit tests, I move it to a module https://github.com/cliffano/bagofholding/blob/master/lib/mock.js , and then just use it from my unit tests. This way I can easily check if the arguments passed to the mocks are correct, and also to simulate a certain mock value which determine the behaviour of the mocked module.

My mock.js is only a quick workaround. I was wondering if there's already a library out there which provides a complete mock version of each module in Node.js API? Using such library in conjunction of node-sandboxed-module will speed up testing, happier developers, better code coverage.

I'm also interested to learn how other people create their mocks when using node-sandboxed-module in the unit tests.

injected array instance fails test for instanceof Array

I found a defect in latest version that when i inject an array and it will not be an instance of Array any more, reproduce with below code


// lib.js
module.exports = {
    'a' : 1,
    'b' : [1,2,3]
}


// target.js
var lib = require('./lib')
    , assert = require('chai').assert

module.exports.test = function(){
    return lib.a
}

module.exports.test2 = function(){
    console.log(lib.b)
    console.log(lib.b instanceof Array)
        // should be true
    return lib.b instanceof Array
}

// test.js, with mocha 
describe('SandboxedModule', function() {
  it('should return true, for an array', function() {
    var target = SandboxedModule.require('./helper/target', {
      requires : {
        './lib' : {
          'b' : [9, 8, 7]
        }
      }
    })
    assert.isTrue(target.test2());
  })
});




module.parent undefined

see #18

var SandboxedModule = require('sandboxed-module');

var app = SandboxedModule.require('./../app', {
  requires: {'somemodule': {}}
});

vs

var app = require('./../app');

app.js

if (!module.parent) {
  console.log('Should not be called if module required');
}

Adding Module fallback function

Hi! If you need help, I would like to try implementing a shadow module like this, but rather it senses your errors in the code first, and if there aren't any, the modules get reloaded. The way I would do this, would be to clone the modules, and then delete them, and if it hasn't got any errors, it pastes the modules and tries to see if there is any errors. Hope to get a reply! My email is "[email protected]"

Source maps for source transformers

Errors originating from source that has been transformed do not have correct mappings in their stack trace. I believe this is because when source is transformed, no source map can be provided.

Could we allow a source map to be passed and then rewrite all call stacks?

Native node modules are not loaded correctly

I have this situation: a sandboxed module loads sequelize, which in turn loads the sqlite3 module.
sqlite3 has a native module (.node) implementation. Somewhere in the chain of calls to require sandboxed-module tries to compile the content of the native module as source code, which leads to an error, obviously.

I have worked around this issue locally by adding a check if the extension of the file to be loaded is ".node":

if (builtinModules.indexOf(request) >= 0 || path.extname(request) == ".node") {
   if (request in cache) return cache[request];
   return require(request);
}

I am happy to submit a pull request if you find this okay.

Circular requires that work with regular requires do not work with sandboxed-module

Node.js supports circular requires
The behavior can be odd or unexpected, but it is supported.

In some cases though, this library is loading these circular requires differently, causing them to fail.

I posted an example of such a situation here: https://github.com/thoughtless/circular_require_demo

Another example is the NPM module aws-sdk. It has a circular require between service.js and core.js.
require("sandboxed-module").require("aws-sdk") will fail.

Modules required with sandboxed-module do something weird with prototypes.

I tried to browse the code to see what exactly, but I decided it would be faster to surface the issue here and see if it's expected behavior. Maybe I'm just using this module wrong (or misunderstanding something).

I've noticed that some testing frameworks have problems in conjunction with this module. See this gist for an example: https://gist.github.com/tandrewnichols/9446085.

Below is the output from running npm test on that code (minus stack traces):

> mocha fooBar.coffee --ui mocha-given --compilers coffee:coffee-script/register --reporter spec

should is defined: { obj: {} }


  foo
@subject.foo is: {}
    1) then console.log('@subject.foo is:', this.subject.foo); return this.subject.foo.should.eql({

  bar
@subject.bar is: []
    2) then console.log('@subject.bar is:', this.subject.bar); return expect(this.subject.bar).to.deep.equal([])


  0 passing (15ms)
  2 failing

  1) foo then console.log('@subject.foo is:', this.subject.foo); return this.subject.foo.should.eql({:
     TypeError: Cannot call method 'eql' of undefined

  2) bar then console.log('@subject.bar is:', this.subject.bar); return expect(this.subject.bar).to.deep.equal([]):

Changing sandbox 'fooBar' to require './fooBar' makes the code pass. Also, wrapping @subject.foo and @subject.bar in JSON.parse(JSON.stringify(...)) makes them pass. Is some additional property being added that would make traditional comparisons fail?

Untrusted modules?

Obviously not looking for any guarantees...

Looking to understand if this is reasonably suitable for the purpose of running untrusted code and only allowing it access to specific data, not allowing access to the system/process/filesystem/runtime/etc.

locals does not appear to set variable inside the module

I'm trying to get locals working and suspect I'm doing something wrong as my scenario feels like it should be very basic.

In this simplified scenario, I have a test that should inject a local variable into my module which should override an existing variable. I then have an assertion that verifies the value was set.

mod.js looks like this

var foo = 'bar';

exports.getFoo = function(key){
    return foo;
};

and modTests.js looks like this

var SandboxedModule = require('sandboxed-module');

var mod = SandboxedModule.require('../lib/mod', {
    locals: { foo: 'baz' }
});

describe('mod', function(){
    it('should have value bar', function(){
        mod.getFoo().should.eql('baz');
    });
});

When I run the tests, I get an error that the function returns undefined. Not sure whether I'm doing something wrong here (I suspect so, as this seems like a really basic scenario) or if there's an issue in the code (I did step into it a bit, but it appeared that the local was at least collected from the options).

Allow injection of modules that do not have corresponding files

Hey,

In using this module was hoping to inject files that would be required dynamically, however I seem to be getting a file error when doing so.

I wrote an addition to add an option ignoreMissing to essentially allow the failing call to "require-like" to fail silently and fall back to the current key as the filename. Leaving the option with a default that preserves the current functionality.

I took a shot at adding a test for the option, adding "test-ignore-missing.js".

Already require'd modules are not reused

If a module has already been require'd (ie, it's cached) before SandboxedModule is invoked, then I would have expected it to reuse this cached version (unless it was explicitly overwritten by a mock) - but it seems to me that SanboxedModule is requiring each module freshly each time.

Eg, this fails when run from the test/integration directory:

var foo = require('../fixture/foo');
foo.bar = 'overwritten';

var requireFixture = SandboxedModule.require('../fixture/require');
assert.strictEqual(foo.bar, requireFixture.foo.bar);
  assert.js:102
    throw new assert.AssertionError({
          ^
  AssertionError: "overwritten" === "bar"

I had expected SandboxedModule.require to act just like a normal require unless it encountered an overwritten module.

This also makes it near impossible to test code that uses modules that rely on state. For example, in our code base we make a lot of use of the nconf library for configuration. Normally I can override any basic config settings by using nconf.overrides({someOption: 'someValue'}) before I require a module that uses nconf - but the only way around this with SandboxedModule seems to be to create a lot of nested SanboxedModule declarations, all specifying that nconf should resolve to the already-resolved nconf... Which is odd... and very difficult for a large codebase.

var nconf = require('nconf')

nconf.overrides({useTestDb: true})

var myMockModel = SandboxedModule.require('../models/myModel', {
  requires: {
    db: {theThing: {iWantTo: {mock: function() { }}}},
    // I didn't want to do this
    nconf: nconf,
    // Especially not this: but I have to to override nconf in any *other* require'd modules
    './myOtherModel': SandboxedModule.require('../models/myOtherModel', {
      requires: {
        nconf: nconf
        // etc this is worse than callback hell arghhhhhh
      }
    })
  }
})

Am I missing something with this?

Deleting modules

Hi, first of all this package works great!

I have a use-case where I want to load sandboxed modules on demand but would like to be able to clean up after them as well, i.e. removing them from memory as much as possible. Any ideas on how I could do that?

Update: after looking at the memory snapshot, looks like the code (as a string) stays in memory forever.

node-sandboxed-module test fails with node v0.6.10

I picked up this error when building my module (which depends on sandboxed-module) on Travis after they upgraded node 0.6 to v0.6.10 .
The latest 0.6 sandboxed-module successful build was from back v0.6.1 http://travis-ci.org/#!/felixge/node-sandboxed-module/jobs/327889, so I believe it would fail too with v0.6.10 .

Here's the test output snippet:

kakashi:node-sandboxed-module cliffano$ make test
[0:00:00 0 0/10 0.0% node test/integration/test-basic.js]

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ENOENT, no such file or directory 'U'
at Object.openSync (fs.js:230:18)
at Object.readFileSync (fs.js:120:15)
at SandboxedModule._getCompileInfo (/Users/cliffano/dev/workspace/node-sandboxed-module/lib/sandboxed_module.js:144:8)
at SandboxedModule._compile (/Users/cliffano/dev/workspace/node-sandboxed-module/lib/sandboxed_module.js:122:22)
at SandboxedModule._init (/Users/cliffano/dev/workspace/node-sandboxed-module/lib/sandboxed_module.js:63:8)
at Function.load (/Users/cliffano/dev/workspace/node-sandboxed-module/lib/sandboxed_module.js:25:19)
at testRequire (/Users/cliffano/dev/workspace/node-sandboxed-module/test/integration/test-basic.js:6:29)
at Object. (/Users/cliffano/dev/workspace/node-sandboxed-module/test/integration/test-basic.js:9:2)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)

... snip ...

[0:00:00 10 0/10 100.0% node test/integration/test-require.js]

Litcoffee support

Hello,

I just encountered a problem trying to test litcoffee modules.

The problem is a combination of three issues:

  1. The coffee build transformer is registered by default in lib/sandboxed_module.js:10 and you cannot deregister it:

    var registeredBuiltInSourceTransformers = ['coffee'];
    
  2. In lib/sandboxed_module.js:310 the expression

    this.filename.search('.coffee$')
    

    also matches .litcoffee files.

  3. built-in transformers are run before any custom build transformer

So I see three possible ways to get around the problem:

  1. Do not set the coffee transformer as default
  2. Use String.prototype.indexOf() instead of String.prototype.search() or escape the . at the beginning of the expression
  3. Provide the possibility to run custom transformers before the built-in transformers

Sandboxed module doesn't play nice with code coverage tools like istanbul

I'm using sandboxed-module to practice TDD with isolated unit tests and I'm absolutely loving it—fantastic contribution, all. Thank you! ✨

One thing I'm playing with this evening is integrating istanbul for code coverage and I noticed something fun: stuff required via sandboxed module is missed by istanbul's module load hook that it uses for ad hoc instrumentation of JS. As a result, the subject code I sandbox-require from my unit tests is never required from the coverage tool's perspective. Whoops!

I'm going to work on this through more nuanced usage of istanbul, but in case anyone here has an interest or has seen something like this before I figured it couldn't hurt to open a thread and ask you all.

Cheers!

strange sandbox behavior with mongoose

Hi Felix,

I'm facing a very odd behavior that I can't track down due to my beginner level on node.js. I use mocha to test my code and your's sandboxed-module (https://github.com/felixge/node-sandboxed-module) for dependency injection in some required modules for the code I'm testing.

Whenever I load a module that uses mongoose inside a sandbox all mongoose calls like model.save or model.find times-out unless I load the module twice. For example, in a piece of code like this (chopped for clarity):

    var User = sandbox.require('../../models/users', {
        requires: { // define some mocks... }
    });

    User = require('../../models/users');   

    var user = new User(user_data);
        user.save(function(err, doc){
            //do something on callback
    });

Without the User = require('../../models/users') the user.save call goes away and never callbacks. Including it makes everything works and the model class stils have the mocks injected just as if it was loaded by the sandbox.require call.

Have you heard about this before? Am I doing something wrong here?

Thanks for any help.

Source transformers do not get applied to nested requires

Given a dependency tree of: main > foo > bar. main requires foo as a sandboxed module, applying the source transformer. foo requires bar, however the source transformer is not applied.

This is demonstrated in my example where I log each time the source transformer is called (see gist for full example):

var SandboxedModule = require('sandboxed-module');

SandboxedModule.require('./foo', { sourceTransformers: {
    test: function (source) {
        console.log('test source transformer:', this.filename);
        return source;
    }
}});

Output:

❯ node main.js
test source transformer: /Users/Oliver/Development/tmp/sandbox-vm-error/foo.js

I expect:

❯ node main.js
test source transformer: /Users/Oliver/Development/tmp/sandbox-vm-error/foo.js
test source transformer: /Users/Oliver/Development/tmp/sandbox-vm-error/bar.js

https://gist.github.com/OliverJAsh/3351f4a96a02ef2e294e

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.