Socket
Socket
Sign inDemoInstall

enhanced-require

Package Overview
Dependencies
5
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.4.2 to 0.5.0-beta1

examples/simple-server/enhanced-require.config.js

10

bin/enhanced-require.js

@@ -8,4 +8,8 @@ #!/usr/bin/env node

require("../lib/require")(process.cwd(), {
recursive: true
})(file.join("!"));
var config = {};
var configFile = path.resolve("enhanced-require.config.js");
if(require("fs").existsSync(configFile))
config = require(configFile);
require("../lib/require")(process.cwd(), config)(file.join("!"));

@@ -8,6 +8,11 @@ #!/usr/bin/env node

require("../lib/require")(process.cwd(), {
recursive: true,
hot: true,
watch: true
})(file.join("!"));
var config = {};
var configFile = path.resolve("enhanced-require.config.js");
if(require("fs").existsSync(configFile))
config = require(configFile);
config.hot = true;
config.watch = true;
require("../lib/require")(process.cwd(), config)(file.join("!"));

@@ -0,0 +0,0 @@ # simple-server

@@ -0,0 +0,0 @@ var pageTemplate = require("./page.jade");

@@ -0,0 +0,0 @@ var http = require("http");

require("../../")(module, {
recursive: true,
hot: true,
watch: true
})("./server");

@@ -0,0 +0,0 @@ /*

@@ -0,0 +0,0 @@ var RequireContext = require("./RequireContext");

@@ -25,3 +25,5 @@ var fs = require("fs");

this.applyOnUpdate = options.applyOnUpdate !== false
this.applyOnUpdate = options.applyOnUpdate !== false;
this.lastTimestamp = Math.floor(new Date().getTime() / 1000) * 1000;
}

@@ -113,19 +115,25 @@

readFileEnabled = false;
this.changedResources[resource] = (this.changedResources[resource] || 0) + 1;
this.changedResources[resource] = true;
this._changed();
}.bind(this);
var currentContent = this.contentCache[resource];
if(currentContent) {
fs.readFile(resource, function(err, content) {
if(!readFileEnabled) return;
if(err || !content || !bufferEqual(content, currentContent))
onChange();
});
var timeout = setTimeout(function() {
fs.stat(resource, function(err, stat) {
if(err) return onChange();
if(stat.mtime.getTime() >= this.lastTimestamp) return onChange();
}.bind(this));
}, 1100);
var watcher = fs.watch(resource, { persistent: false }, function() {
fs.stat(resource, function(err, stat) {
if(err) return onChange();
if(stat.mtime.getTime() >= this.lastTimestamp) return onChange();
}.bind(this));
}.bind(this));
return {
close: function() {
watcher.close();
clearTimeout(timeout);
}
}
return fs.watch(resource, { persistent: false }, onChange)
} else {
return {
mtime: fs.statSync(resource).mtime.getTime(),
content: this.contentCache[resource]
}
return true;
}

@@ -144,3 +152,9 @@ }

if(this._status == "watch") this._status = "watch-delay";
if(this._watchDelayTimeout) clearTimeout(this._watchDelayTimeout);
if(this._watchDelayTimeout) {
clearTimeout(this._watchDelayTimeout);
} else {
this.lastTimestamp = Math.floor(new Date().getTime() / 1000) * 1000;
this.fileSystem.purge();
this.syncFileSystem.purge();
}
this._watchDelayTimeout = setTimeout(this._peekWatch.bind(this, this._onAutomaticPeekWatchResult.bind(this)), this.options.watchDelay);

@@ -157,2 +171,6 @@ }

HotRequireRoot.prototype._peekWatch = function(callback) {
if(this._watchDelayTimeout) {
clearTimeout(this._watchDelayTimeout);
this._watchDelayTimeout = 0;
}
this.currentChangedResources = {};

@@ -162,2 +180,4 @@ Object.keys(this.changedResources).forEach(function(resource) {

}, this);
this.changedResources = {};
this.lastTimestamp = Math.floor(new Date().getTime() / 1000) * 1000;

@@ -184,25 +204,20 @@ this.outdatedResources = Object.keys(this.currentChangedResources);

var count = resources.length;
resources.forEach(function(resource) {
var data = this.resources[resource];
if(data.content) {
fs.readFile(resource, function(err, content) {
if(err || !content || !bufferEqual(content, data.content)) {
this.outdatedResources.push(resource);
data.content = content;
}
return oneDone();
}.bind(this))
} else {
var newTs = Math.floor(new Date().getTime() / 1000) * 1000;
this.fileSystem.purge();
this.syncFileSystem.purge();
// have to wait at least 1s because of timestamps accuracy in fs
setTimeout(function() {
resources.forEach(function(resource) {
fs.stat(resource, function(err, stat) {
if(err || !stat || stat.mtime.getTime() != data.mtime) {
if(err || !stat || stat.mtime.getTime() > this.lastTimestamp) {
this.outdatedResources.push(resource);
data.mtime = mtime;
}
return oneDone();
return oneDone.call(this);
}.bind(this));
}
}, this);
}, this);
}.bind(this), 1100);
function oneDone() {
if(--count == 0) {
this.lastTimestamp = newTs;
return callback();

@@ -290,3 +305,2 @@ }

this.outdatedResources.forEach(function(resource) {
delete this.contentCache[resource];
this._disposeResourceLink(this.resources[resource]);

@@ -296,3 +310,3 @@ delete this.resources[resource];

this.outdatedModules.forEach(function(module) {
delete this.sourceCache[module.id];
delete this.preCache[module.id];
delete this.cache[module.id];

@@ -378,8 +392,2 @@ if(module.children) {

if(this.options.watch) {
Object.keys(this.currentChangedResources).forEach(function(resource) {
this.changedResources[resource] -= this.currentChangedResources[resource];
if(this.changedResources[resource] <= 0)
delete this.changedResources[resource];
}, this);
if(Object.keys(this.changedResources).length > 0) {

@@ -386,0 +394,0 @@ this._status = "watch-delay";

var runInThisContext = require("vm").runInThisContext;
var path = require("path");
var NormalModuleMixin = require("webpack-core/lib/NormalModuleMixin");
var wrapper = ["(function (exports, require, define, module, __filename, __dirname) {", "})"];
function stripBOM(content) {

@@ -16,4 +15,5 @@ // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)

function Module(id, parent, requireRoot) {
this.id = id;
function Module(request, loaders, resource, parent, requireRoot) {
NormalModuleMixin.call(this, loaders, resource);
this.id = request;
this.parent = parent;

@@ -23,2 +23,3 @@ this.children = [];

this.exports = {};
this.filename = this.splitQuery(this.resource)[0];

@@ -30,8 +31,26 @@ this.require = require("./require").factory(this, requireRoot);

Module.prototype._compile = function(code) {
var wrappedCode = wrapper[0] + stripBOM(code) + wrapper[1];
Module.prototype = Object.create(NormalModuleMixin.prototype);
Module.prototype.build = function(options, context, resolver, fs, callback) {
this.buildTimestamp = new Date().getTime();
return this.doBuild(options, false, resolver, fs, callback);
};
Module.prototype.buildSync = function(options, context, resolver, fs) {
this.buildTimestamp = new Date().getTime();
var e, d = false;
return this.doBuild(options, true, resolver, fs, function(err) {
e = err;
d = true;
});
if(!d) throw new Error("build is not synchron");
if(e) throw e;
};
Module.prototype._compile = function() {
var code = this._source.source();
var wrappedCode = "(function (exports, require, define, module, __filename, __dirname) {" + stripBOM(code) + "\n})";
var wrappedFunction = runInThisContext(wrappedCode, this.id, this.id == this.filename);
wrappedFunction.call(
null,
this.exports,
this.exports,
this.require,

@@ -44,2 +63,10 @@ this.require.define,

this.loaded = true;
}
};
Module.prototype.fillLoaderContext = function(loaderContext, options, sync) {
loaderContext.enhancedRequire = true;
loaderContext.target = "node";
if(sync) {
loaderContext.async = function() { return null; }
}
};

@@ -9,2 +9,3 @@ /*

var EROptionsDefaulter = require("./EROptionsDefaulter");

@@ -27,25 +28,7 @@ /**

options = options || {};
if(!options.resolve) options.resolve = {};
if(!options.resolve.loaders) options.resolve.loaders = [];
options.resolve.loaders.push(
{test: /\.node$/, loader: path.join(__dirname, "node.loader.js")},
{test: /\.coffee$/, loader: "coffee"},
{test: /\.json$/, loader: "json"},
{test: /\.jade$/, loader: "jade"}
);
if(!options.resolve.extensions)
options.resolve.extensions = ["", ".node", ".er.js", ".js"];
if(!options.resolve.loaderExtensions)
options.resolve.loaderExtensions = [".er-loader.js", ".loader.js", ".js", ""];
if(!options.resolve.loaderPostfixes)
options.resolve.loaderPostfixes = ["-er-loader", "-loader", ""];
if(!options.amd) options.amd = {};
if(!options.enhanced) options.enhanced = {};
if(!options.substitutions) options.substitutions = {};
if(!options.substitutionFactories) options.substitutionFactories = {};
if(!options.loader) options.loader = {};
if(options.watchDelay === undefined) options.watchDelay = 400;
if(options.recursive === undefined) options.recursive = options.hot;
if(options.hot && !options.recursive) throw new Error("hot option depends on recursive option");
var context = "";
if(parent.context) context = parent.context;
else if(parent.filename) context = path.dirname(parent.filename);
new EROptionsDefaulter(context).process(options)

@@ -58,11 +41,11 @@ var requireRoot = new (options.hot ? require("./HotRequireRoot") : require("./RequireRoot"))(parent, options);

var substitutions = options.substitutions;
options.substitutions = {};
requireRoot.substitutions = {};
for(var key in substitutions) {
options.substitutions[requireFn.resolve(key)] = substitutions[key];
requireRoot.substitutions[requireFn.resolve(key)] = substitutions[key];
}
var substitutionFactories = options.substitutionFactories;
options.substitutionFactories = {};
requireRoot.substitutionFactories = {};
for(var key in substitutionFactories) {
options.substitutionFactories[requireFn.resolve(key)] = substitutionFactories[key];
requireRoot.substitutionFactories[requireFn.resolve(key)] = substitutionFactories[key];
}

@@ -69,0 +52,0 @@

@@ -1,7 +0,3 @@

var fs = require("fs");
var path = require("path");
var clone = require("clone");
var execModule = require("./execModule");
var execLoaders = require("./execLoaders");
var resolve = require("enhanced-resolve");
var hasOwnProperty = Object.prototype.hasOwnProperty;

@@ -64,9 +60,10 @@

this.module = parent;
var parsedRequest = parent && resolve.parse(parent.id);
var mod = parsedRequest && (parsedRequest.resource && parsedRequest.resource.path ? parent : root.main);
if(typeof mod == "string") {
this.context = mod;
if(parent.filename) {
this.context = path.dirname(parent.filename);
} else if(parent.resource && parent.splitQuery) {
this.context = path.dirname(parent.splitQuery(parent.resource)[0]);
} else if(root.main && root.main.filename) {
this.context = path.dirname(root.main.filename);
} else {
parsedRequest = mod && resolve.parse(mod.id);
this.context = (parsedRequest) ? path.dirname(mod.id === "." ? process.argv[1] : parsedRequest.resource.path) : "";
this.context = "";
}

@@ -82,4 +79,3 @@ }

require.cache = this.root.cache;
require.sourceCache = this.root.sourceCache;
require.contentCache = this.root.contentCache;
require.preCache = this.root.preCache;
require.enhanced = this.root.options.enhanced;

@@ -92,2 +88,4 @@ require.amd = this.root.options.amd;

require.define = this.theDefine.bind(this);
require.__root = this.root;
};

@@ -116,9 +114,9 @@

// resolve request
var request = resolve.sync(context, modules, this.root.options.resolve);
// create module by resolving
var module = this.root.moduleFactory.createSync(context, modules, parent, this.root);
// check in cache
var cache = this.root.cache;
if(cache[request]) {
var m = cache[request];
if(cache[module.id]) {
var m = cache[module.id];
if(!m.substitution && parent) {

@@ -132,83 +130,45 @@ m.parents = addToSet(m.parents, parent.id);

// check for substitution
if(hasOwnProperty.call(this.root.options.substitutions, request)) {
var substitutionModule = {
id: request,
if(hasOwnProperty.call(this.root.substitutions, module.id)) {
module = {
id: module.id,
substitution: true,
exports: this.root.options.substitutions[request]
exports: this.root.substitutions[module.id]
};
cache[request] = substitutionModule;
return substitutionModule.exports;
cache[module.id] = module;
return module.exports;
}
if(hasOwnProperty.call(this.root.options.substitutionFactories, request)) {
var substitutionModule = {
id: request,
if(hasOwnProperty.call(this.root.substitutionFactories, module.id)) {
module = {
id: module.id,
substitution: true,
exports: {}
};
cache[request] = substitutionModule;
substitutionModule.exports = this.root.options.substitutionFactories[request](this.root.require);
return substitutionModule.exports;
cache[module.id] = module;
module.exports = this.root.substitutionFactories[module.id](this.root.require);
return module.exports;
}
// split loaders from resource
var requestObj = resolve.parse(request);
var filename = requestObj.resource && requestObj.resource.path;
var loaders = requestObj.loaders || [];
// check for resource cache
if(filename) {
var content = this.root.contentCache[filename];
if(!content) {
content = this.root.contentCache[filename] = fs.readFileSync(filename);
}
var preCache = this.root.preCache;
if(preCache[module.id]) {
module = preCache[module.id];
} else {
// build module
module.buildSync(this.root.options, this, this.root.resolvers.normalSync, this.root.syncFileSystem);
}
// execute the loaders
var source = this.root.sourceCache[request];
if(!source) {
var dependencies = filename ? [filename] : [];
source =
this.root.sourceCache[request] =
execLoaders.sync(
context,
request,
loaders, filename ? [filename] : [],
filename ? [content] : [],
{
loaderType: "loader",
loaders: loaders,
resourceQuery: requestObj.resource && requestObj.resource.query,
enhanced: true
},
{
cacheable: true,
files: dependencies
},
this.root.options
)[0].toString("utf-8");
this.root.setDependencies(request, dependencies);
}
// add to cache
cache[module.id] = module;
// load the source code
var exec = execModule(
source,
parent,
request,
filename,
loaders.length > 0 || this.root.options.recursive,
this.root.options,
this.root
);
// set dependencies
this.root.setDependencies(module.id, module.fileDependencies);
// add to cache
cache[request] = exec.module;
// make dependency graph
if(parent) {
exec.module.parents = [parent.id];
parent.children.push(exec.module);
module.parents = [parent.id];
parent.children.push(module);
}
// execute
return exec();
module._compile();
return module.exports;
}

@@ -220,6 +180,9 @@ }

if(existsNativeModule(name)) return callback(null, name);
return resolve(this.context, name, this.root.options.resolve, callback);
this.root.moduleFactory.create(this.context, name, null, this.root, function(err, module) {
if(err) return callback(err);
return callback(null, module.id);
});
} else {
if(existsNativeModule(name)) return name;
return resolve.sync(this.context, name, this.root.options.resolve);
return this.root.moduleFactory.createSync(this.context, name, null, this.root).id;
}

@@ -233,6 +196,3 @@ }

var reqFn = this.require;
var contentCache = this.root.contentCache;
var sourceCache = this.root.sourceCache;
var loadingContent = this.root.loadingContent;
var loadingSource = this.root.loadingSource;
var preCache = this.root.preCache;
var root = this.root;

@@ -242,77 +202,24 @@ mapAsync(modules, function(name, callback) {

if(existsNativeModule(name)) return callback(null, name);
resolve(context, name, options.resolve, callback);
}, function(err, resolvedModules) {
if(err) return callback(err);
mapAsync(resolvedModules, function(request, callback) {
if(typeof request != "string") return callback();
if(existsNativeModule(request)) return callback();
if(cache[request]) return callback();
if(hasOwnProperty.call(options.substitutions, request)) return callback();
if(hasOwnProperty.call(options.substitutionFactories, request)) return callback();
if(sourceCache[request]) return callback();
this.root.moduleFactory.create(context, name, null, this.root, callback);
}.bind(this), function(err, resolvedModules) {
if(err) return callback(reqFn, err);
mapAsync(resolvedModules, function(module, callback) {
if(cache[module.id]) return callback();
if(preCache[module.id]) return callback();
if(hasOwnProperty.call(root.substitutions, module.id)) return callback();
if(hasOwnProperty.call(root.substitutionFactories, module.id)) return callback();
// split loaders from resource
var requestObj = resolve.parse(request);
var filename = requestObj.resource && requestObj.resource.path;
var loaders = requestObj.loaders || [];
if(!filename || contentCache[filename]) return makeSource(null, contentCache[filename]);
return loadContent();
function loadContent() {
if(!loadingContent[filename]) {
loadingContent[filename] = [makeSource];
fs.readFile(filename, applyToAll(loadingContent[filename], function(content) {
if(!contentCache[filename])
contentCache[filename] = content;
delete loadingContent[filename];
return contentCache[filename];
}));
} else
loadingContent[filename].push(makeSource);
}
function makeSource(err, content) {
if(err) return callback(err);
if(!loadingSource[request]) {
loadingSource[request] = [callback];
var finished = applyToAll(loadingSource[request], function(content) {
if(!sourceCache[request])
sourceCache[request] = content;
delete loadingSource[request];
return sourceCache[request];
});
var dependencies = filename ? [filename] : [];
execLoaders(
context,
request,
loaders,
filename ? [filename] : [],
filename ? [content] : [],
{
loaderType: "loader",
loaders: loaders,
resourceQuery: requestObj.resource && requestObj.resource.query,
enhanced: true
},
{
cacheable: true,
files: dependencies
},
options,
function(err, sources) {
if(err) return finished(err);
root.setDependencies(request, dependencies);
if(sources[0] instanceof Buffer || typeof sources[0] == "string")
finished(null, sources[0].toString("utf-8"));
else
callback(new Error("Loader result is not a Buffer or string"));
}
);
} else
loadingSource[request].push(callback);
}
}, function(err) {
module.build(this.root.options, this, this.root.resolvers.normal, this.root.fileSystem, function(err) {
if(err) {
console.log(err);
return callback();
}
if(!preCache[module.id])
preCache[module.id] = module;
return callback();
});
}.bind(this), function(err) {
return callback(reqFn, err);
})
});
}.bind(this));
}

@@ -336,3 +243,5 @@

});
this.theEnsure(dependencies, function(req, err) {
this.theEnsure(dependencies.filter(function(name) {
return typeof name == "string";
}), function(req, err) {
var exp = fn.apply(null, dependencies.map(function(n) {

@@ -359,13 +268,76 @@ if(typeof n != "string") return n;

RequireContext.prototype.theContext = function theContext(contextName) {
RequireContext.prototype.theContext = function theContext(contextName, recursive, regExp) {
var contextFn = function(name) {
if(typeof name != "string" || name.substr(0, 2) != "./")
throw new Error("A function created by require.context must be called with a string beginning with './'");
if(regExp && !regExp.test(name))
throw new Error("Request '" + name + "' do not match the provided regExp " + regExp.toString() + " on require.context");
if(recursive === false && name.lastIndexOf("/") > 1)
throw new Error("Request '" + name + "' want to access a file outside the directory, this is not allowed by recursive = false");
return this.theRequire(contextName + "/" + name);
}.bind(this);
contextFn.keys = function() {
var request = resolve.context.sync(this.context, contextName, this.root.options.resolve);
var requestObj = resolve.parse(request);
var files = fs.readdirSync(requestObj.resource.path);
return files.map(function(file) { return "./" + file; });
var elements = contextName.split("!");
var resource = elements.pop();
var request = this.root.resolvers.contextSync.resolveSync(this.context, resource);
var stack = [request];
var requests = [];
var fs = this.root.syncFileSystem;
var readdirSync = function(path) {
var r;
fs.readdir(path, function(err, result) {
if(err) throw err;
r = result;
});
return r;
}
var statSync = function(path) {
var r;
fs.stat(path, function(err, result) {
if(err) throw err;
r = result;
});
return r;
}
while(stack.length > 0) {
var dir = stack.pop();
var files = readdirSync(dir);
files = files.map(function(file) {
var p = path.join(dir, file);
return {
path: p,
stat: statSync(p)
}
});
if(recursive !== false) {
stack = stack.concat(files.filter(function(obj) {
return obj.stat.isDirectory()
}).map(function(obj) {
return obj.path;
}));
}
requests = requests.concat(files.filter(function(obj) {
return obj.stat.isFile()
}).map(function(obj) {
return obj.path;
}));
}
requests = requests.map(function(req) {
return this.root.options.resolve.extensions.filter(function(ext) {
var l = req.length;
return (l > ext.length && req.substr(l - ext.length, l) == ext);
}).map(function(ext) {
var l = req.length;
return req.substr(0, l - ext.length);
});
}, this).reduce(function(arr, part) {
return arr.concat(part);
}, []).filter(function(req) {
return req.indexOf(request) == 0;
}).map(function(req) {
return "." + req.substr(request.length).replace(/\\/g, "/");
}).filter(function(req) {
return !regExp || regExp.test(req);
});
return requests.sort();
}.bind(this);

@@ -372,0 +344,0 @@ return contextFn;

@@ -0,11 +1,83 @@

var path = require("path");
var RequireContext = require("./RequireContext");
var ModuleFactory = require("./ModuleFactory");
var Resolver = require("enhanced-resolve/lib/Resolver");
var NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem");
var SyncNodeJsInputFileSystem = require("enhanced-resolve/lib/SyncNodeJsInputFileSystem");
var CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem");
var ModulesInDirectoriesPlugin = require("enhanced-resolve/lib/ModulesInDirectoriesPlugin");
var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
var ModuleTemplatesPlugin = require("enhanced-resolve/lib/ModuleTemplatesPlugin");
var ModuleAsFilePlugin = require("enhanced-resolve/lib/ModuleAsFilePlugin");
var ModuleAsDirectoryPlugin = require("enhanced-resolve/lib/ModuleAsDirectoryPlugin");
var DirectoryDefaultFilePlugin = require("enhanced-resolve/lib/DirectoryDefaultFilePlugin");
var DirectoryDescriptionFilePlugin = require("enhanced-resolve/lib/DirectoryDescriptionFilePlugin");
var DirectoryResultPlugin = require("enhanced-resolve/lib/DirectoryResultPlugin");
var FileAppendPlugin = require("enhanced-resolve/lib/FileAppendPlugin");
var ModulesInRootPlugin = require("enhanced-resolve/lib/ModulesInRootPlugin");
function RequireRoot(parent, options) {
this.main = parent;
if(parent.context) {
this.context = parent.context;
} else if(parent.filename) {
this.context = path.dirname(parent.filename);
} else this.context = options.context;
this.options = options;
this.cache = {};
this.sourceCache = {};
this.contentCache = {};
this.loadingContent = {};
this.loadingSource = {};
this.preCache = {};
this.preLoading = {};
this.fileSystem = new CachedInputFileSystem(new NodeJsInputFileSystem(), 10000);
this.syncFileSystem = new CachedInputFileSystem(new SyncNodeJsInputFileSystem(), 10000);
this.resolvers = {
normal: new Resolver(this.fileSystem),
normalSync: new Resolver(this.syncFileSystem),
context: new Resolver(this.syncFileSystem),
contextSync: new Resolver(this.syncFileSystem),
loader: new Resolver(this.fileSystem),
loaderSync: new Resolver(this.syncFileSystem),
};
(function() {
this.resolvers.normal.apply.apply(this.resolvers.normal, arguments);
this.resolvers.normalSync.apply.apply(this.resolvers.normalSync, arguments);
}.call(this,
new ModuleAliasPlugin(options.resolve.alias),
makeRootPlugin("module", options.resolve.root),
new ModulesInDirectoriesPlugin("module", options.resolve.modulesDirectories),
makeRootPlugin("module", options.resolve.fallback),
new ModuleAsFilePlugin("module"),
new ModuleAsDirectoryPlugin("module"),
new DirectoryDescriptionFilePlugin("package.json", options.resolve.packageMains),
new DirectoryDefaultFilePlugin(["index"]),
new FileAppendPlugin(options.resolve.extensions)
));
(function() {
this.resolvers.context.apply.apply(this.resolvers.context, arguments);
this.resolvers.contextSync.apply.apply(this.resolvers.contextSync, arguments);
}.call(this,
new ModuleAliasPlugin(options.resolve.alias),
makeRootPlugin("module", options.resolve.root),
new ModulesInDirectoriesPlugin("module", options.resolve.modulesDirectories),
makeRootPlugin("module", options.resolve.fallback),
new ModuleAsFilePlugin("module"),
new ModuleAsDirectoryPlugin("module"),
new DirectoryResultPlugin()
));
(function() {
this.resolvers.loader.apply.apply(this.resolvers.loader, arguments);
this.resolvers.loaderSync.apply.apply(this.resolvers.loaderSync, arguments);
}.call(this,
new ModuleAliasPlugin(options.resolveLoader.alias),
makeRootPlugin("loader-module", options.resolveLoader.root),
new ModulesInDirectoriesPlugin("loader-module", options.resolveLoader.modulesDirectories),
makeRootPlugin("loader-module", options.resolveLoader.fallback),
new ModuleTemplatesPlugin("loader-module", options.resolveLoader.moduleTemplates, "node"),
new ModuleAsFilePlugin("node"),
new ModuleAsDirectoryPlugin("node"),
new DirectoryDescriptionFilePlugin("package.json", options.resolveLoader.packageMains),
new DirectoryDefaultFilePlugin(["index"]),
new FileAppendPlugin(options.resolveLoader.extensions)
));
this.moduleFactory = new ModuleFactory(this.context, this.resolvers, options.module);
}

@@ -21,2 +93,15 @@

RequireRoot.prototype.setDependencies = function() {}
RequireRoot.prototype.setDependencies = function() {}
function makeRootPlugin(name, root) {
if(typeof root === "string")
return new ModulesInRootPlugin(name, root);
else if(Array.isArray(root)) {
return function() {
root.forEach(function(root) {
this.apply(new ModulesInRootPlugin(name, root));
}, this);
}
}
return function() {};
}
{
"name": "enhanced-require",
"version": "0.4.2",
"version": "0.5.0-beta1",
"author": "Tobias Koppers @sokra",
"description": "Enhance the require function in node.js with support for loaders which preprocess files and really async require (AMD). Enables Hot Code Replacement.",
"dependencies": {
"enhanced-resolve": "0.4.x",
"clone": "0.0.x",
"enhanced-resolve": "0.5.x",
"webpack-core": "0.1.x",
"async": "0.2.x",
"clone": "0.1.x",
"buffer-equal": "0.0.x"

@@ -18,6 +20,6 @@ },

"devDependencies": {
"mocha": "1.3.x",
"mocha": "1.8.x",
"should": "1.1.x",
"raw-loader": "0.2.x",
"jade-loader": "0.2.x"
"raw-loader": "0.5.x",
"jade-loader": "0.5.x"
},

@@ -35,4 +37,3 @@ "main": "lib/require",

"test": "node node_modules/mocha/bin/_mocha --reporter spec"
},
"license": "MIT"
}
}

@@ -5,7 +5,7 @@ # enhanced-require

* [loader support](https://github.com/sokra/modules-webpack/wiki/Loader-Specification)
* `require.ensure`
* AMD `require`, `define` (from require.js)
* `require.context`
* [Hot Code Replacement](https://github.com/webpack/enhanced-require/wiki/HCR-Spec)
* [loader support](https://github.com/webpack/docs/wiki/loaders)
* [`require.ensure`](https://github.com/webpack/docs/wiki/require.ensure)
* [AMD](https://github.com/webpack/docs/wiki/amd) `require`, `define` (from require.js)
* [`require.context`](https://github.com/webpack/docs/wiki/require.context)
* [Hot Code Replacement](https://github.com/webpack/docs/wiki/hot-code-replacement)
* module substitutions for mocking

@@ -15,131 +15,4 @@

## Create a enhanced require function
[documentation](https://github.com/webpack/docs/wiki)
``` javascript
var myRequire = require("enhanced-require")(module, {
// options
recursive: true // enable for all modules recursivly
// This replaces the original require function in loaded modules
});
// startup your application
myRequire("./startup");
```
## Usage
Than you can use them:
``` javascript
// use loaders
var fileContent = require("raw!"+__filename);
// use loaders automatically
var template = require("./my-template.jade");
var html = template({content: fileContent});
// use require.context
var directoryRequire = require.context("raw!./subdir");
var txtFile = directoryRequire("./aFile.txt");
// use require.ensure
require.ensure(["./someFile.js"], function(require) {
var someFile = require("./someFile.js");
});
// use AMD define
require.define(["./aDep"], function(aDep) {
aDep.run();
});
// use AMD require
require(["./bDep"], function(bDep) {
bDep.doSomething();
});
```
## Hot Code Replacement
``` javascript
require("enhanced-require")(module, {
recursive: true, // enable for all modules
hot: true, // enable hot code replacement
watch: true // watch for changes
})("./startup");
```
For hot code reloading you need to follow the [hot code reloading spec](https://github.com/webpack/enhanced-require/wiki/HCR-Spec).
## Testing/Mocking
``` javascript
var er = require("enhanced-require");
it("should read the config option", function(done) {
var subject = er(module, {
recursive: true,
substitutions: {
// specify the exports of a module directly
"../lib/config.json": {
"test-option": { value: 1234 }
}
},
substitutionFactories: {
// specify lazy generated exports of a module
"../lib/otherConfig.json": function(require) {
// export the same object as "config.json"
return require("../lib/config.json");
}
}
})("../lib/subject");
var result = subject.getConfigOption("test-option");
should.exist(result);
result.should.be.eql({ value: 1234 });
});
```
## Options
``` javascript
{
recursive: false,
// replace require function in required modules with enhanced require method
resolve: {
// ...
// see enhanced-resolve
// https://github.com/webpack/enhanced-resolve
},
substitutions: {},
substitutionFactories: {},
// See above
// Replace modules with mocks
// keys are resolved and have to exist
amd: {},
// The require.amd object
enhanced: {},
// The require.enhanced object
loader: {},
// additional stuff in the loaderContext
hot: false,
// enable hot code replacement
watch: false,
// Watch for file changes and issue hot replacement
watchDelay: 400,
// Time to summarize changes for watching
}
```
## Future Plans
* cli tool
## License

@@ -146,0 +19,0 @@

@@ -15,4 +15,5 @@ var should = require("should");

clean(req.cache);
clean(req.contentCache);
clean(req.sourceCache);
clean(req.preCache);
req.__root.fileSystem.purge();
req.__root.syncFileSystem.purge();
});

@@ -19,0 +20,0 @@

@@ -27,4 +27,4 @@ var should = require("should");

outerLoaded.loader.should.have.property("request").be.eql(req.resolve("./fixtures/loader!./fixtures/outer"));
outerLoaded.loader.should.have.property("context").be.eql(__dirname);
outerLoaded.loader.should.have.property("filenames").be.eql([req.resolve("./fixtures/outer")]);
outerLoaded.loader.should.have.property("context").be.eql(path.join(__dirname, "fixtures"));
outerLoaded.loader.should.have.property("resource").be.eql(req.resolve("./fixtures/outer"));
});

@@ -38,4 +38,4 @@

loaded.loader.should.have.property("request").be.eql(req.resolve("./fixtures/loader!"));
loaded.loader.should.have.property("context").be.eql(__dirname);
loaded.loader.should.have.property("filenames").be.eql([]);
loaded.loader.should.have.property("context").be.eql(null);
loaded.loader.should.have.property("resource").be.eql("");
});

@@ -51,6 +51,8 @@

loaded.loader.should.have.property("query").be.eql("?query2");
loaded.loader.should.have.property("context").be.eql(__dirname);
loaded.loader.should.have.property("filenames").be.eql([]);
loaded.loader.should.have.property("context").be.eql(null);
loaded.loader.should.have.property("resourcePath").be.eql("");
loaded.loader.should.have.property("resource").be.eql("?query1");
loaded.loader.should.have.property("resourceQuery").be.eql("?query1");
});
});

@@ -7,3 +7,3 @@ var should = require("should");

var req = reqFactory(module);
beforeEach(function() {

@@ -18,5 +18,5 @@ function clean(obj) {

});
it("should form a require function", function() {
should.exist(req);

@@ -29,7 +29,6 @@ req.should.be.a("function");

req.should.have.property("cache").be.a("object");
req.should.have.property("contentCache").be.a("object");
req.should.have.property("sourceCache").be.a("object");
req.should.have.property("preCache").be.a("object");
});
it("should require a file sync", function() {

@@ -41,3 +40,3 @@ var file = req("./fixtures/file.js");

});
it("should require.resolve a file sync", function() {

@@ -49,3 +48,3 @@ var file = req.resolve("./fixtures/file.js");

});
it("should let the user clean the cache", function() {

@@ -59,3 +58,3 @@ var fileId = req.resolve("./fixtures/file");

});
it("should be able to require in a required module", function() {

@@ -65,3 +64,3 @@ var outer = req("./fixtures/outer");

});
it("should fill free vars in required module", function() {

@@ -79,5 +78,5 @@ var freeVars = req("./fixtures/freeVars");

.be.a("object").and.have.property("exports").be.equal(freeVars.exports);
});
it("should handle native modules", function() {

@@ -88,3 +87,3 @@ var fs = req("fs");

});
});
module.exports = 1;
module.exports = { two: require("./circular2") };
module.exports = 2;
module.exports = { one: require("./circular1") };
exports.module = module;
exports.a = require("./graph/a.js");
exports.b = require("./graph/b.js");
module.exports = module;
require("./b");

@@ -0,0 +0,0 @@ var list = [];

@@ -0,0 +0,0 @@ var list = [];

@@ -0,0 +0,0 @@ var list = [];

@@ -8,2 +8,4 @@ var should = require("should");

this.timeout(10000);
var counterValuePath = path.join(__dirname, "fixtures", "hot", "counter-value.js");

@@ -27,4 +29,3 @@

var req = reqFactory(module, {
hot: true,
recursive: true
hot: true
});

@@ -64,4 +65,3 @@

var req = reqFactory(module, {
hot: true,
recursive: true
hot: true
});

@@ -101,15 +101,16 @@

var req = reqFactory(module, {
hot: true,
recursive: true
hot: true
});
var fail = req("./fixtures/hot/not-accepted");
writeCounter(2);
req.hot.check(function(err, updatedModules) {
should.exist(err);
should.not.exist(updatedModules);
err.should.be.instanceOf(Error);
/bubbling/.test(err.toString()).should.be.ok;
done();
});
setTimeout(function() {
writeCounter(2);
req.hot.check(function(err, updatedModules) {
should.exist(err);
should.not.exist(updatedModules);
err.should.be.instanceOf(Error);
/bubbling/.test(err.toString()).should.be.ok;
done();
});
}, 1000);
});

@@ -119,4 +120,3 @@

var req = reqFactory(module, {
hot: true,
recursive: true
hot: true
});

@@ -157,5 +157,4 @@

hot: true,
recursive: true,
watch: true,
watchDelay: 10
watchDelay: 200
});

@@ -174,9 +173,12 @@

setTimeout(function() {
list.should.be.eql([1, -1, 2, -2, 3]);
req.hot.stop();
done();
writeCounter(4);
setTimeout(function() {
list.should.be.eql([1, -1, 2, -2, 4]);
req.hot.stop();
done();
}, 300);
}, 100);
}, 100);
}, 100);
}, 100);
}, 1000);
}, 300);
}, 1000);
});

@@ -187,3 +189,2 @@

hot: true,
recursive: true,
watch: true,

@@ -227,4 +228,2 @@ watchDelay: 10

});
});

@@ -6,5 +6,3 @@ var should = require("should");

describe("module-graph", function() {
var req = reqFactory(module, {
recursive: true
});
var req = reqFactory(module);

@@ -11,0 +9,0 @@ var graphModule = req("./fixtures/graph");

@@ -14,4 +14,5 @@ var should = require("should");

clean(req.cache);
clean(req.contentCache);
clean(req.sourceCache);
clean(req.preCache);
req.__root.fileSystem.purge();
req.__root.syncFileSystem.purge();
});

@@ -23,6 +24,7 @@

req.ensure(["./fixtures/file", "./fixtures/inner"], function(req2) {
req.ensure(["./fixtures/file", "./fixtures/inner"], function(req2, err) {
if(err) throw err;
should.exist(req2);
req2.should.be.a("function");
should.exist(req2.sourceCache[id]);
should.exist(req2.preCache[id]);
var file = req2(id);

@@ -39,7 +41,9 @@ file.should.be.eql({value: "file"});

var async = false;
req.ensure(["./fixtures/file", "./fixtures/file?1"], function(req2, err) {
if(err) throw err;
should.exist(req2);
req2.should.be.a("function");
should.exist(req2.sourceCache[id]);
should.exist(req2.sourceCache[id+"?1"]);
should.exist(req2.preCache[id]);
should.exist(req2.preCache[id+"?1"]);
var file = req2(id);

@@ -49,4 +53,6 @@ var file1 = req2(id+"?1");

file1.should.be.eql({value: "file"});
async.should.be.eql(true);
done();
});
async = true;

@@ -53,0 +59,0 @@ });

@@ -40,3 +40,3 @@ var should = require("should");

context("./notExists.js");
}).should.throw(/Module ".*?" not found/);
}).should.throw(/notExists\.js/);
});

@@ -57,3 +57,5 @@

keys.should.be.eql([
"./a",
"./a.js",
"./b",
"./b.js"

@@ -70,3 +72,5 @@ ]);

keys.should.be.eql([
"./a",
"./a.js",
"./b",
"./b.js"

@@ -76,2 +80,42 @@ ]);

it("should be able to use context.keys() with RegExp", function() {
var context = req.context("./fixtures/graph", true, /^\.\/a/);
should.exist(context.keys);
context.keys.should.be.a("function");
var keys = context.keys();
should.exist(keys);
keys.should.be.eql([
"./a",
"./a.js"
]);
});
it("should be able to use context.keys() with RegExp, recursive = true", function() {
var context = req.context("./fixtures", true, /^\.\/graph/);
should.exist(context.keys);
context.keys.should.be.a("function");
var keys = context.keys();
should.exist(keys);
keys.should.be.eql([
"./graph",
"./graph.js",
"./graph/a",
"./graph/a.js",
"./graph/b",
"./graph/b.js"
]);
});
it("should be able to use context.keys() with RegExp, recursive = false", function() {
var context = req.context("./fixtures", false, /^\.\/graph/);
should.exist(context.keys);
context.keys.should.be.a("function");
var keys = context.keys();
should.exist(keys);
keys.should.be.eql([
"./graph",
"./graph.js"
]);
});
});

@@ -54,5 +54,3 @@ var should = require("should");

it("should be able to combine recursive with a own cache", function() {
var req = reqFactory(module, {
recursive: true
});
var req = reqFactory(module);

@@ -59,0 +57,0 @@ var a = req("./fixtures/recursiveRandom2");

@@ -5,5 +5,3 @@ var should = require("should");

describe("require-recusive", function() {
var req = reqFactory(module, {
recursive: true
});
var req = reqFactory(module);

@@ -10,0 +8,0 @@ beforeEach(function() {

@@ -6,3 +6,2 @@ var should = require("should");

var req = reqFactory(module, {
recursive: true,
substitutions: {

@@ -9,0 +8,0 @@ "./fixtures/recursive1": "substitution1",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc