From 0684c08a986dec48773211085e076c3a5a8521c3 Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Thu, 9 Nov 2023 22:04:32 +0000 Subject: [PATCH 01/15] feat: Use enhanced-resolve for imports --- lib/converted-esm/import-meta-resolve.js | 1274 ---------------------- lib/rules/no-hide-core-modules.js | 48 +- lib/util/import-target.js | 88 +- package.json | 2 +- scripts/convert-pure-esm-to-cjs.js | 6 - tests/lib/rules/no-missing-require.js | 11 +- tests/lib/rules/no-unpublished-import.js | 6 - 7 files changed, 60 insertions(+), 1375 deletions(-) delete mode 100644 lib/converted-esm/import-meta-resolve.js delete mode 100644 scripts/convert-pure-esm-to-cjs.js diff --git a/lib/converted-esm/import-meta-resolve.js b/lib/converted-esm/import-meta-resolve.js deleted file mode 100644 index d79301de..00000000 --- a/lib/converted-esm/import-meta-resolve.js +++ /dev/null @@ -1,1274 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// node_modules/import-meta-resolve/lib/resolve.js -var resolve_exports = {}; -__export(resolve_exports, { - defaultResolve: () => defaultResolve, - moduleResolve: () => moduleResolve -}); -module.exports = __toCommonJS(resolve_exports); -var import_node_assert2 = __toESM(require("node:assert"), 1); -var import_node_fs2 = require("node:fs"); -var import_node_process2 = __toESM(require("node:process"), 1); -var import_node_url3 = require("node:url"); -var import_node_path3 = __toESM(require("node:path"), 1); -var import_node_module = require("node:module"); - -// node_modules/import-meta-resolve/lib/get-format.js -var import_node_path2 = __toESM(require("node:path"), 1); -var import_node_url2 = require("node:url"); - -// node_modules/import-meta-resolve/lib/package-config.js -var import_node_url = require("node:url"); - -// node_modules/import-meta-resolve/lib/errors.js -var import_node_v8 = __toESM(require("node:v8"), 1); -var import_node_process = __toESM(require("node:process"), 1); -var import_node_assert = __toESM(require("node:assert"), 1); -var import_node_util = require("node:util"); -var isWindows = import_node_process.default.platform === "win32"; -var own = {}.hasOwnProperty; -var codes = {}; -function formatList(array, type = "and") { - return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`; -} -var messages = /* @__PURE__ */ new Map(); -var nodeInternalPrefix = "__node_internal_"; -var userStackTraceLimit; -codes.ERR_INVALID_MODULE_SPECIFIER = createError( - "ERR_INVALID_MODULE_SPECIFIER", - /** - * @param {string} request - * @param {string} reason - * @param {string} [base] - */ - (request, reason, base = void 0) => { - return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`; - }, - TypeError -); -codes.ERR_INVALID_PACKAGE_CONFIG = createError( - "ERR_INVALID_PACKAGE_CONFIG", - /** - * @param {string} path - * @param {string} [base] - * @param {string} [message] - */ - (path4, base, message) => { - return `Invalid package config ${path4}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`; - }, - Error -); -codes.ERR_INVALID_PACKAGE_TARGET = createError( - "ERR_INVALID_PACKAGE_TARGET", - /** - * @param {string} pkgPath - * @param {string} key - * @param {unknown} target - * @param {boolean} [isImport=false] - * @param {string} [base] - */ - (pkgPath, key, target, isImport = false, base = void 0) => { - const relError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./"); - if (key === ".") { - (0, import_node_assert.default)(isImport === false); - return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`; - } - return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify( - target - )} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`; - }, - Error -); -codes.ERR_MODULE_NOT_FOUND = createError( - "ERR_MODULE_NOT_FOUND", - /** - * @param {string} path - * @param {string} base - * @param {string} [type] - */ - (path4, base, type = "package") => { - return `Cannot find ${type} '${path4}' imported from ${base}`; - }, - Error -); -codes.ERR_NETWORK_IMPORT_DISALLOWED = createError( - "ERR_NETWORK_IMPORT_DISALLOWED", - "import of '%s' by %s is not supported: %s", - Error -); -codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError( - "ERR_PACKAGE_IMPORT_NOT_DEFINED", - /** - * @param {string} specifier - * @param {string} packagePath - * @param {string} base - */ - (specifier, packagePath, base) => { - return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`; - }, - TypeError -); -codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError( - "ERR_PACKAGE_PATH_NOT_EXPORTED", - /** - * @param {string} pkgPath - * @param {string} subpath - * @param {string} [base] - */ - (pkgPath, subpath, base = void 0) => { - if (subpath === ".") - return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`; - return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`; - }, - Error -); -codes.ERR_UNSUPPORTED_DIR_IMPORT = createError( - "ERR_UNSUPPORTED_DIR_IMPORT", - "Directory import '%s' is not supported resolving ES modules imported from %s", - Error -); -codes.ERR_UNKNOWN_FILE_EXTENSION = createError( - "ERR_UNKNOWN_FILE_EXTENSION", - /** - * @param {string} ext - * @param {string} path - */ - (ext, path4) => { - return `Unknown file extension "${ext}" for ${path4}`; - }, - TypeError -); -codes.ERR_INVALID_ARG_VALUE = createError( - "ERR_INVALID_ARG_VALUE", - /** - * @param {string} name - * @param {unknown} value - * @param {string} [reason='is invalid'] - */ - (name, value, reason = "is invalid") => { - let inspected = (0, import_node_util.inspect)(value); - if (inspected.length > 128) { - inspected = `${inspected.slice(0, 128)}...`; - } - const type = name.includes(".") ? "property" : "argument"; - return `The ${type} '${name}' ${reason}. Received ${inspected}`; - }, - TypeError - // Note: extra classes have been shaken out. - // , RangeError -); -codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError( - "ERR_UNSUPPORTED_ESM_URL_SCHEME", - /** - * @param {URL} url - * @param {Array} supported - */ - (url, supported) => { - let message = `Only URLs with a scheme in: ${formatList( - supported - )} are supported by the default ESM loader`; - if (isWindows && url.protocol.length === 2) { - message += ". On Windows, absolute paths must be valid file:// URLs"; - } - message += `. Received protocol '${url.protocol}'`; - return message; - }, - Error -); -function createError(sym, value, def) { - messages.set(sym, value); - return makeNodeErrorWithCode(def, sym); -} -function makeNodeErrorWithCode(Base, key) { - return NodeError; - function NodeError(...args) { - const limit = Error.stackTraceLimit; - if (isErrorStackTraceLimitWritable()) - Error.stackTraceLimit = 0; - const error = new Base(); - if (isErrorStackTraceLimitWritable()) - Error.stackTraceLimit = limit; - const message = getMessage(key, args, error); - Object.defineProperties(error, { - // Note: no need to implement `kIsNodeError` symbol, would be hard, - // probably. - message: { - value: message, - enumerable: false, - writable: true, - configurable: true - }, - toString: { - /** @this {Error} */ - value() { - return `${this.name} [${key}]: ${this.message}`; - }, - enumerable: false, - writable: true, - configurable: true - } - }); - captureLargerStackTrace(error); - error.code = key; - return error; - } -} -function isErrorStackTraceLimitWritable() { - try { - if (import_node_v8.default.startupSnapshot.isBuildingSnapshot()) { - return false; - } - } catch { - } - const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); - if (desc === void 0) { - return Object.isExtensible(Error); - } - return own.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0; -} -function hideStackFrames(fn) { - const hidden = nodeInternalPrefix + fn.name; - Object.defineProperty(fn, "name", { value: hidden }); - return fn; -} -var captureLargerStackTrace = hideStackFrames( - /** - * @param {Error} error - * @returns {Error} - */ - // @ts-expect-error: fine - function(error) { - const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); - if (stackTraceLimitIsWritable) { - userStackTraceLimit = Error.stackTraceLimit; - Error.stackTraceLimit = Number.POSITIVE_INFINITY; - } - Error.captureStackTrace(error); - if (stackTraceLimitIsWritable) - Error.stackTraceLimit = userStackTraceLimit; - return error; - } -); -function getMessage(key, args, self) { - const message = messages.get(key); - (0, import_node_assert.default)(typeof message !== "undefined", "expected `message` to be found"); - if (typeof message === "function") { - (0, import_node_assert.default)( - message.length <= args.length, - // Default options do not count. - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${message.length}).` - ); - return Reflect.apply(message, self, args); - } - const regex = /%[dfijoOs]/g; - let expectedLength = 0; - while (regex.exec(message) !== null) - expectedLength++; - (0, import_node_assert.default)( - expectedLength === args.length, - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` - ); - if (args.length === 0) - return message; - args.unshift(message); - return Reflect.apply(import_node_util.format, null, args); -} - -// node_modules/import-meta-resolve/lib/package-json-reader.js -var import_node_fs = __toESM(require("node:fs"), 1); -var import_node_path = __toESM(require("node:path"), 1); -var reader = { read }; -var package_json_reader_default = reader; -function read(jsonPath) { - try { - const string = import_node_fs.default.readFileSync( - import_node_path.default.toNamespacedPath(import_node_path.default.join(import_node_path.default.dirname(jsonPath), "package.json")), - "utf8" - ); - return { string }; - } catch (error) { - const exception = ( - /** @type {ErrnoException} */ - error - ); - if (exception.code === "ENOENT") { - return { string: void 0 }; - } - throw exception; - } -} - -// node_modules/import-meta-resolve/lib/package-config.js -var { ERR_INVALID_PACKAGE_CONFIG } = codes; -var packageJsonCache = /* @__PURE__ */ new Map(); -function getPackageConfig(path4, specifier, base) { - const existing = packageJsonCache.get(path4); - if (existing !== void 0) { - return existing; - } - const source = package_json_reader_default.read(path4).string; - if (source === void 0) { - const packageConfig2 = { - pjsonPath: path4, - exists: false, - main: void 0, - name: void 0, - type: "none", - exports: void 0, - imports: void 0 - }; - packageJsonCache.set(path4, packageConfig2); - return packageConfig2; - } - let packageJson; - try { - packageJson = JSON.parse(source); - } catch (error) { - const exception = ( - /** @type {ErrnoException} */ - error - ); - throw new ERR_INVALID_PACKAGE_CONFIG( - path4, - (base ? `"${specifier}" from ` : "") + (0, import_node_url.fileURLToPath)(base || specifier), - exception.message - ); - } - const { exports, imports, main, name, type } = packageJson; - const packageConfig = { - pjsonPath: path4, - exists: true, - main: typeof main === "string" ? main : void 0, - name: typeof name === "string" ? name : void 0, - type: type === "module" || type === "commonjs" ? type : "none", - // @ts-expect-error Assume `Record`. - exports, - // @ts-expect-error Assume `Record`. - imports: imports && typeof imports === "object" ? imports : void 0 - }; - packageJsonCache.set(path4, packageConfig); - return packageConfig; -} -function getPackageScopeConfig(resolved) { - let packageJsonUrl = new import_node_url.URL("package.json", resolved); - while (true) { - const packageJsonPath2 = packageJsonUrl.pathname; - if (packageJsonPath2.endsWith("node_modules/package.json")) - break; - const packageConfig2 = getPackageConfig( - (0, import_node_url.fileURLToPath)(packageJsonUrl), - resolved - ); - if (packageConfig2.exists) - return packageConfig2; - const lastPackageJsonUrl = packageJsonUrl; - packageJsonUrl = new import_node_url.URL("../package.json", packageJsonUrl); - if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) - break; - } - const packageJsonPath = (0, import_node_url.fileURLToPath)(packageJsonUrl); - const packageConfig = { - pjsonPath: packageJsonPath, - exists: false, - main: void 0, - name: void 0, - type: "none", - exports: void 0, - imports: void 0 - }; - packageJsonCache.set(packageJsonPath, packageConfig); - return packageConfig; -} - -// node_modules/import-meta-resolve/lib/resolve-get-package-type.js -function getPackageType(url) { - const packageConfig = getPackageScopeConfig(url); - return packageConfig.type; -} - -// node_modules/import-meta-resolve/lib/get-format.js -var { ERR_UNKNOWN_FILE_EXTENSION } = codes; -var hasOwnProperty = {}.hasOwnProperty; -var extensionFormatMap = { - // @ts-expect-error: hush. - __proto__: null, - ".cjs": "commonjs", - ".js": "module", - ".json": "json", - ".mjs": "module" -}; -function mimeToFormat(mime) { - if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) - return "module"; - if (mime === "application/json") - return "json"; - return null; -} -var protocolHandlers = { - // @ts-expect-error: hush. - __proto__: null, - "data:": getDataProtocolModuleFormat, - "file:": getFileProtocolModuleFormat, - "http:": getHttpProtocolModuleFormat, - "https:": getHttpProtocolModuleFormat, - "node:"() { - return "builtin"; - } -}; -function getDataProtocolModuleFormat(parsed) { - const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec( - parsed.pathname - ) || [null, null, null]; - return mimeToFormat(mime); -} -function getFileProtocolModuleFormat(url, _context, ignoreErrors) { - const filepath = (0, import_node_url2.fileURLToPath)(url); - const ext = import_node_path2.default.extname(filepath); - if (ext === ".js") { - return getPackageType(url) === "module" ? "module" : "commonjs"; - } - const format2 = extensionFormatMap[ext]; - if (format2) - return format2; - if (ignoreErrors) { - return void 0; - } - throw new ERR_UNKNOWN_FILE_EXTENSION(ext, filepath); -} -function getHttpProtocolModuleFormat() { -} -function defaultGetFormatWithoutErrors(url, context) { - if (!hasOwnProperty.call(protocolHandlers, url.protocol)) { - return null; - } - return protocolHandlers[url.protocol](url, context, true) || null; -} - -// node_modules/import-meta-resolve/lib/utils.js -var { ERR_INVALID_ARG_VALUE } = codes; -var DEFAULT_CONDITIONS = Object.freeze(["node", "import"]); -var DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS); -function getDefaultConditions() { - return DEFAULT_CONDITIONS; -} -function getDefaultConditionsSet() { - return DEFAULT_CONDITIONS_SET; -} -function getConditionsSet(conditions) { - if (conditions !== void 0 && conditions !== getDefaultConditions()) { - if (!Array.isArray(conditions)) { - throw new ERR_INVALID_ARG_VALUE( - "conditions", - conditions, - "expected an array" - ); - } - return new Set(conditions); - } - return getDefaultConditionsSet(); -} - -// node_modules/import-meta-resolve/lib/resolve.js -var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace]; -var experimentalNetworkImports = false; -var { - ERR_NETWORK_IMPORT_DISALLOWED, - ERR_INVALID_MODULE_SPECIFIER, - ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG2, - ERR_INVALID_PACKAGE_TARGET, - ERR_MODULE_NOT_FOUND, - ERR_PACKAGE_IMPORT_NOT_DEFINED, - ERR_PACKAGE_PATH_NOT_EXPORTED, - ERR_UNSUPPORTED_DIR_IMPORT, - ERR_UNSUPPORTED_ESM_URL_SCHEME -} = codes; -var own2 = {}.hasOwnProperty; -var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; -var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; -var invalidPackageNameRegEx = /^\.|%|\\/; -var patternRegEx = /\*/g; -var encodedSepRegEx = /%2f|%5c/i; -var emittedPackageWarnings = /* @__PURE__ */ new Set(); -var doubleSlashRegEx = /[/\\]{2}/; -function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) { - const pjsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl); - const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null; - import_node_process2.default.emitWarning( - `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_node_url3.fileURLToPath)(base)}` : ""}.`, - "DeprecationWarning", - "DEP0166" - ); -} -function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { - const format2 = defaultGetFormatWithoutErrors(url, { parentURL: base.href }); - if (format2 !== "module") - return; - const path4 = (0, import_node_url3.fileURLToPath)(url.href); - const pkgPath = (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)); - const basePath = (0, import_node_url3.fileURLToPath)(base); - if (main) - import_node_process2.default.emitWarning( - `Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, excluding the full filename and extension to the resolved file at "${path4.slice( - pkgPath.length - )}", imported from ${basePath}. - Automatic extension resolution of the "main" field isdeprecated for ES modules.`, - "DeprecationWarning", - "DEP0151" - ); - else - import_node_process2.default.emitWarning( - `No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path4.slice( - pkgPath.length - )}", imported from ${basePath}. -Default "index" lookups for the main are deprecated for ES modules.`, - "DeprecationWarning", - "DEP0151" - ); -} -function tryStatSync(path4) { - try { - return (0, import_node_fs2.statSync)(path4); - } catch { - return new import_node_fs2.Stats(); - } -} -function fileExists(url) { - const stats = (0, import_node_fs2.statSync)(url, { throwIfNoEntry: false }); - const isFile = stats ? stats.isFile() : void 0; - return isFile === null || isFile === void 0 ? false : isFile; -} -function legacyMainResolve(packageJsonUrl, packageConfig, base) { - let guess; - if (packageConfig.main !== void 0) { - guess = new import_node_url3.URL(packageConfig.main, packageJsonUrl); - if (fileExists(guess)) - return guess; - const tries2 = [ - `./${packageConfig.main}.js`, - `./${packageConfig.main}.json`, - `./${packageConfig.main}.node`, - `./${packageConfig.main}/index.js`, - `./${packageConfig.main}/index.json`, - `./${packageConfig.main}/index.node` - ]; - let i2 = -1; - while (++i2 < tries2.length) { - guess = new import_node_url3.URL(tries2[i2], packageJsonUrl); - if (fileExists(guess)) - break; - guess = void 0; - } - if (guess) { - emitLegacyIndexDeprecation( - guess, - packageJsonUrl, - base, - packageConfig.main - ); - return guess; - } - } - const tries = ["./index.js", "./index.json", "./index.node"]; - let i = -1; - while (++i < tries.length) { - guess = new import_node_url3.URL(tries[i], packageJsonUrl); - if (fileExists(guess)) - break; - guess = void 0; - } - if (guess) { - emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); - return guess; - } - throw new ERR_MODULE_NOT_FOUND( - (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)), - (0, import_node_url3.fileURLToPath)(base) - ); -} -function finalizeResolution(resolved, base, preserveSymlinks) { - if (encodedSepRegEx.exec(resolved.pathname) !== null) - throw new ERR_INVALID_MODULE_SPECIFIER( - resolved.pathname, - 'must not include encoded "/" or "\\" characters', - (0, import_node_url3.fileURLToPath)(base) - ); - const filePath = (0, import_node_url3.fileURLToPath)(resolved); - const stats = tryStatSync( - filePath.endsWith("/") ? filePath.slice(-1) : filePath - ); - if (stats.isDirectory()) { - const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, (0, import_node_url3.fileURLToPath)(base)); - error.url = String(resolved); - throw error; - } - if (!stats.isFile()) { - throw new ERR_MODULE_NOT_FOUND( - filePath || resolved.pathname, - base && (0, import_node_url3.fileURLToPath)(base), - "module" - ); - } - if (!preserveSymlinks) { - const real = (0, import_node_fs2.realpathSync)(filePath); - const { search, hash } = resolved; - resolved = (0, import_node_url3.pathToFileURL)(real + (filePath.endsWith(import_node_path3.default.sep) ? "/" : "")); - resolved.search = search; - resolved.hash = hash; - } - return resolved; -} -function importNotDefined(specifier, packageJsonUrl, base) { - return new ERR_PACKAGE_IMPORT_NOT_DEFINED( - specifier, - packageJsonUrl && (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)), - (0, import_node_url3.fileURLToPath)(base) - ); -} -function exportsNotFound(subpath, packageJsonUrl, base) { - return new ERR_PACKAGE_PATH_NOT_EXPORTED( - (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)), - subpath, - base && (0, import_node_url3.fileURLToPath)(base) - ); -} -function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) { - const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${(0, import_node_url3.fileURLToPath)(packageJsonUrl)}`; - throw new ERR_INVALID_MODULE_SPECIFIER( - request, - reason, - base && (0, import_node_url3.fileURLToPath)(base) - ); -} -function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { - target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`; - return new ERR_INVALID_PACKAGE_TARGET( - (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)), - subpath, - target, - internal, - base && (0, import_node_url3.fileURLToPath)(base) - ); -} -function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) { - if (subpath !== "" && !pattern && target[target.length - 1] !== "/") - throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); - if (!target.startsWith("./")) { - if (internal && !target.startsWith("../") && !target.startsWith("/")) { - let isURL = false; - try { - new import_node_url3.URL(target); - isURL = true; - } catch { - } - if (!isURL) { - const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call( - patternRegEx, - target, - () => subpath - ) : target + subpath; - return packageResolve(exportTarget, packageJsonUrl, conditions); - } - } - throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); - } - if (invalidSegmentRegEx.exec(target.slice(2)) !== null) { - if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) { - if (!isPathMap) { - const request = pattern ? match.replace("*", () => subpath) : match + subpath; - const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call( - patternRegEx, - target, - () => subpath - ) : target; - emitInvalidSegmentDeprecation( - resolvedTarget, - request, - match, - packageJsonUrl, - internal, - base, - true - ); - } - } else { - throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); - } - } - const resolved = new import_node_url3.URL(target, packageJsonUrl); - const resolvedPath = resolved.pathname; - const packagePath = new import_node_url3.URL(".", packageJsonUrl).pathname; - if (!resolvedPath.startsWith(packagePath)) - throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); - if (subpath === "") - return resolved; - if (invalidSegmentRegEx.exec(subpath) !== null) { - const request = pattern ? match.replace("*", () => subpath) : match + subpath; - if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) { - if (!isPathMap) { - const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call( - patternRegEx, - target, - () => subpath - ) : target; - emitInvalidSegmentDeprecation( - resolvedTarget, - request, - match, - packageJsonUrl, - internal, - base, - false - ); - } - } else { - throwInvalidSubpath(request, match, packageJsonUrl, internal, base); - } - } - if (pattern) { - return new import_node_url3.URL( - RegExpPrototypeSymbolReplace.call( - patternRegEx, - resolved.href, - () => subpath - ) - ); - } - return new import_node_url3.URL(subpath, resolved); -} -function isArrayIndex(key) { - const keyNumber = Number(key); - if (`${keyNumber}` !== key) - return false; - return keyNumber >= 0 && keyNumber < 4294967295; -} -function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) { - if (typeof target === "string") { - return resolvePackageTargetString( - target, - subpath, - packageSubpath, - packageJsonUrl, - base, - pattern, - internal, - isPathMap, - conditions - ); - } - if (Array.isArray(target)) { - const targetList = target; - if (targetList.length === 0) - return null; - let lastException; - let i = -1; - while (++i < targetList.length) { - const targetItem = targetList[i]; - let resolveResult; - try { - resolveResult = resolvePackageTarget( - packageJsonUrl, - targetItem, - subpath, - packageSubpath, - base, - pattern, - internal, - isPathMap, - conditions - ); - } catch (error) { - const exception = ( - /** @type {ErrnoException} */ - error - ); - lastException = exception; - if (exception.code === "ERR_INVALID_PACKAGE_TARGET") - continue; - throw error; - } - if (resolveResult === void 0) - continue; - if (resolveResult === null) { - lastException = null; - continue; - } - return resolveResult; - } - if (lastException === void 0 || lastException === null) { - return null; - } - throw lastException; - } - if (typeof target === "object" && target !== null) { - const keys = Object.getOwnPropertyNames(target); - let i = -1; - while (++i < keys.length) { - const key = keys[i]; - if (isArrayIndex(key)) { - throw new ERR_INVALID_PACKAGE_CONFIG2( - (0, import_node_url3.fileURLToPath)(packageJsonUrl), - base, - '"exports" cannot contain numeric property keys.' - ); - } - } - i = -1; - while (++i < keys.length) { - const key = keys[i]; - if (key === "default" || conditions && conditions.has(key)) { - const conditionalTarget = ( - /** @type {unknown} */ - target[key] - ); - const resolveResult = resolvePackageTarget( - packageJsonUrl, - conditionalTarget, - subpath, - packageSubpath, - base, - pattern, - internal, - isPathMap, - conditions - ); - if (resolveResult === void 0) - continue; - return resolveResult; - } - } - return null; - } - if (target === null) { - return null; - } - throw invalidPackageTarget( - packageSubpath, - target, - packageJsonUrl, - internal, - base - ); -} -function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { - if (typeof exports === "string" || Array.isArray(exports)) - return true; - if (typeof exports !== "object" || exports === null) - return false; - const keys = Object.getOwnPropertyNames(exports); - let isConditionalSugar = false; - let i = 0; - let j = -1; - while (++j < keys.length) { - const key = keys[j]; - const curIsConditionalSugar = key === "" || key[0] !== "."; - if (i++ === 0) { - isConditionalSugar = curIsConditionalSugar; - } else if (isConditionalSugar !== curIsConditionalSugar) { - throw new ERR_INVALID_PACKAGE_CONFIG2( - (0, import_node_url3.fileURLToPath)(packageJsonUrl), - base, - `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.` - ); - } - } - return isConditionalSugar; -} -function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { - const pjsonPath = (0, import_node_url3.fileURLToPath)(pjsonUrl); - if (emittedPackageWarnings.has(pjsonPath + "|" + match)) - return; - emittedPackageWarnings.add(pjsonPath + "|" + match); - import_node_process2.default.emitWarning( - `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_node_url3.fileURLToPath)(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`, - "DeprecationWarning", - "DEP0155" - ); -} -function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) { - let exports = packageConfig.exports; - if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) { - exports = { ".": exports }; - } - if (own2.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) { - const target = exports[packageSubpath]; - const resolveResult = resolvePackageTarget( - packageJsonUrl, - target, - "", - packageSubpath, - base, - false, - false, - false, - conditions - ); - if (resolveResult === null || resolveResult === void 0) { - throw exportsNotFound(packageSubpath, packageJsonUrl, base); - } - return resolveResult; - } - let bestMatch = ""; - let bestMatchSubpath = ""; - const keys = Object.getOwnPropertyNames(exports); - let i = -1; - while (++i < keys.length) { - const key = keys[i]; - const patternIndex = key.indexOf("*"); - if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) { - if (packageSubpath.endsWith("/")) { - emitTrailingSlashPatternDeprecation( - packageSubpath, - packageJsonUrl, - base - ); - } - const patternTrailer = key.slice(patternIndex + 1); - if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) { - bestMatch = key; - bestMatchSubpath = packageSubpath.slice( - patternIndex, - packageSubpath.length - patternTrailer.length - ); - } - } - } - if (bestMatch) { - const target = ( - /** @type {unknown} */ - exports[bestMatch] - ); - const resolveResult = resolvePackageTarget( - packageJsonUrl, - target, - bestMatchSubpath, - bestMatch, - base, - true, - false, - packageSubpath.endsWith("/"), - conditions - ); - if (resolveResult === null || resolveResult === void 0) { - throw exportsNotFound(packageSubpath, packageJsonUrl, base); - } - return resolveResult; - } - throw exportsNotFound(packageSubpath, packageJsonUrl, base); -} -function patternKeyCompare(a, b) { - const aPatternIndex = a.indexOf("*"); - const bPatternIndex = b.indexOf("*"); - const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; - const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; - if (baseLengthA > baseLengthB) - return -1; - if (baseLengthB > baseLengthA) - return 1; - if (aPatternIndex === -1) - return 1; - if (bPatternIndex === -1) - return -1; - if (a.length > b.length) - return -1; - if (b.length > a.length) - return 1; - return 0; -} -function packageImportsResolve(name, base, conditions) { - if (name === "#" || name.startsWith("#/") || name.endsWith("/")) { - const reason = "is not a valid internal imports specifier name"; - throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, import_node_url3.fileURLToPath)(base)); - } - let packageJsonUrl; - const packageConfig = getPackageScopeConfig(base); - if (packageConfig.exists) { - packageJsonUrl = (0, import_node_url3.pathToFileURL)(packageConfig.pjsonPath); - const imports = packageConfig.imports; - if (imports) { - if (own2.call(imports, name) && !name.includes("*")) { - const resolveResult = resolvePackageTarget( - packageJsonUrl, - imports[name], - "", - name, - base, - false, - true, - false, - conditions - ); - if (resolveResult !== null && resolveResult !== void 0) { - return resolveResult; - } - } else { - let bestMatch = ""; - let bestMatchSubpath = ""; - const keys = Object.getOwnPropertyNames(imports); - let i = -1; - while (++i < keys.length) { - const key = keys[i]; - const patternIndex = key.indexOf("*"); - if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) { - const patternTrailer = key.slice(patternIndex + 1); - if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) { - bestMatch = key; - bestMatchSubpath = name.slice( - patternIndex, - name.length - patternTrailer.length - ); - } - } - } - if (bestMatch) { - const target = imports[bestMatch]; - const resolveResult = resolvePackageTarget( - packageJsonUrl, - target, - bestMatchSubpath, - bestMatch, - base, - true, - true, - false, - conditions - ); - if (resolveResult !== null && resolveResult !== void 0) { - return resolveResult; - } - } - } - } - } - throw importNotDefined(name, packageJsonUrl, base); -} -function parsePackageName(specifier, base) { - let separatorIndex = specifier.indexOf("/"); - let validPackageName = true; - let isScoped = false; - if (specifier[0] === "@") { - isScoped = true; - if (separatorIndex === -1 || specifier.length === 0) { - validPackageName = false; - } else { - separatorIndex = specifier.indexOf("/", separatorIndex + 1); - } - } - const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); - if (invalidPackageNameRegEx.exec(packageName) !== null) { - validPackageName = false; - } - if (!validPackageName) { - throw new ERR_INVALID_MODULE_SPECIFIER( - specifier, - "is not a valid package name", - (0, import_node_url3.fileURLToPath)(base) - ); - } - const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex)); - return { packageName, packageSubpath, isScoped }; -} -function packageResolve(specifier, base, conditions) { - if (import_node_module.builtinModules.includes(specifier)) { - return new import_node_url3.URL("node:" + specifier); - } - const { packageName, packageSubpath, isScoped } = parsePackageName( - specifier, - base - ); - const packageConfig = getPackageScopeConfig(base); - if (packageConfig.exists) { - const packageJsonUrl2 = (0, import_node_url3.pathToFileURL)(packageConfig.pjsonPath); - if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) { - return packageExportsResolve( - packageJsonUrl2, - packageSubpath, - packageConfig, - base, - conditions - ); - } - } - let packageJsonUrl = new import_node_url3.URL( - "./node_modules/" + packageName + "/package.json", - base - ); - let packageJsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl); - let lastPath; - do { - const stat = tryStatSync(packageJsonPath.slice(0, -13)); - if (!stat.isDirectory()) { - lastPath = packageJsonPath; - packageJsonUrl = new import_node_url3.URL( - (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", - packageJsonUrl - ); - packageJsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl); - continue; - } - const packageConfig2 = getPackageConfig(packageJsonPath, specifier, base); - if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) { - return packageExportsResolve( - packageJsonUrl, - packageSubpath, - packageConfig2, - base, - conditions - ); - } - if (packageSubpath === ".") { - return legacyMainResolve(packageJsonUrl, packageConfig2, base); - } - return new import_node_url3.URL(packageSubpath, packageJsonUrl); - } while (packageJsonPath.length !== lastPath.length); - throw new ERR_MODULE_NOT_FOUND(packageName, (0, import_node_url3.fileURLToPath)(base)); -} -function isRelativeSpecifier(specifier) { - if (specifier[0] === ".") { - if (specifier.length === 1 || specifier[1] === "/") - return true; - if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) { - return true; - } - } - return false; -} -function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { - if (specifier === "") - return false; - if (specifier[0] === "/") - return true; - return isRelativeSpecifier(specifier); -} -function moduleResolve(specifier, base, conditions, preserveSymlinks) { - const isRemote = base.protocol === "http:" || base.protocol === "https:"; - let resolved; - if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { - resolved = new import_node_url3.URL(specifier, base); - } else if (!isRemote && specifier[0] === "#") { - resolved = packageImportsResolve(specifier, base, conditions); - } else { - try { - resolved = new import_node_url3.URL(specifier); - } catch { - if (!isRemote) { - resolved = packageResolve(specifier, base, conditions); - } - } - } - (0, import_node_assert2.default)(typeof resolved !== "undefined", "expected to be defined"); - if (resolved.protocol !== "file:") { - return resolved; - } - return finalizeResolution(resolved, base, preserveSymlinks); -} -function checkIfDisallowedImport(specifier, parsed, parsedParentURL) { - if (parsed && parsedParentURL && (parsedParentURL.protocol === "http:" || parsedParentURL.protocol === "https:")) { - if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { - if (parsed && parsed.protocol !== "https:" && parsed.protocol !== "http:") { - throw new ERR_NETWORK_IMPORT_DISALLOWED( - specifier, - parsedParentURL, - "remote imports cannot import from a local location." - ); - } - return { url: parsed.href }; - } - if (import_node_module.builtinModules.includes(specifier)) { - throw new ERR_NETWORK_IMPORT_DISALLOWED( - specifier, - parsedParentURL, - "remote imports cannot import from a local location." - ); - } - throw new ERR_NETWORK_IMPORT_DISALLOWED( - specifier, - parsedParentURL, - "only relative and absolute specifiers are supported." - ); - } -} -function throwIfUnsupportedURLProtocol(url) { - if (url.protocol !== "file:" && url.protocol !== "data:" && url.protocol !== "node:") { - throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url); - } -} -function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports2) { - if (parsed && parsed.protocol !== "file:" && parsed.protocol !== "data:" && (!experimentalNetworkImports2 || parsed.protocol !== "https:" && parsed.protocol !== "http:")) { - throw new ERR_UNSUPPORTED_ESM_URL_SCHEME( - parsed, - ["file", "data"].concat( - experimentalNetworkImports2 ? ["https", "http"] : [] - ) - ); - } -} -function defaultResolve(specifier, context = {}) { - const { parentURL } = context; - (0, import_node_assert2.default)(typeof parentURL !== "undefined", "expected `parentURL` to be defined"); - let parsedParentURL; - if (parentURL) { - try { - parsedParentURL = new import_node_url3.URL(parentURL); - } catch { - } - } - let parsed; - try { - parsed = shouldBeTreatedAsRelativeOrAbsolutePath(specifier) ? new import_node_url3.URL(specifier, parsedParentURL) : new import_node_url3.URL(specifier); - if (parsed.protocol === "data:" || experimentalNetworkImports && (parsed.protocol === "https:" || parsed.protocol === "http:")) { - return { url: parsed.href, format: null }; - } - } catch { - } - const maybeReturn = checkIfDisallowedImport( - specifier, - parsed, - parsedParentURL - ); - if (maybeReturn) - return maybeReturn; - if (parsed && parsed.protocol === "node:") - return { url: specifier }; - throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports); - const conditions = getConditionsSet(context.conditions); - const url = moduleResolve(specifier, new import_node_url3.URL(parentURL), conditions, false); - throwIfUnsupportedURLProtocol(url); - return { - // Do NOT cast `url` to a string: that will work even when there are real - // problems, silencing them - url: url.href, - format: defaultGetFormatWithoutErrors(url, { parentURL }) - }; -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - defaultResolve, - moduleResolve -}); diff --git a/lib/rules/no-hide-core-modules.js b/lib/rules/no-hide-core-modules.js index 6c66b1e7..87e1e237 100644 --- a/lib/rules/no-hide-core-modules.js +++ b/lib/rules/no-hide-core-modules.js @@ -9,11 +9,7 @@ "use strict" const path = require("path") -const resolve = require("resolve") -const { pathToFileURL, fileURLToPath } = require("url") -const { - defaultResolve: importResolve, -} = require("../converted-esm/import-meta-resolve") +const resolver = require("enhanced-resolve") const getPackageJson = require("../util/get-package-json") const mergeVisitorsInPlace = require("../util/merge-visitors-in-place") const visitImport = require("../util/visit-import") @@ -117,6 +113,10 @@ module.exports = { ), { "Program:exit"() { + const requireResolve = resolver.create.sync({ + conditionNames: ["node", "import", "require"], + }) + for (const target of targets.filter( t => CORE_MODULES.has(t.moduleName) && @@ -132,34 +132,22 @@ module.exports = { continue } - let resolved = "" - const moduleId = `${name}/` try { - resolved = resolve.sync(moduleId, { - basedir: dirPath, - }) - } catch (_error) { - try { - const { url } = importResolve(moduleId, { - parentURL: pathToFileURL(dirPath).href, - }) + const resolved = requireResolve(dirPath, `${name}/`) - resolved = fileURLToPath(url) - } catch (_error) { - continue - } + context.report({ + node: target.node, + loc: target.node.loc, + messageId: "unexpectedImport", + data: { + name: path + .relative(dirPath, resolved) + .replace(BACK_SLASH, "/"), + }, + }) + } catch { + continue } - - context.report({ - node: target.node, - loc: target.node.loc, - messageId: "unexpectedImport", - data: { - name: path - .relative(dirPath, resolved) - .replace(BACK_SLASH, "/"), - }, - }) } }, }, diff --git a/lib/util/import-target.js b/lib/util/import-target.js index 268a99f2..a46ceab2 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -4,13 +4,9 @@ */ "use strict" -const path = require("path") -const { pathToFileURL, fileURLToPath } = require("url") +const { resolve, sep } = require("path") const isBuiltin = require("is-builtin-module") -const resolve = require("resolve") -const { - defaultResolve: importResolve, -} = require("../converted-esm/import-meta-resolve") +const resolver = require("enhanced-resolve") /** * Resolve the given id to file paths. @@ -22,60 +18,50 @@ const { * @returns {string|null} The resolved path. */ function getFilePath(isModule, id, options, moduleType) { + const conditionNames = ["node", "require"] + const { extensions } = options + const mainFields = [] + const mainFiles = [] + if (moduleType === "import") { - const paths = - options.paths && options.paths.length > 0 - ? options.paths.map(p => path.resolve(process.cwd(), p)) - : [options.basedir] - for (const aPath of paths) { - try { - const { url } = importResolve(id, { - parentURL: pathToFileURL(path.join(aPath, "dummy-file.mjs")) - .href, - conditions: ["node", "import", "require"], - }) - - if (url) { - return fileURLToPath(url) - } - } catch (e) { - continue - } - } + conditionNames.push("import") + } - if (isModule) { - return null - } - return path.resolve( - (options.paths && options.paths[0]) || options.basedir, - id - ) - } else { + if (moduleType === "require" || isModule === true) { + mainFields.push("main") + mainFiles.push("index") + } + + const requireResolve = resolver.create.sync({ + conditionNames, + extensions, + mainFields, + mainFiles, + }) + + const directories = Array.isArray(options.paths) + ? [...options.paths, options.basedir] + : [options.basedir] + + for (const directory of directories) { try { - return resolve.sync(id, options) - } catch (_err) { - try { - const { url } = importResolve(id, { - parentURL: pathToFileURL( - path.join(options.basedir, "dummy-file.js") - ).href, - conditions: ["node", "require"], - }) - - return fileURLToPath(url) - } catch (err) { - if (isModule) { - return null - } - return path.resolve(options.basedir, id) - } + const baseDir = resolve(process.cwd(), directory) + return requireResolve(baseDir, id) + } catch { + continue } } + + if (isModule) { + return null + } + + return resolve(options.basedir, id) } function isNodeModule(name, options) { try { - return require.resolve(name, options).startsWith(path.sep) + return require.resolve(name, options).startsWith(sep) } catch { return false } diff --git a/package.json b/package.json index a34aa275..a2e228ac 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", "builtins": "^5.0.1", + "enhanced-resolve": "^5.15.0", "eslint-plugin-es-x": "^7.5.0", "get-tsconfig": "^4.7.0", "globals": "^13.24.0", @@ -38,7 +39,6 @@ "eslint-plugin-n": "file:.", "fast-glob": "^3.2.12", "husky": "^8.0.3", - "import-meta-resolve": "^3.0.0", "lint-staged": "^13.2.2", "markdownlint-cli": "^0.35.0", "mocha": "^10.2.0", diff --git a/scripts/convert-pure-esm-to-cjs.js b/scripts/convert-pure-esm-to-cjs.js deleted file mode 100644 index bbd859b4..00000000 --- a/scripts/convert-pure-esm-to-cjs.js +++ /dev/null @@ -1,6 +0,0 @@ -const { execSync } = require("child_process") - -execSync( - "./node_modules/.bin/esbuild --platform=node --external:builtins --bundle node_modules/import-meta-resolve/lib/resolve.js > lib/converted-esm/import-meta-resolve.js", - { shell: true } -) diff --git a/tests/lib/rules/no-missing-require.js b/tests/lib/rules/no-missing-require.js index cadcfc16..c86b9aa8 100644 --- a/tests/lib/rules/no-missing-require.js +++ b/tests/lib/rules/no-missing-require.js @@ -40,10 +40,6 @@ ruleTester.run("no-missing-require", rule, { filename: fixture("test.js"), code: "require('eslint');", }, - { - filename: fixture("test.js"), - code: "require('eslint/lib/api');", - }, { filename: fixture("test.js"), code: "require('./a');", @@ -100,19 +96,20 @@ ruleTester.run("no-missing-require", rule, { // resolvePaths { filename: fixture("test.js"), - code: "require('fixtures/no-missing/a');", + code: "require('./fixtures/no-missing/a');", + env: { node: true }, settings: { node: { resolvePaths: [path.resolve(__dirname, "../../")] }, }, }, { filename: fixture("test.js"), - code: "require('fixtures/no-missing/a');", + code: "require('./fixtures/no-missing/a');", options: [{ resolvePaths: [path.resolve(__dirname, "../../")] }], }, { filename: fixture("test.js"), - code: "require('fixtures/no-missing/a');", + code: "require('./fixtures/no-missing/a');", options: [{ resolvePaths: ["tests"] }], }, diff --git a/tests/lib/rules/no-unpublished-import.js b/tests/lib/rules/no-unpublished-import.js index 99bbc4f6..9582c69d 100644 --- a/tests/lib/rules/no-unpublished-import.js +++ b/tests/lib/rules/no-unpublished-import.js @@ -129,12 +129,6 @@ ruleTester.run("no-unpublished-import", rule, { options: [{ allowModules: ["electron"] }], }, - // Should not fill in the extension - { - filename: fixture("2/test.js"), - code: "import ignore1 from './ignore1';", - }, - // Auto-published files only apply to root package directory { filename: fixture("3/src/readme.js"), From 4170b374157e4a6aeb30827ebef5478cd0e87016 Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Tue, 21 Nov 2023 19:24:21 +0000 Subject: [PATCH 02/15] chore: Improve the metadata from "ImportTarget" --- lib/util/check-existence.js | 2 +- lib/util/check-publish.js | 3 +- lib/util/exists.js | 4 + lib/util/import-target.js | 210 +++++++++++++++++++++++++----------- 4 files changed, 156 insertions(+), 63 deletions(-) diff --git a/lib/util/check-existence.js b/lib/util/check-existence.js index 29ef3551..40aad74e 100644 --- a/lib/util/check-existence.js +++ b/lib/util/check-existence.js @@ -17,7 +17,7 @@ const mapTypescriptExtension = require("../util/map-typescript-extension") * See Also: https://nodejs.org/api/modules.html * * @param {RuleContext} context - A context to report. - * @param {ImportTarget[]} targets - A list of target information to check. + * @param {import('../util/import-target.js')[]} targets - A list of target information to check. * @returns {void} */ exports.checkExistence = function checkExistence(context, targets) { diff --git a/lib/util/check-publish.js b/lib/util/check-publish.js index 0f5a9805..7b4535a0 100644 --- a/lib/util/check-publish.js +++ b/lib/util/check-publish.js @@ -59,7 +59,7 @@ exports.checkPublish = function checkPublish(context, filePath, targets) { if (target.moduleName != null) { return false } - const relativeTargetPath = toRelative(target.filePath) + const relativeTargetPath = toRelative(target.filePath ?? "") return ( relativeTargetPath !== "" && npmignore.match(relativeTargetPath) @@ -70,6 +70,7 @@ exports.checkPublish = function checkPublish(context, filePath, targets) { devDependencies.has(target.moduleName) && !dependencies.has(target.moduleName) && !allowed.has(target.moduleName) + if (isPrivateFile() || isDevPackage()) { context.report({ node: target.node, diff --git a/lib/util/exists.js b/lib/util/exists.js index d57981b2..b0324ae1 100644 --- a/lib/util/exists.js +++ b/lib/util/exists.js @@ -38,6 +38,10 @@ function existsCaseSensitive(filePath) { * @returns {boolean} `true` if the file of a given path exists. */ module.exports = function exists(filePath) { + if (filePath == null) { + return false + } + let result = cache.get(filePath) if (result == null) { try { diff --git a/lib/util/import-target.js b/lib/util/import-target.js index a46ceab2..81778bec 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -4,30 +4,44 @@ */ "use strict" -const { resolve, sep } = require("path") +const { resolve } = require("path") const isBuiltin = require("is-builtin-module") const resolver = require("enhanced-resolve") +/** + * @typedef {Object} Options + * @property {string[]} [extensions] + * @property {string[]} [paths] + * @property {string} basedir + */ +/** + * @typedef { 'unknown' | 'relative' | 'absolute' | 'node' | 'npm' | 'http' } ModuleType + * @typedef { 'import' | 'require' | 'type' } ModuleStyle + */ + /** * Resolve the given id to file paths. - * @param {boolean} isModule The flag which indicates this id is a module. * @param {string} id The id to resolve. - * @param {object} options The options of node-resolve module. - * It requires `options.basedir`. - * @param {'import' | 'require'} moduleType - whether the target was require-ed or imported - * @returns {string|null} The resolved path. + * @param {Options} options The options of node-resolve module. + * @param {ModuleType} moduleType - whether the target was require-ed or imported + * @param {ModuleStyle} moduleStyle - whether the target was require-ed or imported + * @returns {string | null} The resolved path. */ -function getFilePath(isModule, id, options, moduleType) { +function getFilePath(id, options, moduleType, moduleStyle) { const conditionNames = ["node", "require"] const { extensions } = options const mainFields = [] const mainFiles = [] - if (moduleType === "import") { + if (moduleStyle === "import") { conditionNames.push("import") } - if (moduleType === "require" || isModule === true) { + if (moduleStyle === "type") { + conditionNames.push("import", "types") + } + + if (moduleStyle === "require" || moduleType === "npm") { mainFields.push("main") mainFiles.push("index") } @@ -52,36 +66,15 @@ function getFilePath(isModule, id, options, moduleType) { } } - if (isModule) { - return null + if (moduleType === "absolute" || moduleType === "relative") { + return resolve(options.basedir, id) } - return resolve(options.basedir, id) + return null } -function isNodeModule(name, options) { - try { - return require.resolve(name, options).startsWith(sep) - } catch { - return false - } -} - -/** - * Gets the module name of a given path. - * - * e.g. `eslint/lib/ast-utils` -> `eslint` - * - * @param {string} nameOrPath - A path to get. - * @returns {string} The module name of the path. - */ -function getModuleName(nameOrPath) { - let end = nameOrPath.indexOf("/") - if (end !== -1 && nameOrPath[0] === "@") { - end = nameOrPath.indexOf("/", 1 + end) - } - - return end === -1 ? nameOrPath : nameOrPath.slice(0, end) +function trimAfter(string, matcher, count = 1) { + return string.split(matcher).slice(0, count).join(matcher) } /** @@ -90,17 +83,15 @@ function getModuleName(nameOrPath) { module.exports = class ImportTarget { /** * Initialize this instance. - * @param {ASTNode} node - The node of a `require()` or a module declaraiton. + * @param {import('eslint').Rule.Node} node - The node of a `require()` or a module declaraiton. * @param {string} name - The name of an import target. - * @param {object} options - The options of `node-resolve` module. + * @param {Options} options - The options of `node-resolve` module. * @param {'import' | 'require'} moduleType - whether the target was require-ed or imported */ constructor(node, name, options, moduleType) { - const isModule = !/^(?:[./\\]|\w+:)/u.test(name) - /** * The node of a `require()` or a module declaraiton. - * @type {ASTNode} + * @type {import('eslint').Rule.Node} */ this.node = node @@ -111,35 +102,132 @@ module.exports = class ImportTarget { this.name = name /** - * What type of module is this - * @type {'unknown'|'relative'|'absolute'|'node'|'npm'|'http'|void} + * The import target options. + * @type {Options} */ - this.moduleType = "unknown" - - if (name.startsWith("./") || name.startsWith(".\\")) { - this.moduleType = "relative" - } else if (name.startsWith("/") || name.startsWith("\\")) { - this.moduleType = "absolute" - } else if (isBuiltin(name)) { - this.moduleType = "node" - } else if (isNodeModule(name, options)) { - this.moduleType = "npm" - } else if (name.startsWith("http://") || name.startsWith("https://")) { - this.moduleType = "http" - } + this.options = options /** - * The full path of this import target. - * If the target is a module and it does not exist then this is `null`. - * @type {string|null} + * What type of module are we looking for? + * @type {ModuleType} + */ + this.moduleType = this.getModuleType() + + /** + * What import style are we using + * @type {ModuleStyle} */ - this.filePath = getFilePath(isModule, name, options, moduleType) + this.moduleStyle = this.getModuleStyle(moduleType) /** * The module name of this import target. * If the target is a relative path then this is `null`. - * @type {string|null} + * @type {string | null} */ - this.moduleName = isModule ? getModuleName(name) : null + this.moduleName = this.getModuleName() + + /** + * The full path of this import target. + * If the target is a module and it does not exist then this is `null`. + * @type {string | null} + */ + this.filePath = getFilePath( + name, + options, + this.moduleType, + this.moduleStyle + ) + } + + /** + * What type of module is this + * @returns {ModuleType} + */ + getModuleType() { + if (/^\.{1,2}([\\/]|$)/.test(this.name)) { + return "relative" + } + + if (/^[\\/]/.test(this.name)) { + return "absolute" + } + + if (isBuiltin(this.name)) { + return "node" + } + + if (/^(@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*/.test(this.name)) { + return "npm" + } + + if (/^https?:\/\//.test(this.name)) { + return "http" + } + + return "unknown" + } + + /** + * What module import style is used + * @param {'import' | 'require'} fallback + * @returns {ModuleStyle} + */ + getModuleStyle(fallback) { + /** @type {import('eslint').Rule.Node} */ + let node = { parent: this.node } + + do { + node = node.parent + + // `const {} = require('')` + if ( + node.type === "CallExpression" && + node.callee.name === "require" + ) { + return "require" + } + + // `import type {} from '';` + if ( + node.type === "ImportDeclaration" && + node.importKind === "type" + ) { + return "type" + } + + // `import {} from '';` + if ( + node.type === "ImportDeclaration" && + node.importKind === "value" + ) { + return "import" + } + } while (node.parent) + + return fallback + } + + /** + * Get the node or npm module name + * @returns {string} + */ + getModuleName() { + if (this.moduleType === "relative") return + + if (this.moduleType === "npm") { + if (this.name.startsWith("@")) { + return trimAfter(this.name, "/", 2) + } + + return trimAfter(this.name, "/") + } + + if (this.moduleType === "node") { + if (this.name.startsWith("node:")) { + return trimAfter(this.name.slice(5), "/") + } + + return trimAfter(this.name, "/") + } } } From b0c0fedfd6a3f6734f1461051b4a9203bb019e94 Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Tue, 21 Nov 2023 20:47:26 +0000 Subject: [PATCH 03/15] chore: remove "enhanced-resolve" from "no-hide-core-modules" --- lib/rules/no-hide-core-modules.js | 37 +++++++++++++------------------ lib/util/import-target.js | 6 ++++- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/lib/rules/no-hide-core-modules.js b/lib/rules/no-hide-core-modules.js index 87e1e237..167b45b8 100644 --- a/lib/rules/no-hide-core-modules.js +++ b/lib/rules/no-hide-core-modules.js @@ -9,7 +9,6 @@ "use strict" const path = require("path") -const resolver = require("enhanced-resolve") const getPackageJson = require("../util/get-package-json") const mergeVisitorsInPlace = require("../util/merge-visitors-in-place") const visitImport = require("../util/visit-import") @@ -25,7 +24,8 @@ const CORE_MODULES = new Set([ "crypto", "dgram", "dns", - /* "domain", */ "events", + /* "domain", */ + "events", "fs", "http", "https", @@ -33,7 +33,8 @@ const CORE_MODULES = new Set([ "net", "os", "path", - /* "punycode", */ "querystring", + /* "punycode", */ + "querystring", "readline", "repl", "stream", @@ -113,10 +114,6 @@ module.exports = { ), { "Program:exit"() { - const requireResolve = resolver.create.sync({ - conditionNames: ["node", "import", "require"], - }) - for (const target of targets.filter( t => CORE_MODULES.has(t.moduleName) && @@ -132,22 +129,20 @@ module.exports = { continue } - try { - const resolved = requireResolve(dirPath, `${name}/`) - - context.report({ - node: target.node, - loc: target.node.loc, - messageId: "unexpectedImport", - data: { - name: path - .relative(dirPath, resolved) - .replace(BACK_SLASH, "/"), - }, - }) - } catch { + if (target.filePath == null) { continue } + + context.report({ + node: target.node, + loc: target.node.loc, + messageId: "unexpectedImport", + data: { + name: path + .relative(dirPath, target.filePath) + .replace(BACK_SLASH, "/"), + }, + }) } }, }, diff --git a/lib/util/import-target.js b/lib/util/import-target.js index 81778bec..d16a0db4 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -41,7 +41,11 @@ function getFilePath(id, options, moduleType, moduleStyle) { conditionNames.push("import", "types") } - if (moduleStyle === "require" || moduleType === "npm") { + if ( + moduleStyle === "require" || + moduleType === "npm" || + moduleType === "node" + ) { mainFields.push("main") mainFiles.push("index") } From 609bdc2f3b4f37b1a52369d0b969d2197d185c43 Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Sat, 25 Nov 2023 16:52:38 +0000 Subject: [PATCH 04/15] test: Add a test for #66 --- .../no-missing/node_modules/types-only/package.json | 5 +++++ .../no-missing/node_modules/types-only/types.d.ts | 0 tests/lib/rules/no-missing-import.js | 11 +++++++++++ 3 files changed, 16 insertions(+) create mode 100644 tests/fixtures/no-missing/node_modules/types-only/package.json create mode 100644 tests/fixtures/no-missing/node_modules/types-only/types.d.ts diff --git a/tests/fixtures/no-missing/node_modules/types-only/package.json b/tests/fixtures/no-missing/node_modules/types-only/package.json new file mode 100644 index 00000000..2c8dc4f4 --- /dev/null +++ b/tests/fixtures/no-missing/node_modules/types-only/package.json @@ -0,0 +1,5 @@ +{ + "exports": { + ".": {"types": "./types.d.ts"} + } +} diff --git a/tests/fixtures/no-missing/node_modules/types-only/types.d.ts b/tests/fixtures/no-missing/node_modules/types-only/types.d.ts new file mode 100644 index 00000000..e69de29b diff --git a/tests/lib/rules/no-missing-import.js b/tests/lib/rules/no-missing-import.js index c4c9e8fa..a84911cb 100644 --- a/tests/lib/rules/no-missing-import.js +++ b/tests/lib/rules/no-missing-import.js @@ -266,6 +266,17 @@ ruleTester.run("no-missing-import", rule, { code: "import d from './d.js';", }, + // type only tests + { + filename: fixture("test.ts"), + parser: path.join( + __dirname, + "../../../node_modules/@typescript-eslint/parser" + ), + code: "import type d from 'types-only';", + env: { node: true }, + }, + // import() ...(DynamicImportSupported ? [ From 6623a68c57ae4f4fe640b01a1cca8a2ea2c71d1f Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Sun, 26 Nov 2023 15:58:42 +0000 Subject: [PATCH 05/15] feat!: Allow ts paths aliases (#84) --- lib/rules/file-extension-in-import.js | 73 ++++--- lib/util/check-existence.js | 44 +++-- lib/util/get-try-extensions.js | 2 +- lib/util/get-tsconfig.js | 2 +- lib/util/get-typescript-extension-map.js | 8 +- lib/util/import-target.js | 186 ++++++++++++------ lib/util/visit-import.js | 8 +- lib/util/visit-require.js | 8 +- .../{multi.cjs => multi.js} | 0 .../{multi.mjs => multi.json} | 0 .../no-missing/ts-paths/some/where.ts | 0 .../no-missing/ts-paths/tsconfig.json | 8 + tests/lib/rules/file-extension-in-import.js | 19 +- tests/lib/rules/no-missing-import.js | 15 +- 14 files changed, 253 insertions(+), 120 deletions(-) rename tests/fixtures/file-extension-in-import/{multi.cjs => multi.js} (100%) rename tests/fixtures/file-extension-in-import/{multi.mjs => multi.json} (100%) create mode 100644 tests/fixtures/no-missing/ts-paths/some/where.ts create mode 100644 tests/fixtures/no-missing/ts-paths/tsconfig.json diff --git a/lib/rules/file-extension-in-import.js b/lib/rules/file-extension-in-import.js index 80804029..b79e6c07 100644 --- a/lib/rules/file-extension-in-import.js +++ b/lib/rules/file-extension-in-import.js @@ -15,14 +15,14 @@ const visitImport = require("../util/visit-import") * @returns {string[]} File extensions. */ function getExistingExtensions(filePath) { - const basename = path.basename(filePath, path.extname(filePath)) + const directory = path.dirname(filePath) + const extension = path.extname(filePath) + const basename = path.basename(filePath, extension) + try { return fs - .readdirSync(path.dirname(filePath)) - .filter( - filename => - path.basename(filename, path.extname(filename)) === basename - ) + .readdirSync(directory) + .filter(filename => filename.startsWith(`${basename}.`)) .map(filename => path.extname(filename)) } catch (_error) { return [] @@ -74,47 +74,56 @@ module.exports = { } // Get extension. - const originalExt = path.extname(name) - const existingExts = getExistingExtensions(filePath) - const ext = path.extname(filePath) || existingExts.join(" or ") - const style = overrideStyle[ext] || defaultStyle + const currentExt = path.extname(name) + const actualExt = path.extname(filePath) + const style = overrideStyle[actualExt] || defaultStyle + + const expectedExt = mapTypescriptExtension( + context, + filePath, + actualExt + ) // Verify. - if (style === "always" && ext !== originalExt) { - const fileExtensionToAdd = mapTypescriptExtension( - context, - filePath, - ext - ) + if (style === "always" && currentExt !== expectedExt) { context.report({ node, messageId: "requireExt", - data: { ext: fileExtensionToAdd }, + data: { ext: expectedExt }, fix(fixer) { - if (existingExts.length !== 1) { - return null - } const index = node.range[1] - 1 return fixer.insertTextBeforeRange( [index, index], - fileExtensionToAdd + expectedExt ) }, }) - } else if (style === "never" && ext === originalExt) { + } + + if ( + style === "never" && + currentExt !== "" && + expectedExt !== "" && + currentExt === expectedExt + ) { + const otherExtensions = getExistingExtensions(filePath) + + let fix = fixer => { + const index = name.lastIndexOf(currentExt) + const start = node.range[0] + 1 + index + const end = start + currentExt.length + return fixer.removeRange([start, end]) + } + + if (otherExtensions.length > 1) { + fix = undefined + } + context.report({ node, messageId: "forbidExt", - data: { ext }, - fix(fixer) { - if (existingExts.length !== 1) { - return null - } - const index = name.lastIndexOf(ext) - const start = node.range[0] + 1 + index - const end = start + ext.length - return fixer.removeRange([start, end]) - }, + data: { ext: currentExt }, + fix, }) } } diff --git a/lib/util/check-existence.js b/lib/util/check-existence.js index 40aad74e..a29e1278 100644 --- a/lib/util/check-existence.js +++ b/lib/util/check-existence.js @@ -10,6 +10,21 @@ const getAllowModules = require("./get-allow-modules") const isTypescript = require("./is-typescript") const mapTypescriptExtension = require("../util/map-typescript-extension") +/** + * Reports a missing file from ImportTarget + * @param {RuleContext} context - A context to report. + * @param {import('../util/import-target.js')} target - A list of target information to check. + * @returns {void} + */ +function markMissing(context, target) { + context.report({ + node: target.node, + loc: target.node.loc, + messageId: "notFound", + data: target, + }) +} + /** * Checks whether or not each requirement target exists. * @@ -24,14 +39,26 @@ exports.checkExistence = function checkExistence(context, targets) { const allowed = new Set(getAllowModules(context)) for (const target of targets) { - const missingModule = + if ( target.moduleName != null && !allowed.has(target.moduleName) && target.filePath == null + ) { + markMissing(context, target) + continue + } + + if (target.moduleName != null) { + continue + } + + let missingFile = + target.filePath == null ? false : !exists(target.filePath) - let missingFile = target.moduleName == null && !exists(target.filePath) if (missingFile && isTypescript(context)) { const parsed = path.parse(target.filePath) + const pathWithoutExt = path.resolve(parsed.dir, parsed.name) + const reversedExts = mapTypescriptExtension( context, target.filePath, @@ -39,21 +66,16 @@ exports.checkExistence = function checkExistence(context, targets) { true ) const reversedPaths = reversedExts.map( - reversedExt => - path.resolve(parsed.dir, parsed.name) + reversedExt + reversedExt => pathWithoutExt + reversedExt ) missingFile = reversedPaths.every( reversedPath => target.moduleName == null && !exists(reversedPath) ) } - if (missingModule || missingFile) { - context.report({ - node: target.node, - loc: target.node.loc, - messageId: "notFound", - data: target, - }) + + if (missingFile) { + markMissing(context, target) } } } diff --git a/lib/util/get-try-extensions.js b/lib/util/get-try-extensions.js index 1b7aa50a..ce00803a 100644 --- a/lib/util/get-try-extensions.js +++ b/lib/util/get-try-extensions.js @@ -4,7 +4,7 @@ */ "use strict" -const DEFAULT_VALUE = Object.freeze([".js", ".json", ".node"]) +const DEFAULT_VALUE = Object.freeze([".js", ".json", ".node", ".mjs", ".cjs"]) /** * Gets `tryExtensions` property from a given option object. diff --git a/lib/util/get-tsconfig.js b/lib/util/get-tsconfig.js index cbc202f0..8688a822 100644 --- a/lib/util/get-tsconfig.js +++ b/lib/util/get-tsconfig.js @@ -17,7 +17,7 @@ function getTSConfig(filename) { * Attempts to get the ExtensionMap from the tsconfig of a given file. * * @param {string} filename - The path to the file we need to find the tsconfig.json of - * @returns {import("get-tsconfig").TsConfigResult} + * @returns {import("get-tsconfig").TsConfigResult | null} */ function getTSConfigForFile(filename) { return getTsconfig(filename, "tsconfig.json", fsCache) diff --git a/lib/util/get-typescript-extension-map.js b/lib/util/get-typescript-extension-map.js index 034d6fab..917b7c39 100644 --- a/lib/util/get-typescript-extension-map.js +++ b/lib/util/get-typescript-extension-map.js @@ -32,9 +32,14 @@ const tsConfigMapping = { * @property {Record} backward Convert from javascript to typescript */ +/** + * @param {Record} typescriptExtensionMap A forward extension mapping + * @returns {ExtensionMap} + */ function normalise(typescriptExtensionMap) { const forward = {} const backward = {} + for (const [typescript, javascript] of typescriptExtensionMap) { forward[typescript] = javascript if (!typescript) { @@ -43,6 +48,7 @@ function normalise(typescriptExtensionMap) { backward[javascript] ??= [] backward[javascript].push(typescript) } + return { forward, backward } } @@ -109,7 +115,7 @@ function getFromTSConfigFromFile(filename) { * 8. This returns `PRESERVE_MAPPING`. * * @param {import("eslint").Rule.RuleContext} context - The rule context. - * @returns {string[]} A list of extensions. + * @returns {ExtensionMap} A list of extensions. */ module.exports = function getTypescriptExtensionMap(context) { const filename = diff --git a/lib/util/import-target.js b/lib/util/import-target.js index d16a0db4..72e82b45 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -4,10 +4,53 @@ */ "use strict" +require("util").inspect.defaultOptions.depth = null + const { resolve } = require("path") const isBuiltin = require("is-builtin-module") const resolver = require("enhanced-resolve") +const isTypescript = require("./is-typescript") +const { getTSConfigForFile } = require("./get-tsconfig.js") +const getTypescriptExtensionMap = require("./get-typescript-extension-map") + +function removeTrailWildcard(input) { + if (Array.isArray(input)) { + return [...input].map(removeTrailWildcard) + } + + return input.replace(/[/\\*]+$/, "") +} + +/** + * Initialize this instance. + * @param {import('eslint').Rule.RuleContext} context - The context for the import origin. + * @returns {import('enhanced-resolve').ResolveOptions['alias'] | undefined} + */ +function getTSConfigAliases(context) { + const tsConfig = getTSConfigForFile( + // eslint ^8 + context.physicalFilename ?? + // eslint ^7.28 (deprecated ^8) + context.getPhysicalFilename?.() ?? + // eslint ^8 (if physicalFilename undefined) + context.filename ?? + // eslint ^7 (deprecated ^8) + context.getFilename?.() + ) + + const paths = tsConfig?.config?.compilerOptions?.paths + + if (paths == null) { + return + } + + return Object.entries(paths).map(([name, alias]) => ({ + name: removeTrailWildcard(name), + alias: removeTrailWildcard(alias), + })) +} + /** * @typedef {Object} Options * @property {string[]} [extensions] @@ -19,64 +62,6 @@ const resolver = require("enhanced-resolve") * @typedef { 'import' | 'require' | 'type' } ModuleStyle */ -/** - * Resolve the given id to file paths. - * @param {string} id The id to resolve. - * @param {Options} options The options of node-resolve module. - * @param {ModuleType} moduleType - whether the target was require-ed or imported - * @param {ModuleStyle} moduleStyle - whether the target was require-ed or imported - * @returns {string | null} The resolved path. - */ -function getFilePath(id, options, moduleType, moduleStyle) { - const conditionNames = ["node", "require"] - const { extensions } = options - const mainFields = [] - const mainFiles = [] - - if (moduleStyle === "import") { - conditionNames.push("import") - } - - if (moduleStyle === "type") { - conditionNames.push("import", "types") - } - - if ( - moduleStyle === "require" || - moduleType === "npm" || - moduleType === "node" - ) { - mainFields.push("main") - mainFiles.push("index") - } - - const requireResolve = resolver.create.sync({ - conditionNames, - extensions, - mainFields, - mainFiles, - }) - - const directories = Array.isArray(options.paths) - ? [...options.paths, options.basedir] - : [options.basedir] - - for (const directory of directories) { - try { - const baseDir = resolve(process.cwd(), directory) - return requireResolve(baseDir, id) - } catch { - continue - } - } - - if (moduleType === "absolute" || moduleType === "relative") { - return resolve(options.basedir, id) - } - - return null -} - function trimAfter(string, matcher, count = 1) { return string.split(matcher).slice(0, count).join(matcher) } @@ -87,12 +72,19 @@ function trimAfter(string, matcher, count = 1) { module.exports = class ImportTarget { /** * Initialize this instance. + * @param {import('eslint').Rule.RuleContext} context - The context for the import origin. * @param {import('eslint').Rule.Node} node - The node of a `require()` or a module declaraiton. * @param {string} name - The name of an import target. * @param {Options} options - The options of `node-resolve` module. * @param {'import' | 'require'} moduleType - whether the target was require-ed or imported */ - constructor(node, name, options, moduleType) { + constructor(context, node, name, options, moduleType) { + /** + * The context for the import origin + * @type {import('eslint').Rule.Node} + */ + this.context = context + /** * The node of a `require()` or a module declaraiton. * @type {import('eslint').Rule.Node} @@ -135,12 +127,7 @@ module.exports = class ImportTarget { * If the target is a module and it does not exist then this is `null`. * @type {string | null} */ - this.filePath = getFilePath( - name, - options, - this.moduleType, - this.moduleStyle - ) + this.filePath = this.getFilePath() } /** @@ -234,4 +221,73 @@ module.exports = class ImportTarget { return trimAfter(this.name, "/") } } + + getPaths() { + if (Array.isArray(this.options.paths)) { + return [...this.options.paths, this.options.basedir] + } + + return [this.options.basedir] + } + + /** + * Resolve the given id to file paths. + * @returns {string | null} The resolved path. + */ + getFilePath() { + const conditionNames = ["node", "require"] + const { extensions } = this.options + const mainFields = [] + const mainFiles = [] + + if (this.moduleStyle === "import") { + conditionNames.push("import") + } + + if (this.moduleStyle === "type") { + conditionNames.push("import", "types") + } + + if ( + this.moduleStyle === "require" || + this.moduleType === "npm" || + this.moduleType === "node" + ) { + mainFields.push("main") + mainFiles.push("index") + } + + let alias = undefined + let extensionAlias = undefined + + if (isTypescript(this.context)) { + alias = getTSConfigAliases(this.context) + extensionAlias = getTypescriptExtensionMap(this.context).backward + } + + const requireResolve = resolver.create.sync({ + conditionNames, + extensions, + mainFields, + mainFiles, + + extensionAlias, + alias, + }) + + for (const directory of this.getPaths()) { + try { + const baseDir = resolve(process.cwd(), directory) + return requireResolve(baseDir, this.name) + } catch { + continue + } + } + + if (this.moduleType === "absolute" || this.moduleType === "relative") { + return resolve(this.options.basedir, this.name) + } + + return null + } } diff --git a/lib/util/visit-import.js b/lib/util/visit-import.js index f44149be..69c41599 100644 --- a/lib/util/visit-import.js +++ b/lib/util/visit-import.js @@ -68,7 +68,13 @@ module.exports = function visitImport( // Note: "999" arbitrary to check current/future Node.js version if (name && (includeCore || !isCoreModule(name, "999"))) { targets.push( - new ImportTarget(sourceNode, name, options, "import") + new ImportTarget( + context, + sourceNode, + name, + options, + "import" + ) ) } }, diff --git a/lib/util/visit-require.js b/lib/util/visit-require.js index c7692b9c..99fb3ce2 100644 --- a/lib/util/visit-require.js +++ b/lib/util/visit-require.js @@ -60,7 +60,13 @@ module.exports = function visitRequire( // Note: "999" arbitrary to check current/future Node.js version if (name && (includeCore || !isCoreModule(name, "999"))) { targets.push( - new ImportTarget(targetNode, name, options, "require") + new ImportTarget( + context, + targetNode, + name, + options, + "require" + ) ) } } diff --git a/tests/fixtures/file-extension-in-import/multi.cjs b/tests/fixtures/file-extension-in-import/multi.js similarity index 100% rename from tests/fixtures/file-extension-in-import/multi.cjs rename to tests/fixtures/file-extension-in-import/multi.js diff --git a/tests/fixtures/file-extension-in-import/multi.mjs b/tests/fixtures/file-extension-in-import/multi.json similarity index 100% rename from tests/fixtures/file-extension-in-import/multi.mjs rename to tests/fixtures/file-extension-in-import/multi.json diff --git a/tests/fixtures/no-missing/ts-paths/some/where.ts b/tests/fixtures/no-missing/ts-paths/some/where.ts new file mode 100644 index 00000000..e69de29b diff --git a/tests/fixtures/no-missing/ts-paths/tsconfig.json b/tests/fixtures/no-missing/ts-paths/tsconfig.json new file mode 100644 index 00000000..f832947b --- /dev/null +++ b/tests/fixtures/no-missing/ts-paths/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "paths": { + "@direct": ["./some/where.ts"], + "@wild/*": ["./some/*"] + } + } +} diff --git a/tests/lib/rules/file-extension-in-import.js b/tests/lib/rules/file-extension-in-import.js index d4f986a9..4e2323e7 100644 --- a/tests/lib/rules/file-extension-in-import.js +++ b/tests/lib/rules/file-extension-in-import.js @@ -309,21 +309,28 @@ new RuleTester({ options: ["never", { ".json": "always" }], errors: [{ messageId: "forbidExt", data: { ext: ".mjs" } }], }, + { + // name: '.js has a higher priority than .json' filename: fixture("test.js"), code: "import './multi'", - output: null, + output: "import './multi.js'", options: ["always"], - errors: [ - { messageId: "requireExt", data: { ext: ".cjs or .mjs" } }, - ], + errors: [{ messageId: "requireExt", data: { ext: ".js" } }], + }, + { + filename: fixture("test.js"), + code: "import './multi.js'", + output: null, + options: ["never"], + errors: [{ messageId: "forbidExt", data: { ext: ".js" } }], }, { filename: fixture("test.js"), - code: "import './multi.cjs'", + code: "import './multi.json'", output: null, options: ["never"], - errors: [{ messageId: "forbidExt", data: { ext: ".cjs" } }], + errors: [{ messageId: "forbidExt", data: { ext: ".json" } }], }, // import() diff --git a/tests/lib/rules/no-missing-import.js b/tests/lib/rules/no-missing-import.js index a84911cb..cb1f87dc 100644 --- a/tests/lib/rules/no-missing-import.js +++ b/tests/lib/rules/no-missing-import.js @@ -266,8 +266,21 @@ ruleTester.run("no-missing-import", rule, { code: "import d from './d.js';", }, - // type only tests { + // name: "tsconfig - compilerOptions.paths - direct reference", + filename: fixture("ts-paths/test.ts"), + code: "import before from '@direct';", + env: { node: true }, + }, + { + // name: "tsconfig - compilerOptions.paths - wildcard reference", + filename: fixture("ts-paths/test.ts"), + code: "import before from '@wild/where.js';", + env: { node: true }, + }, + + { + // name: 'Ensure type only packages can be imported', filename: fixture("test.ts"), parser: path.join( __dirname, From 7818a8f18198a2f7b29d72c18d9fac0cb0fdfbc8 Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Sun, 26 Nov 2023 16:27:42 +0000 Subject: [PATCH 06/15] feat: Allow for "allowImportingTsExtensions" (#134) --- lib/util/get-try-extensions.js | 49 +++++++++++++++---- lib/util/get-tsconfig.js | 18 +++++++ lib/util/get-typescript-extension-map.js | 15 ++---- lib/util/import-target.js | 13 +---- .../ts-allow-extension/file.ts | 0 .../ts-allow-extension/tsconfig.json | 6 +++ .../no-missing/ts-allow-extension/file.ts | 0 .../ts-allow-extension/tsconfig.json | 6 +++ tests/lib/rules/file-extension-in-import.js | 11 +++++ tests/lib/rules/no-missing-import.js | 11 +++++ 10 files changed, 98 insertions(+), 31 deletions(-) create mode 100644 tests/fixtures/file-extension-in-import/ts-allow-extension/file.ts create mode 100644 tests/fixtures/file-extension-in-import/ts-allow-extension/tsconfig.json create mode 100644 tests/fixtures/no-missing/ts-allow-extension/file.ts create mode 100644 tests/fixtures/no-missing/ts-allow-extension/tsconfig.json diff --git a/lib/util/get-try-extensions.js b/lib/util/get-try-extensions.js index ce00803a..29c16cad 100644 --- a/lib/util/get-try-extensions.js +++ b/lib/util/get-try-extensions.js @@ -4,7 +4,26 @@ */ "use strict" -const DEFAULT_VALUE = Object.freeze([".js", ".json", ".node", ".mjs", ".cjs"]) +const { getTSConfigForContext } = require("./get-tsconfig") +const isTypescript = require("./is-typescript") + +const DEFAULT_JS_VALUE = Object.freeze([ + ".js", + ".json", + ".node", + ".mjs", + ".cjs", +]) +const DEFAULT_TS_VALUE = Object.freeze([ + ".js", + ".ts", + ".mjs", + ".mts", + ".cjs", + ".cts", + ".json", + ".node", +]) /** * Gets `tryExtensions` property from a given option object. @@ -13,7 +32,7 @@ const DEFAULT_VALUE = Object.freeze([".js", ".json", ".node", ".mjs", ".cjs"]) * @returns {string[]|null} The `tryExtensions` value, or `null`. */ function get(option) { - if (option && option.tryExtensions && Array.isArray(option.tryExtensions)) { + if (Array.isArray(option?.tryExtensions)) { return option.tryExtensions.map(String) } return null @@ -24,19 +43,29 @@ function get(option) { * * 1. This checks `options` property, then returns it if exists. * 2. This checks `settings.n` | `settings.node` property, then returns it if exists. - * 3. This returns `[".js", ".json", ".node"]`. + * 3. This returns `[".js", ".json", ".node", ".mjs", ".cjs"]`. * * @param {RuleContext} context - The rule context. * @returns {string[]} A list of extensions. */ module.exports = function getTryExtensions(context, optionIndex = 0) { - return ( - get(context.options && context.options[optionIndex]) || - get( - context.settings && (context.settings.n || context.settings.node) - ) || - DEFAULT_VALUE - ) + const configured = + get(context.options?.[optionIndex]) ?? + get(context.settings?.n) ?? + get(context.settings?.node) + + if (configured != null) { + return configured + } + + if (isTypescript(context)) { + const tsconfig = getTSConfigForContext(context) + if (tsconfig?.config?.compilerOptions?.allowImportingTsExtensions) { + return DEFAULT_TS_VALUE + } + } + + return DEFAULT_JS_VALUE } module.exports.schema = { diff --git a/lib/util/get-tsconfig.js b/lib/util/get-tsconfig.js index 8688a822..8bb6b5f2 100644 --- a/lib/util/get-tsconfig.js +++ b/lib/util/get-tsconfig.js @@ -23,9 +23,27 @@ function getTSConfigForFile(filename) { return getTsconfig(filename, "tsconfig.json", fsCache) } +/** + * Attempts to get the ExtensionMap from the tsconfig of a given file. + * + * @param {import('eslint').Rule.RuleContext} context - The current eslint context + * @returns {import("get-tsconfig").TsConfigResult | null} + */ +function getTSConfigForContext(context) { + // TODO: remove context.get(PhysicalFilename|Filename) when dropping eslint < v10 + const filename = + context.physicalFilename ?? + context.getPhysicalFilename?.() ?? + context.filename ?? + context.getFilename?.() + + return getTSConfigForFile(filename) +} + module.exports = { getTSConfig, getTSConfigForFile, + getTSConfigForContext, } module.exports.schema = { type: "string" } diff --git a/lib/util/get-typescript-extension-map.js b/lib/util/get-typescript-extension-map.js index 917b7c39..5c6a3b1b 100644 --- a/lib/util/get-typescript-extension-map.js +++ b/lib/util/get-typescript-extension-map.js @@ -1,6 +1,6 @@ "use strict" -const { getTSConfig, getTSConfigForFile } = require("./get-tsconfig") +const { getTSConfig, getTSConfigForContext } = require("./get-tsconfig") const DEFAULT_MAPPING = normalise([ ["", ".js"], @@ -95,11 +95,11 @@ function get(option) { /** * Attempts to get the ExtensionMap from the tsconfig of a given file. * - * @param {string} filename - The filename we're getting from + * @param {import('eslint').Rule.RuleContext} context - The current file context * @returns {ExtensionMap} The `typescriptExtensionMap` value, or `null`. */ -function getFromTSConfigFromFile(filename) { - return getMappingFromTSConfig(getTSConfigForFile(filename)?.config) +function getFromTSConfigFromFile(context) { + return getMappingFromTSConfig(getTSConfigForContext(context)?.config) } /** @@ -118,15 +118,10 @@ function getFromTSConfigFromFile(filename) { * @returns {ExtensionMap} A list of extensions. */ module.exports = function getTypescriptExtensionMap(context) { - const filename = - context.physicalFilename ?? - context.getPhysicalFilename?.() ?? - context.filename ?? - context.getFilename?.() // TODO: remove context.get(PhysicalFilename|Filename) when dropping eslint < v10 return ( get(context.options?.[0]) || get(context.settings?.n ?? context.settings?.node) || - getFromTSConfigFromFile(filename) || + getFromTSConfigFromFile(context) || PRESERVE_MAPPING ) } diff --git a/lib/util/import-target.js b/lib/util/import-target.js index 72e82b45..98e9fd87 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -11,7 +11,7 @@ const isBuiltin = require("is-builtin-module") const resolver = require("enhanced-resolve") const isTypescript = require("./is-typescript") -const { getTSConfigForFile } = require("./get-tsconfig.js") +const { getTSConfigForContext } = require("./get-tsconfig.js") const getTypescriptExtensionMap = require("./get-typescript-extension-map") function removeTrailWildcard(input) { @@ -28,16 +28,7 @@ function removeTrailWildcard(input) { * @returns {import('enhanced-resolve').ResolveOptions['alias'] | undefined} */ function getTSConfigAliases(context) { - const tsConfig = getTSConfigForFile( - // eslint ^8 - context.physicalFilename ?? - // eslint ^7.28 (deprecated ^8) - context.getPhysicalFilename?.() ?? - // eslint ^8 (if physicalFilename undefined) - context.filename ?? - // eslint ^7 (deprecated ^8) - context.getFilename?.() - ) + const tsConfig = getTSConfigForContext(context) const paths = tsConfig?.config?.compilerOptions?.paths diff --git a/tests/fixtures/file-extension-in-import/ts-allow-extension/file.ts b/tests/fixtures/file-extension-in-import/ts-allow-extension/file.ts new file mode 100644 index 00000000..e69de29b diff --git a/tests/fixtures/file-extension-in-import/ts-allow-extension/tsconfig.json b/tests/fixtures/file-extension-in-import/ts-allow-extension/tsconfig.json new file mode 100644 index 00000000..32d0a2a9 --- /dev/null +++ b/tests/fixtures/file-extension-in-import/ts-allow-extension/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "noEmit": true, + "allowImportingTsExtensions": true + } +} diff --git a/tests/fixtures/no-missing/ts-allow-extension/file.ts b/tests/fixtures/no-missing/ts-allow-extension/file.ts new file mode 100644 index 00000000..e69de29b diff --git a/tests/fixtures/no-missing/ts-allow-extension/tsconfig.json b/tests/fixtures/no-missing/ts-allow-extension/tsconfig.json new file mode 100644 index 00000000..32d0a2a9 --- /dev/null +++ b/tests/fixtures/no-missing/ts-allow-extension/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "noEmit": true, + "allowImportingTsExtensions": true + } +} diff --git a/tests/lib/rules/file-extension-in-import.js b/tests/lib/rules/file-extension-in-import.js index 4e2323e7..ff2cb5fb 100644 --- a/tests/lib/rules/file-extension-in-import.js +++ b/tests/lib/rules/file-extension-in-import.js @@ -193,6 +193,17 @@ new RuleTester({ code: "require('./e.js');", settings: { node: { typescriptExtensionMap: tsReactExtensionMap } }, }, + + { + filename: fixture("ts-allow-extension/test.ts"), + code: "require('./file.js');", + env: { node: true }, + }, + { + filename: fixture("ts-allow-extension/test.ts"), + code: "require('./file.ts');", + env: { node: true }, + }, ], invalid: [ { diff --git a/tests/lib/rules/no-missing-import.js b/tests/lib/rules/no-missing-import.js index cb1f87dc..00c577f0 100644 --- a/tests/lib/rules/no-missing-import.js +++ b/tests/lib/rules/no-missing-import.js @@ -290,6 +290,17 @@ ruleTester.run("no-missing-import", rule, { env: { node: true }, }, + { + filename: fixture("ts-allow-extension/test.ts"), + code: "import './file.js';", + env: { node: true }, + }, + { + filename: fixture("ts-allow-extension/test.ts"), + code: "import './file.ts';", + env: { node: true }, + }, + // import() ...(DynamicImportSupported ? [ From f033dcecb3922a66bec5d63087dae42a58b38672 Mon Sep 17 00:00:00 2001 From: scagood <2230835+scagood@users.noreply.github.com> Date: Mon, 11 Dec 2023 09:27:00 +0000 Subject: [PATCH 07/15] feat: Add test for import maps (#147) --- tests/fixtures/no-extraneous/import-map/package.json | 5 +++++ tests/fixtures/no-extraneous/import-map/src/b.js | 0 tests/lib/rules/no-extraneous-import.js | 4 ++++ 3 files changed, 9 insertions(+) create mode 100644 tests/fixtures/no-extraneous/import-map/package.json create mode 100644 tests/fixtures/no-extraneous/import-map/src/b.js diff --git a/tests/fixtures/no-extraneous/import-map/package.json b/tests/fixtures/no-extraneous/import-map/package.json new file mode 100644 index 00000000..0ecd8c90 --- /dev/null +++ b/tests/fixtures/no-extraneous/import-map/package.json @@ -0,0 +1,5 @@ +{ + "imports": { + "#b": "./src/a.js" + } +} diff --git a/tests/fixtures/no-extraneous/import-map/src/b.js b/tests/fixtures/no-extraneous/import-map/src/b.js new file mode 100644 index 00000000..e69de29b diff --git a/tests/lib/rules/no-extraneous-import.js b/tests/lib/rules/no-extraneous-import.js index d63de62d..4829d58f 100644 --- a/tests/lib/rules/no-extraneous-import.js +++ b/tests/lib/rules/no-extraneous-import.js @@ -68,6 +68,10 @@ ruleTester.run("no-extraneous-import", rule, { filename: fixture("optionalDependencies/a.js"), code: "import aaa from 'aaa'", }, + { + filename: fixture("import-map/a.js"), + code: "import '#b'", + }, // missing packages are warned by no-missing-import { From 96389b94fb0adfbcbd8b2ccc021da27c55860d3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=AF=E7=84=B6?= Date: Tue, 19 Dec 2023 11:21:44 +0800 Subject: [PATCH 08/15] Update lib/util/import-target.js Co-authored-by: Sebastian Good <2230835+scagood@users.noreply.github.com> --- lib/util/import-target.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/util/import-target.js b/lib/util/import-target.js index 98e9fd87..ee803530 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -66,7 +66,7 @@ module.exports = class ImportTarget { * @param {import('eslint').Rule.RuleContext} context - The context for the import origin. * @param {import('eslint').Rule.Node} node - The node of a `require()` or a module declaraiton. * @param {string} name - The name of an import target. - * @param {Options} options - The options of `node-resolve` module. + * @param {Options} options - The options of `enhanced-resolve` module. * @param {'import' | 'require'} moduleType - whether the target was require-ed or imported */ constructor(context, node, name, options, moduleType) { From 6ee32ff6512d17577d988f6f91b21e21f3fdb139 Mon Sep 17 00:00:00 2001 From: Sebastian Good <2230835+scagood@users.noreply.github.com> Date: Tue, 2 Jan 2024 14:59:45 +0000 Subject: [PATCH 09/15] test: Add test for n/no-missing-require eslint/use-at-your-own-risk --- tests/lib/rules/no-missing-require.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/lib/rules/no-missing-require.js b/tests/lib/rules/no-missing-require.js index c86b9aa8..3c894874 100644 --- a/tests/lib/rules/no-missing-require.js +++ b/tests/lib/rules/no-missing-require.js @@ -40,6 +40,11 @@ ruleTester.run("no-missing-require", rule, { filename: fixture("test.js"), code: "require('eslint');", }, + { + filename: fixture("test.js"), + code: "require('eslint/use-at-your-own-risk');", + env: { node: true }, + }, { filename: fixture("test.js"), code: "require('./a');", From 1d421ccca0d7150c41cd5e9e63366f37a5febf3d Mon Sep 17 00:00:00 2001 From: Sebastian Good <2230835+scagood@users.noreply.github.com> Date: Tue, 2 Jan 2024 15:06:00 +0000 Subject: [PATCH 10/15] chore: Remove esbuild --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index a2e228ac..682ce3a6 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,6 @@ "@eslint/js": "^8.43.0", "@types/eslint": "^8.44.6", "@typescript-eslint/parser": "^5.60.0", - "esbuild": "^0.18.7", "eslint": "^8", "eslint-config-prettier": "^8.8.0", "eslint-doc-generator": "^1.6.1", From b8aa4f8f9791391acb61a18f1de128ddbe167dc8 Mon Sep 17 00:00:00 2001 From: Sebastian Good <2230835+scagood@users.noreply.github.com> Date: Tue, 2 Jan 2024 15:09:41 +0000 Subject: [PATCH 11/15] feat: Allow for settings.cwd to be used before process.cwd --- lib/util/import-target.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/util/import-target.js b/lib/util/import-target.js index ee803530..1acb7b3f 100644 --- a/lib/util/import-target.js +++ b/lib/util/import-target.js @@ -266,9 +266,10 @@ module.exports = class ImportTarget { alias, }) + const cwd = this.context.settings?.cwd ?? process.cwd() for (const directory of this.getPaths()) { try { - const baseDir = resolve(process.cwd(), directory) + const baseDir = resolve(cwd, directory) return requireResolve(baseDir, this.name) } catch { continue From 83dc99f44307375bd31df85ee68a33c05cc55f70 Mon Sep 17 00:00:00 2001 From: Sebastian Good <2230835+scagood@users.noreply.github.com> Date: Tue, 2 Jan 2024 15:19:57 +0000 Subject: [PATCH 12/15] chore: replace reference to eslint/use-at-your-own-risk --- tests/lib/rules/no-missing-require.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/lib/rules/no-missing-require.js b/tests/lib/rules/no-missing-require.js index 3c894874..0df93a6f 100644 --- a/tests/lib/rules/no-missing-require.js +++ b/tests/lib/rules/no-missing-require.js @@ -42,7 +42,7 @@ ruleTester.run("no-missing-require", rule, { }, { filename: fixture("test.js"), - code: "require('eslint/use-at-your-own-risk');", + code: "require('rimraf/package.json');", env: { node: true }, }, { From 9945cda6dfd3537ae918caf0cf958cb015f3edcf Mon Sep 17 00:00:00 2001 From: Sebastian Good <2230835+scagood@users.noreply.github.com> Date: Tue, 2 Jan 2024 15:20:14 +0000 Subject: [PATCH 13/15] chore: Remove more unused packages --- package.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/package.json b/package.json index 682ce3a6..cefbabb9 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,6 @@ }, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", - "builtins": "^5.0.1", "enhanced-resolve": "^5.15.0", "eslint-plugin-es-x": "^7.5.0", "get-tsconfig": "^4.7.0", @@ -24,7 +23,6 @@ "is-builtin-module": "^3.2.1", "is-core-module": "^2.12.1", "minimatch": "^3.1.2", - "resolve": "^1.22.2", "semver": "^7.5.3" }, "devDependencies": { From 10babca66770d7c48e02acfa32a203faf08199b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=AF=E7=84=B6?= Date: Tue, 9 Jan 2024 13:49:20 +0800 Subject: [PATCH 14/15] chore: update rule test options to flat config --- tests/lib/rules/file-extension-in-import.js | 2 -- tests/lib/rules/no-missing-import.js | 10 +--------- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/tests/lib/rules/file-extension-in-import.js b/tests/lib/rules/file-extension-in-import.js index ff2cb5fb..9c03c343 100644 --- a/tests/lib/rules/file-extension-in-import.js +++ b/tests/lib/rules/file-extension-in-import.js @@ -197,12 +197,10 @@ new RuleTester({ { filename: fixture("ts-allow-extension/test.ts"), code: "require('./file.js');", - env: { node: true }, }, { filename: fixture("ts-allow-extension/test.ts"), code: "require('./file.ts');", - env: { node: true }, }, ], invalid: [ diff --git a/tests/lib/rules/no-missing-import.js b/tests/lib/rules/no-missing-import.js index 00c577f0..2f6ea3f0 100644 --- a/tests/lib/rules/no-missing-import.js +++ b/tests/lib/rules/no-missing-import.js @@ -270,35 +270,27 @@ ruleTester.run("no-missing-import", rule, { // name: "tsconfig - compilerOptions.paths - direct reference", filename: fixture("ts-paths/test.ts"), code: "import before from '@direct';", - env: { node: true }, }, { // name: "tsconfig - compilerOptions.paths - wildcard reference", filename: fixture("ts-paths/test.ts"), code: "import before from '@wild/where.js';", - env: { node: true }, }, { // name: 'Ensure type only packages can be imported', filename: fixture("test.ts"), - parser: path.join( - __dirname, - "../../../node_modules/@typescript-eslint/parser" - ), + languageOptions: { parser: require("@typescript-eslint/parser") }, code: "import type d from 'types-only';", - env: { node: true }, }, { filename: fixture("ts-allow-extension/test.ts"), code: "import './file.js';", - env: { node: true }, }, { filename: fixture("ts-allow-extension/test.ts"), code: "import './file.ts';", - env: { node: true }, }, // import() From 20c1c9a2e1a00f595cff85fcadf7561b2fe31591 Mon Sep 17 00:00:00 2001 From: Sebastian Good <2230835+scagood@users.noreply.github.com> Date: Tue, 9 Jan 2024 09:55:37 +0100 Subject: [PATCH 15/15] fix: incorrect env in tests --- tests/lib/rules/no-missing-require.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/lib/rules/no-missing-require.js b/tests/lib/rules/no-missing-require.js index 0df93a6f..4c291674 100644 --- a/tests/lib/rules/no-missing-require.js +++ b/tests/lib/rules/no-missing-require.js @@ -43,7 +43,6 @@ ruleTester.run("no-missing-require", rule, { { filename: fixture("test.js"), code: "require('rimraf/package.json');", - env: { node: true }, }, { filename: fixture("test.js"), @@ -102,7 +101,6 @@ ruleTester.run("no-missing-require", rule, { { filename: fixture("test.js"), code: "require('./fixtures/no-missing/a');", - env: { node: true }, settings: { node: { resolvePaths: [path.resolve(__dirname, "../../")] }, },