public Module(string id, IVirtualPath virtualPath, Module parent, IModuleLoader loader) { Evaluator = loader.Evaluator; Id = id; Parent = parent; Loader = loader; VirtualPath = virtualPath; parent?.Children?.Add(this); Loaded = false; Children = new List<Module>(); RequireFunction = new RequireFunction(Evaluator, loader, this); }
public IVirtualPath Resolve(string path, Module parent) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Invalid file path."); } string combinedPath; if (path.StartsWith("/")) { combinedPath = path.Substring(1); } else if (path.Length > 1) { var start = path.Substring(0, 2); if (start == "./" || start == "../") { var parentDirectory = Path.GetDirectoryName(parent.FileName); if (parentDirectory == null) { return null; } combinedPath = Path.Combine(parentDirectory, path); } else { combinedPath = Path.Combine(ModulesPath, path); } } else { combinedPath = Path.Combine(ModulesPath, path); } var result = SearchFile(combinedPath) ?? SearchDirectory(combinedPath); if (result == null) { return null; } return new FilePath(result); }
public Module Load(string request, Module parent, bool isMain) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (parent != null && parent.Loader != this) { throw new InvalidOperationException("Parent module is initialized from a different loader."); } Module module; if (NativeModules.TryGetValue(request, out module)) { return module; } var virtualPath = PathResolver.Resolve(request, parent); var identifier = virtualPath?.Identifier; if (identifier == null) { throw new InvalidOperationException($"Module '{request}' not found."); } if (LoadedModules.TryGetValue(identifier, out module)) { return module; } module = new Module(identifier, virtualPath, parent, this); var oldMain = MainModule; if (isMain) { MainModule = module; } var extension = virtualPath.ResolveExtension(); IModuleCompiler compiler; if (!Compilers.TryGetValue(extension, out compiler)) { throw new InvalidOperationException($"Invalid file extension {extension}."); } LoadedModules[identifier] = module; try { compiler.Compile(module); } catch { LoadedModules.Remove(identifier); if (isMain) { MainModule = oldMain; } throw; } return module; }
public RequireFunction(IScriptEvaluator scriptEvaluator, IModuleLoader loader, Module module) { this.scriptEvaluator = scriptEvaluator; Loader = loader; Module = module; }