@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
89 lines (88 loc) • 3.88 kB
JavaScript
import { gqlPluckFromCodeStringSync, } from '@graphql-tools/graphql-tag-pluck';
import { asArray } from '@graphql-tools/utils';
import { loadOnDiskGraphQLConfig } from './graphql-config.js';
import { REPORT_ON_FIRST_CHARACTER } from './utils.js';
const blocksMap = new Map();
let onDiskConfig;
let onDiskConfigLoaded = false;
const RELEVANT_KEYWORDS = ['gql', 'graphql', 'GraphQL'];
export const processor = {
supportsAutofix: true,
preprocess(code, filePath) {
if (!onDiskConfigLoaded) {
onDiskConfig = loadOnDiskGraphQLConfig(filePath);
onDiskConfigLoaded = true;
}
let keywords = RELEVANT_KEYWORDS;
const pluckConfig = onDiskConfig === null || onDiskConfig === void 0 ? void 0 : onDiskConfig.getProjectForFile(filePath).extensions.pluckConfig;
if (pluckConfig) {
const { modules = [], globalGqlIdentifierName = ['gql', 'graphql'], gqlMagicComment = 'GraphQL', } = pluckConfig;
keywords = [
...new Set([
...modules.map(({ identifier }) => identifier),
...asArray(globalGqlIdentifierName),
gqlMagicComment,
].filter(Boolean)),
];
}
if (keywords.every(keyword => !code.includes(keyword))) {
return [code];
}
try {
const sources = gqlPluckFromCodeStringSync(filePath, code, {
skipIndent: true,
...pluckConfig,
});
const blocks = sources.map(item => ({
filename: 'document.graphql',
text: item.body,
lineOffset: item.locationOffset.line - 1,
// @ts-expect-error -- `index` field exist but show ts error
offset: item.locationOffset.index + 1,
}));
blocksMap.set(filePath, blocks);
return [...blocks, code /* source code must be provided and be last */];
}
catch (e) {
// eslint-disable-next-line no-console
console.error(e);
// in case of parsing error return code as is
return [code];
}
},
postprocess(messages, filePath) {
const blocks = blocksMap.get(filePath) || [];
for (let i = 0; i < blocks.length; i += 1) {
const { lineOffset, offset } = blocks[i];
for (const message of messages[i] || []) {
const isVueOrSvelte = /\.(vue|svelte)$/.test(filePath);
if (isVueOrSvelte) {
// We can't show correct report location because after processing with
// graphql-tag-pluck location is incorrect, disable fixes as well
delete message.endLine;
delete message.endColumn;
delete message.fix;
delete message.suggestions;
Object.assign(message, REPORT_ON_FIRST_CHARACTER);
continue;
}
message.line += lineOffset;
// endLine can not exist if only `loc: { start, column }` was provided to context.report
if (typeof message.endLine === 'number') {
message.endLine += lineOffset;
}
if (message.fix) {
message.fix.range[0] += offset;
message.fix.range[1] += offset;
}
for (const suggestion of message.suggestions || []) {
suggestion.fix.range[0] += offset;
suggestion.fix.range[1] += offset;
}
}
}
const result = messages.flat();
// sort eslint/graphql-eslint messages by line/column
return result.sort((a, b) => a.line - b.line || a.column - b.column);
},
};