|
| 1 | +"use strict" |
| 2 | + |
| 3 | +const DEFAULT_MAPPING = normalise([ |
| 4 | + ["", ".js"], |
| 5 | + [".ts", ".js"], |
| 6 | + [".cts", ".cjs"], |
| 7 | + [".mts", ".mjs"], |
| 8 | + [".tsx", ".jsx"], |
| 9 | +]) |
| 10 | + |
| 11 | +/** |
| 12 | + * @typedef {Object} ExtensionMap |
| 13 | + * @property {Record<string, string>} forward Convert from typescript to javascript |
| 14 | + * @property {Record<string, string[]>} backward Convert from javascript to typescript |
| 15 | + */ |
| 16 | + |
| 17 | +function normalise(typescriptExtensionMap) { |
| 18 | + const forward = {} |
| 19 | + const backward = {} |
| 20 | + for (const [typescript, javascript] of typescriptExtensionMap) { |
| 21 | + forward[typescript] = javascript |
| 22 | + if (!typescript) { |
| 23 | + continue |
| 24 | + } |
| 25 | + backward[javascript] ??= [] |
| 26 | + backward[javascript].push(typescript) |
| 27 | + } |
| 28 | + return { forward, backward } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Gets `typescriptExtensionMap` property from a given option object. |
| 33 | + * |
| 34 | + * @param {object|undefined} option - An option object to get. |
| 35 | + * @returns {ExtensionMap} The `typescriptExtensionMap` value, or `null`. |
| 36 | + */ |
| 37 | +function get(option) { |
| 38 | + if ( |
| 39 | + option && |
| 40 | + option.typescriptExtensionMap && |
| 41 | + Array.isArray(option.typescriptExtensionMap) |
| 42 | + ) { |
| 43 | + return normalise(option.typescriptExtensionMap) |
| 44 | + } |
| 45 | + |
| 46 | + return null |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Gets "typescriptExtensionMap" setting. |
| 51 | + * |
| 52 | + * 1. This checks `options` property, then returns it if exists. |
| 53 | + * 2. This checks `settings.n` | `settings.node` property, then returns it if exists. |
| 54 | + * 3. This returns `DEFAULT_MAPPING`. |
| 55 | + * |
| 56 | + * @param {import('eslint').Rule.RuleContext} context - The rule context. |
| 57 | + * @returns {string[]} A list of extensions. |
| 58 | + */ |
| 59 | +module.exports = function getTypescriptExtensionMap(context) { |
| 60 | + return ( |
| 61 | + get(context.options && context.options[0]) || |
| 62 | + get( |
| 63 | + context.settings && (context.settings.n || context.settings.node) |
| 64 | + ) || |
| 65 | + // TODO: Detect tsconfig.json here |
| 66 | + DEFAULT_MAPPING |
| 67 | + ) |
| 68 | +} |
| 69 | + |
| 70 | +module.exports.schema = { |
| 71 | + type: "array", |
| 72 | + items: { |
| 73 | + type: "array", |
| 74 | + prefixItems: [ |
| 75 | + { type: "string", pattern: "^(?:|\\.\\w+)$" }, |
| 76 | + { type: "string", pattern: "^\\.\\w+$" }, |
| 77 | + ], |
| 78 | + additionalItems: false, |
| 79 | + }, |
| 80 | + uniqueItems: true, |
| 81 | +} |
0 commit comments