Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add missing fragment spread warnings #152

Merged
merged 7 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mean-news-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@0no-co/graphqlsp': minor
---

Warn when an import defines a fragment that is unused in the current file
2 changes: 1 addition & 1 deletion packages/example-external-generator/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"name": "@0no-co/graphqlsp",
"schema": "./schema.graphql",
"disableTypegen": true,
"shouldCheckForColocatedFragments": false,
"shouldCheckForColocatedFragments": true,
"template": "graphql",
"templateIsCallExpression": true,
"trackFieldUsage": true
Expand Down
5 changes: 3 additions & 2 deletions packages/graphqlsp/src/ast/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,15 @@ export function findAllTaggedTemplateNodes(
export function findAllCallExpressions(
sourceFile: ts.SourceFile,
template: string,
info: ts.server.PluginCreateInfo
info: ts.server.PluginCreateInfo,
shouldSearchFragments: boolean = true
): {
nodes: Array<ts.NoSubstitutionTemplateLiteral>;
fragments: Array<FragmentDefinitionNode>;
} {
const result: Array<ts.NoSubstitutionTemplateLiteral> = [];
let fragments: Array<FragmentDefinitionNode> = [];
let hasTriedToFindFragments = false;
let hasTriedToFindFragments = shouldSearchFragments ? false : true;
function find(node: ts.Node) {
if (ts.isCallExpression(node) && node.expression.getText() === template) {
if (!hasTriedToFindFragments) {
Expand Down
10 changes: 7 additions & 3 deletions packages/graphqlsp/src/autoComplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ export function getGraphQLCompletions(
const foundToken = getToken(node.arguments[0], cursorPosition);
if (!schema.current || !foundToken) return undefined;

const queryText = node.arguments[0].getText();
const queryText = node.arguments[0].getText().slice(1, -1);
const fragments = getAllFragments(filename, node, info);

text = `${queryText}\m${fragments.map(x => print(x)).join('\n')}`;
text = `${queryText}\n${fragments.map(x => print(x)).join('\n')}`;
cursor = new Cursor(foundToken.line, foundToken.start - 1);
} else if (ts.isTaggedTemplateExpression(node)) {
const { template, tag } = node;
Expand Down Expand Up @@ -151,7 +151,10 @@ export function getSuggestionsInternal(
fragments = parsed.definitions.filter(
x => x.kind === Kind.FRAGMENT_DEFINITION
) as Array<FragmentDefinitionNode>;
} catch (e) {}
} catch (e) {
console.log('[GraphQLSP] ', e);
}
console.log('fraggers', fragments.map(x => print(x)).join('\n'));

let suggestions = getAutocompleteSuggestions(schema, queryText, cursor);
let spreadSuggestions = getSuggestionsForFragmentSpread(
Expand All @@ -161,6 +164,7 @@ export function getSuggestionsInternal(
queryText,
fragments
);
console.log(JSON.stringify(spreadSuggestions, null, 2));

const state =
token.state.kind === 'Invalid' ? token.state.prevState : token.state;
Expand Down
168 changes: 166 additions & 2 deletions packages/graphqlsp/src/checkImports.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import ts from 'typescript/lib/tsserverlibrary';
import { Kind, parse } from 'graphql';
import { FragmentDefinitionNode, Kind, parse } from 'graphql';

import { findAllImports, findAllTaggedTemplateNodes } from './ast';
import {
findAllCallExpressions,
findAllImports,
findAllTaggedTemplateNodes,
getSource,
} from './ast';
import { resolveTemplate } from './ast/resolve';

export const MISSING_FRAGMENT_CODE = 52003;
Expand Down Expand Up @@ -113,3 +118,162 @@ export const checkImportsForFragments = (

return tsDiagnostics;
};

export const getColocatedFragmentNames = (
source: ts.SourceFile,
info: ts.server.PluginCreateInfo
): Record<
string,
{ start: number; length: number; fragments: Array<string> }
> => {
const imports = findAllImports(source);
const importSpecifierToFragments: Record<
string,
{ start: number; length: number; fragments: Array<string> }
> = {};

if (imports.length) {
imports.forEach(imp => {
if (!imp.importClause) return;

if (imp.importClause.name) {
const definitions = info.languageService.getDefinitionAtPosition(
source.fileName,
imp.importClause.name.getStart()
);
if (definitions && definitions.length) {
const [def] = definitions;
if (def.fileName.includes('node_modules')) return;

const externalSource = getSource(info, def.fileName);
if (!externalSource) return;

const fragmentsForImport = getFragmentsInSource(externalSource, info);

const names = fragmentsForImport.map(fragment => fragment.name.value);
if (
names.length &&
!importSpecifierToFragments[imp.moduleSpecifier.getText()]
) {
importSpecifierToFragments[imp.moduleSpecifier.getText()] = {
start: imp.moduleSpecifier.getStart(),
length: imp.moduleSpecifier.getText().length,
fragments: names,
};
} else if (names.length) {
importSpecifierToFragments[
imp.moduleSpecifier.getText()
].fragments =
importSpecifierToFragments[
imp.moduleSpecifier.getText()
].fragments.concat(names);
}
}
}

if (
imp.importClause.namedBindings &&
ts.isNamespaceImport(imp.importClause.namedBindings)
) {
const definitions = info.languageService.getDefinitionAtPosition(
source.fileName,
imp.importClause.namedBindings.getStart()
);
if (definitions && definitions.length) {
const [def] = definitions;
if (def.fileName.includes('node_modules')) return;

const externalSource = getSource(info, def.fileName);
if (!externalSource) return;

const fragmentsForImport = getFragmentsInSource(externalSource, info);
const names = fragmentsForImport.map(fragment => fragment.name.value);
if (
names.length &&
!importSpecifierToFragments[imp.moduleSpecifier.getText()]
) {
importSpecifierToFragments[imp.moduleSpecifier.getText()] = {
start: imp.moduleSpecifier.getStart(),
length: imp.moduleSpecifier.getText().length,
fragments: names,
};
} else if (names.length) {
importSpecifierToFragments[
imp.moduleSpecifier.getText()
].fragments =
importSpecifierToFragments[
imp.moduleSpecifier.getText()
].fragments.concat(names);
}
}
} else if (
imp.importClause.namedBindings &&
ts.isNamedImportBindings(imp.importClause.namedBindings)
) {
imp.importClause.namedBindings.elements.forEach(el => {
const definitions = info.languageService.getDefinitionAtPosition(
source.fileName,
el.getStart()
);
if (definitions && definitions.length) {
const [def] = definitions;
if (def.fileName.includes('node_modules')) return;

const externalSource = getSource(info, def.fileName);
if (!externalSource) return;

const fragmentsForImport = getFragmentsInSource(
externalSource,
info
);
const names = fragmentsForImport.map(
fragment => fragment.name.value
);
if (
names.length &&
!importSpecifierToFragments[imp.moduleSpecifier.getText()]
) {
importSpecifierToFragments[imp.moduleSpecifier.getText()] = {
start: imp.moduleSpecifier.getStart(),
length: imp.moduleSpecifier.getText().length,
fragments: names,
};
} else if (names.length) {
importSpecifierToFragments[
imp.moduleSpecifier.getText()
].fragments =
importSpecifierToFragments[
imp.moduleSpecifier.getText()
].fragments.concat(names);
}
}
});
}
});
}

return importSpecifierToFragments;
};

function getFragmentsInSource(
src: ts.SourceFile,
info: ts.server.PluginCreateInfo
): Array<FragmentDefinitionNode> {
let fragments: Array<FragmentDefinitionNode> = [];
const tagTemplate = info.config.template || 'gql';
const callExpressions = findAllCallExpressions(src, tagTemplate, info, false);

callExpressions.nodes.forEach(node => {
const text = resolveTemplate(node, src.fileName, info).combinedText;
try {
const parsed = parse(text, { noLocation: true });
if (parsed.definitions.every(x => x.kind === Kind.FRAGMENT_DEFINITION)) {
fragments = fragments.concat(parsed.definitions as any);
}
} catch (e) {
return;
}
});

return fragments;
}
77 changes: 70 additions & 7 deletions packages/graphqlsp/src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
OperationDefinitionNode,
parse,
print,
visit,
} from 'graphql';
import { LRUCache } from 'lru-cache';
import fnv1a from '@sindresorhus/fnv1a';
Expand All @@ -20,7 +21,11 @@ import {
import { resolveTemplate } from './ast/resolve';
import { generateTypedDocumentNodes } from './graphql/generateTypes';
import { checkFieldUsageInFile } from './fieldUsage';
import { checkImportsForFragments } from './checkImports';
import {
MISSING_FRAGMENT_CODE,
checkImportsForFragments,
getColocatedFragmentNames,
} from './checkImports';

const clientDirectives = new Set([
'populate',
Expand Down Expand Up @@ -304,15 +309,73 @@ const runDiagnostics = (
messageText: diag.message.split('\n')[0],
}));

const importDiagnostics = isCallExpression
? checkFieldUsageInFile(
if (isCallExpression) {
const usageDiagnostics = checkFieldUsageInFile(
source,
nodes as ts.NoSubstitutionTemplateLiteral[],
info
);

const shouldCheckForColocatedFragments =
info.config.shouldCheckForColocatedFragments ?? false;
let fragmentDiagnostics: ts.Diagnostic[] = [];
console.log(
'[GraphhQLSP] Checking for colocated fragments ',
!!shouldCheckForColocatedFragments
);
if (shouldCheckForColocatedFragments) {
const moduleSpecifierToFragments = getColocatedFragmentNames(
source,
nodes as ts.NoSubstitutionTemplateLiteral[],
info
)
: checkImportsForFragments(source, info);
);
console.log(
'[GraphhQLSP] Checking for colocated fragments ',
JSON.stringify(moduleSpecifierToFragments, null, 2)
);

return [...tsDiagnostics, ...importDiagnostics];
const usedFragments = new Set();
nodes.forEach(node => {
try {
const parsed = parse(node.getText().slice(1, -1), {
noLocation: true,
});
visit(parsed, {
FragmentSpread: node => {
usedFragments.add(node.name.value);
},
});
} catch (e) {}
});

Object.keys(moduleSpecifierToFragments).forEach(moduleSpecifier => {
const {
fragments: fragmentNames,
start,
length,
} = moduleSpecifierToFragments[moduleSpecifier];
const missingFragments = fragmentNames.filter(
x => !usedFragments.has(x)
);
if (missingFragments.length) {
fragmentDiagnostics.push({
file: source,
length,
start,
category: ts.DiagnosticCategory.Warning,
code: MISSING_FRAGMENT_CODE,
messageText: `Unused co-located fragment definition(s) "${missingFragments.join(
', '
)}" in ${moduleSpecifier}`,
});
}
});
}

return [...tsDiagnostics, ...usageDiagnostics, ...fragmentDiagnostics];
} else {
const importDiagnostics = checkImportsForFragments(source, info);
return [...tsDiagnostics, ...importDiagnostics];
}
};

const runTypedDocumentNodes = (
Expand Down
Loading