Example #1
0
function legacyGetDefaultComponentModule(dirname) {
    var filename;
    var legacy = true;

    if ((filename = resolveFrom(dirname, "./widget"))) {
        return {
            filename,
            requirePath: "./widget",
            legacy
        };
    } else if ((filename = resolveFrom(dirname, "./component"))) {
        return {
            filename,
            requirePath: "./component",
            legacy
        };
    } else if ((filename = resolveFrom(dirname, "./"))) {
        return {
            filename,
            requirePath: "./",
            legacy
        };
    } else {
        return null;
    }
}
Example #2
0
 getDefaultWidgetModule() {
     var dirname = this.dirname;
     if (resolveFrom(dirname, './component')) {
         return './component';
     } else if (resolveFrom(dirname, './widget')) {
         return './widget';
     } else if (resolveFrom(dirname, './')) {
         return './';
     } else {
         return null;
     }
 }
Example #3
0
  constructor(opts: ExampleOpts) {
    this.filePath = opts.filePath;
    this.relativePath = path.relative(opts.cwd, this.filePath);
    this.relativePathOut = this.relativePath
      .split(path.sep)
      .map(part => part.replace(constants.EXAMPLE_PATH_PART_NUMBER, '$2'))
      .join(path.sep);

    this.dirName = path.dirname(this.relativePath);
    this.dirNameOut = path.dirname(this.relativePathOut);

    this.baseName = basename(this.relativePath);
    this.baseNameOut = basename(this.relativePathOut);

    this.tempDir = path.join(opts.tempDir, this.dirNameOut);
    this.htmlPath = path.join(this.tempDir, this.baseNameOut + '.html');
    this.txtPath = path.join(this.tempDir, this.baseNameOut + '.txt');
    this.jsPath = path.join(this.tempDir, this.baseNameOut + '.js');

    let currentDirName = path.basename(opts.cwd);
    let exampleDirName = this.dirNameOut.replace(path.sep, '/');

    this.title = `${currentDirName}/${exampleDirName}/${this.baseNameOut}`;

    let reactImport = resolveFrom(this.filePath, 'react');
    let reactDomImport = resolveFrom(this.filePath, 'react-dom');

    let relativeJsImport = path.relative(this.jsPath, this.filePath);
    let relativeReactImport = path.relative(this.jsPath, reactImport);
    let relativeReactDomImport = path.relative(this.jsPath, reactDomImport);

    this.htmlContent = stripIndent(`
      <!doctype html>
      <html>
      <head>
        <meta charset="utf-8">
        <title>${this.title}</title>
      </head>
      <body>
        <div id="root"></div>
        <script type="text/javascript" src="./${this.baseNameOut}.js"></script>
      </body>
      </html>
    `).trim();

    this.jsContent = stripIndent(`
      import React from "${relativeReactImport}";
      import { render } from "${relativeReactDomImport}";
      import Example from "${relativeJsImport}";

      render(React.createElement(Example), document.getElementById("root"));
    `).trim();
  }
Example #4
0
module.exports = function (cwd, debug, browserAdapterPath) {
	var avaBundler = browserify({debug: debug, basedir: cwd, fullPaths: true});
	var processAdapterPath = resolveFrom(cwd, 'ava/lib/process-adapter');
	var avaPath = resolveFrom(cwd, 'ava');
	avaBundler.avaProcessAdapterPath = processAdapterPath;

	avaBundler.require(processAdapterPath);

	avaBundler.require(avaPath);

	avaBundler.transform(replaceTransform(processAdapterPath, browserAdapterPath), {global: true});

	return avaBundler;
};
Example #5
0
	beforeEach(function () {
		process.env = {};
		Object.defineProperty(process, 'platform', {value: 'win32'});
		// since chalk internally modifies ansiStyles.blue.open, ansi-styles needs
		// to be removed from the require cache for require-uncached to work
		delete require.cache[resolveFrom(__dirname, 'ansi-styles')];
	});
module.exports = function urlResolver(url, from, lassoContext, callback) {
    if (url.charAt(0) === '/' && url.charAt(1) !== '/') {
        var rootDir = raptorModulesUtil.getProjectRootDir();
        return callback(null, nodePath.join(rootDir, url));
    } else if (url.startsWith(REQUIRE_PREFIX)) {
        var requirePath = url.substring(REQUIRE_PREFIX.length).trim();

        var query;
        var pos = requirePath.indexOf('?');
        if (pos !== -1) {
            query = requirePath.substring(pos + 1);
            requirePath = requirePath = requirePath.substring(0, pos);
        }

        requirePath = resolveFrom(from, requirePath);

        if (query) {
            requirePath += '?' + query;
        }

        return callback(null, requirePath);
    } else {
        // Relative path such as "./foo.png" or "foo.png"
        return callback(null, nodePath.resolve(from, url));
    }

    callback(null, url);
};
Example #7
0
		var configs = opts.extends.map(function (name) {
			if (name.indexOf('eslint-config-') === -1) {
				name = 'eslint-config-' + name;
			}

			return resolveFrom(opts.cwd, name);
		});
Example #8
0
module.exports = function codeGenerator(el, codegen) {
    let argument = el.argument;
    if (!argument) {
        return;
    }

    let builder = codegen.builder;
    let pathExpression = builder.parseExpression(argument);
    if (pathExpression.type !== 'Literal' || typeof pathExpression.value !== 'string') {
        codegen.addError('Argument to the <include-html> tag should be a string value: <include-html("./foo.txt")/>');
        return;
    }

    var path = pathExpression.value;
    var dirname = codegen.context.dirname;
    try {
        path = resolveFrom(dirname, path);
    } catch (e) {
        codegen.addError('File not found: ' + path);
        return;
    }

    var txt = fs.readFileSync(path, { encoding: 'utf8' });
    return builder.text(builder.literal(txt), false /* do not escape since this is HTML*/);
};
Example #9
0
function getModulePath(basedir, lookup) {
  const path = resolveFrom(basedir, lookup)
  if (path) return path
  throw configurationError(
    `Could not find "${lookup}". Do you need a \`configBasedir\`?`
  )
}
Example #10
0
var clear = module.exports = function (moduleId) {
	if (typeof moduleId !== 'string') {
		throw new TypeError('Expected a string');
	}

	delete require.cache[resolveFrom(path.dirname(callerPath()), moduleId)];
};
  function getCrossImportPackage(id) {
    const resolved = resolveFrom(dirname, id);
    // Exclude modules that are not found or not ours.
    if (resolved == null || resolved.includes('/node_modules/')) {
      return null;
    }
    const resolvedPackage = getPackage(resolved);
    // Requiring anything within our own package is ok.
    if (resolvedPackage.__dirname === ownPackage.__dirname) {
      return null;
    }
    // An apm package requiring a whitelisted package is ok.
    if (ownPackage.nuclide &&
        ownPackage.nuclide.testRunner === 'apm' &&
        whitelist.has(resolvedPackage.name)) {
      return null;
    }
    // Nothing can require into an Atom package
    if (resolvedPackage.nuclide &&
        resolvedPackage.nuclide.packageType === 'Atom') {
      return {type: 'NO_ATOM', pkg: resolvedPackage};
    }
    // npm packages can only require other npm packages.
    if (ownPackage.nuclide &&
        ownPackage.nuclide.testRunner === 'npm' &&
        resolvedPackage.nuclide &&
        resolvedPackage.nuclide.testRunner === 'apm') {
      return {type: 'NO_NPM_TO_APM', pkg: resolvedPackage};
    }

    return null;
  }
 function checkDependency(node, dep) {
   // Relative imports must be within the root.
   if (dep[0] === '.') {
     const depPath = path.join(dirname, dep);
     if (!depPath.startsWith(moduleDir + path.sep)) {
       context.report({
         node,
         message: 'modules/ cannot have external relative dependencies.',
       });
     }
     return;
   }
   // Built-in modules.
   if (ATOM_BUILTIN_PACKAGES.has(dep) || resolveFrom(moduleDir, dep) === dep) {
     return;
   }
   const depName = dep.split('/')[0];
   if (!Object.hasOwnProperty.call(modulePkg.dependencies, depName)) {
     context.report({
       node,
       data: {dep: depName, pkg: modulePkg.name},
       message: 'Dependency "{{dep}}" must be declared in module "{{pkg}}".',
     });
   }
 }
Example #13
0
export default function (
  basedir: string,
  lookup: string,
): string {
  // First try to resolve from the provided directory,
  // then try to resolve from process.cwd.
  let path = resolveFrom(basedir, lookup)
  if (!path) {
    path = resolveFrom(process.cwd(), lookup)
  }
  if (!path) {
    throw configurationError(
      `Could not find "${lookup}". Do you need a \`configBasedir\`?`
    )
  }
  return path
}
Example #14
0
function findMain(dir) {
    try {
        return resolveFrom(dir, './');
    } catch(e) {
        return null;
    }

}
Example #15
0
        ? this.config.plugins.map(p => {
            if (typeof p === 'string') {
              p = { resolve: p }
            }

            p.resolve = resolveFrom(this.configDir, p.resolve)
            return p
          })
Example #16
0
    taglibImports: function(imports) {
        // The "taglib-imports" property allows another taglib to be imported
        // into this taglib so that the tags defined in the imported taglib
        // will be part of this taglib.
        //
        // NOTE: If a taglib import refers to a package.json file then we read
        //       the package.json file and automatically import *all* of the
        //       taglibs from the installed modules found in the "dependencies"
        //       section
        var taglib = this.taglib;
        var dirname = this.dirname;
        var importPath;
        var resolveFrom = require('resolve-from');

        if (imports && Array.isArray(imports)) {
            for (var i=0; i<imports.length; i++) {
                var curImport = imports[i];
                if (typeof curImport === 'string') {
                    var basename = nodePath.basename(curImport);
                    if (basename === 'package.json') {
                        var packagePath = resolve(curImport, dirname);
                        var pkg = require(packagePath);
                        var dependencies = pkg.dependencies;
                        if (dependencies) {
                            var dependencyNames = Object.keys(dependencies);
                            for (var j=0; j<dependencyNames.length; j++) {
                                var dependencyName = dependencyNames[j];

                                try {
                                    importPath = resolveFrom(dirname, dependencyName + '/marko-taglib.json');
                                } catch(e) {}

                                if (importPath) {
                                    taglib.addImport(importPath);
                                }
                            }
                        }
                    } else {
                        importPath = resolveFrom(dirname, curImport);
                        taglib.addImport(importPath);
                    }
                }
            }
        }
    },
Example #17
0
module.exports = function getRequirePath(target, context) {
    var relPath = target === 'marko-widgets' ?
        './' :
        '.' + target.substring(target.indexOf('/'));

    var resolvedTarget = resolveFrom(markoWidgetsDir, relPath);
    var requirePath = context.getRequirePath(resolvedTarget);
    return requirePath;
};
Example #18
0
 getAllDependencyNames(rootPkg).forEach((name) => {
     if (!excludedPackages[name]) {
         let taglibPath = resolveFrom(rootPkg.__dirname, name + '/marko.json');
         if (taglibPath) {
             var taglib = taglibLoader.load(taglibPath);
             helper.addTaglib(taglib);
         }
     }
 });
Example #19
0
function buildConfig(opts) {
	var config = deepAssign(
		emptyOptions(),
		DEFAULT_CONFIG,
		opts
	);

	if (opts.space) {
		var spaces = typeof opts.space === 'number' ? opts.space : 2;
		config.rules.indent = [2, spaces, {SwitchCase: 1}];

		// only apply if the user has the React plugin
		if (opts.cwd && resolveFrom(opts.cwd, 'eslint-plugin-react')) {
			config.plugins = config.plugins.concat('react');
			config.rules['react/jsx-indent-props'] = [2, spaces];
			config.rules['react/jsx-indent'] = [2, spaces];
		}
	}

	if (opts.semicolon === false) {
		config.rules.semi = [2, 'never'];
		config.rules['semi-spacing'] = [2, {
			before: false,
			after: true
		}];
	}

	if (opts.esnext) {
		config.baseConfig.extends = ['xo/esnext', path.join(__dirname, 'config/plugins.js')];
	}

	if (opts.rules) {
		objectAssign(config.rules, opts.rules);
	}

	if (opts.extends && opts.extends.length > 0) {
		// TODO: this logic needs to be improved, preferably use the same code as ESLint
		// user's configs must be resolved to their absolute paths
		var configs = opts.extends.map(function (name) {
			// don't do anything if it's a filepath
			if (pathExists.sync(name)) {
				return name;
			}

			if (name.indexOf('eslint-config-') === -1) {
				name = 'eslint-config-' + name;
			}

			return resolveFrom(opts.cwd, name);
		});

		config.baseConfig.extends = config.baseConfig.extends.concat(configs);
	}

	return config;
}
Example #20
0
exports.loadModule = function(root, path) {
  if (rRelativePath.test(path)) {
    path = pathUtil.join(root, path);
  } else if (pathUtil.isAbsolute(path)) {
    path = path;
  } else {
    path = resolveFrom(root, path);
  }
  return require(path);
};
Example #21
0
 this.require.forEach(function (r) {
   // first attempt to require the module relative to
   // the directory being instrumented.
   var p = resolveFrom(_this.cwd, r)
   if (p) {
     require(p)
     return
   }
   // now try other locations, .e.g, the nyc node_modules folder.
   require(r)
 })
Example #22
0
  loadPlugins(projectDir, config) {

    let plugins = config.plugins;
    let options = {};
    this.config.pluginImports = [];

    for (let plugin in plugins) {

      let val = plugins[plugin];

      if (!val) {

        continue;
      }

      let found =
        this.findFile(`${plugin}.js`, projectDir, path.resolve(this.distDir, 'plugin')) ||
        resolveFrom(projectDir, `tern-${plugin}`)
        ;

      if (!found) {

        try {

          found = require.resolve(`tern-${plugin}`);

        } catch (e) {

          console.warn(e);
        }
      }

      if (!found) {

        try {

          found = require.resolve(`${this.projectDir}/node_modules/tern-${plugin}`);

        } catch (e) {

          atom.notifications.addError(`Failed to find plugin ${plugin}\n`, {

            dismissable: true
          });
          continue;
        }
      }

      this.config.pluginImports.push(found);
      options[path.basename(plugin)] = val;
    }

    return options;
  }
  function getCrossImportPackage(id) {
    // npm packages can't require Atom builtins.
    if (ATOM_BUILTIN_PACKAGES.has(id)) {
      if (isPureNode) {
        return {type: 'NO_NPM_TO_ATOM_BUILTIN', name: id};
      } else {
        return null;
      }
    }

    if (ATOM_IDE_PACKAGES.has(id)) {
      if (isPureNode) {
        return {type: 'NO_NPM_TO_ATOM_UI_PACKAGES', name: id};
      } else {
        return null;
      }
    }

    const resolved = resolveFrom(dirname, id);
    // Exclude modules that are not found, builtins, or not ours.
    if (
      resolved == null ||
      resolved === id ||
      resolved.includes('/node_modules/')
    ) {
      return null;
    }
    const resolvedPackage = getPackage(resolved);
    // Requiring anything within our own package is ok.
    if (resolvedPackage.__dirname === ownPackage.__dirname) {
      return null;
    }
    // An apm package requiring a whitelisted package is ok.
    if (ownPackage.nuclide &&
        ownPackage.nuclide.testRunner === 'apm' &&
        whitelist.has(resolvedPackage.name)) {
      return null;
    }
    // Nothing can require into an Atom package
    if (resolvedPackage.nuclide &&
        resolvedPackage.nuclide.packageType === 'Atom') {
      return {type: 'NO_ATOM', name: resolvedPackage.name};
    }
    // npm packages can only require other npm packages.
    if (ownPackage.nuclide &&
        ownPackage.nuclide.testRunner === 'npm' &&
        resolvedPackage.nuclide &&
        resolvedPackage.nuclide.testRunner === 'apm') {
      return {type: 'NO_NPM_TO_APM', name: resolvedPackage.name};
    }

    return null;
  }
Example #24
0
        getAllDependencyNames(rootPkg).forEach((name) => {
            let taglibPath;
            try {
                taglibPath = resolveFrom(rootPkg.__dirname, name + '/marko.json');
            } catch(e) {
                // The installed dependency does not export a taglib... skip it
                return;
            }

            var taglib = taglibLoader.load(taglibPath);
            helper.addTaglib(taglib);
        });
Example #25
0
module.exports = function getRequirePath(target, context) {
    if (target === 'marko' || target.startsWith('marko/')) {
        return target;
    }

    var resolvedTarget = resolveFrom(context.dirname, target);
    if (!resolvedTarget) {
        throw new Error('Unable to resolve "' + target + '" from "' + context.dirname + '"');
    }
    var requirePath = context.getRequirePath(resolvedTarget);
    return requirePath;
};
Example #26
0
		var configs = opts.extends.map(function (name) {
			// don't do anything if it's a filepath
			if (pathExists.sync(name)) {
				return name;
			}

			if (name.indexOf('eslint-config-') === -1) {
				name = 'eslint-config-' + name;
			}

			return resolveFrom(opts.cwd, name);
		});
Example #27
0
  _parseFile(fileName: string, fileType: FileType, source: string): void {
    const parser = new FileParser(fileName, fileType, this._defs);
    const imports = parser.parse(source);
    for (const imp of imports) {
      const resolvedFrom = resolveFrom(path.dirname(fileName), imp);

      if (!this._filesSeen.has(resolvedFrom)) {
        this._filesSeen.add(resolvedFrom);
        this._filesTodo.push(resolvedFrom);
      }
    }
  }
Example #28
0
var require_optional = function(name, options) {
  options = options || {};
  options.strict = typeof options.strict == 'boolean' ? options.strict : true;

  var res = find_package_json_with_name(name)
  var object = res.object;
  var parts = res.parts;

  // Unpack the expected version
  var expectedVersions = object.peerOptionalDependencies[parts[0]];
  // The resolved package
  var moduleEntry = undefined;
  // Module file
  var moduleEntryFile = name;

  try {
    // Validate if it's possible to read the module
    moduleEntry = require(moduleEntryFile);
  } catch(err) {
    // Attempt to resolve in top level package
    try {
      // Get the module entry file
      moduleEntryFile = resolveFrom(process.cwd(), name);
      if(moduleEntryFile == null) return undefined;
      // Attempt to resolve the module
      moduleEntry = require(moduleEntryFile);
    } catch(err) {
      if(err.code === 'MODULE_NOT_FOUND') return undefined;
    }
  }

  // Resolve the location of the module's package.json file
  var location = find_package_json(require.resolve(moduleEntryFile));
  if(!location) {
    throw new Error('package.json can not be located');
  }

  // Read the module file
  var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location)));
  // Get the version
  var version = dependentOnModule.version;
  // Validate if the found module satisfies the version id
  if(semver.satisfies(version, expectedVersions) == false
    && options.strict) {
      var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions));
      error.code = 'OPTIONAL_MODULE_NOT_FOUND';
      throw error;
  }

  // Satifies the module requirement
  return moduleEntry;
}
Example #29
0
module.exports = function (moduleId) {
	if (typeof moduleId !== 'string') {
		throw new TypeError('Expected a string');
	}

	var filePath = resolveFrom(path.dirname(callerPath()), moduleId);
	var tmp = require.cache[filePath];
	require.uncache(filePath);
	var ret = require(filePath);
	require.cache[filePath] = tmp;

	return ret;
};
Example #30
0
/**
 * This function provides provides an implementation that is used by
 * Dependency.prototype.resolvePath and Dependency.prototype.requireResolvePath.
 * These functions will now use the same machenism for resolving paths which
 * will work as follows:
 *
 * If path starts with "." then resolve as relative path.
 * If path starts with "/" then path is absolute and has been resolved already.
 * Otherwise, try to resolve path using NodeJS module search path convention
 * and if that fails fallback to using relative path resolution.
 */
function Dependency_resolvePath(path, from) {
    // NOTE: "this" is the Dependency
    var dependency = this;

    if (!from) {
        from = dependency.__dirname;
    }

    var firstChar = path.charAt(0);
    if (firstChar === '.') {
        // path is relative to dependency directory
        return nodePath.resolve(from, path);
    } else if (isAbsolute(path)) {
        // path is absolute
        return path;
    } else {
        // path should be resolved using require.resolve() convention first
        // and attempt relative path resolution if that fails
        try {
            return resolveFrom(from, path);
        } catch(e) {
            // Not bothering to check error code since serverResolveRequire
            // should only throw error for one reason which is "module not found".
            // if (e.code === 'MODULE_NOT_FOUND') {
            //
            // }
            var resolvedPath = nodePath.resolve(from, path);

            // Since the path looked like it was for a module we should check
            // to see if the fallback technique actually found a file. If file
            // does not exist for fallback path, then we'll report an error
            // that the module does not exist by re-throwing the original error.
            if (cachingFs.existsSync(resolvedPath)) {
                // Fallback technique found the path.
                // We might want to log something here to suggest that relative
                // paths be prefixed with "." to avoid the extra work of trying to
                // resolve path using NodeJS module search path.
            } else {
                // Path is not a module or resolved path.
                // Since the path did not start with a "." let's
                // throw the error that we caught when trying to
                // resolve as module
                throw new Error('Failed to resolve path "' + path + '". Target file does not exist. Started search from directory "' + from + '".');
            }

            // We were able to r
            return resolvedPath;
        }
    }
}