-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
parseDocument.ts
73 lines (68 loc) · 2.09 KB
/
parseDocument.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { extname } from 'path';
import type { CachedContent } from 'graphql-language-service';
import { Range, Position } from 'graphql-language-service';
import { findGraphQLTags, DEFAULT_TAGS } from './findGraphQLTags';
import { Logger } from './Logger';
export const DEFAULT_SUPPORTED_EXTENSIONS = [
'.js',
'.cjs',
'.mjs',
'.es',
'.esm',
'.es6',
'.ts',
'.jsx',
'.tsx',
'.vue',
];
/**
* .graphql is the officially recommended extension for graphql files
*
* .gql and .graphqls are included for compatibility for commonly used extensions
*
* GQL is a registered trademark of Google, and refers to Google Query Language.
* GraphQL Foundation does *not* recommend using this extension or acronym for
* referring to GraphQL.
*/
export const DEFAULT_SUPPORTED_GRAPHQL_EXTENSIONS = [
'.graphql',
'.graphqls',
'.gql',
];
/**
* Helper functions to perform requested services from client/server.
*/
// Check the uri to determine the file type (JavaScript/GraphQL).
// If .js file, either return the parsed query/range or null if GraphQL queries
// are not found.
export function parseDocument(
text: string,
uri: string,
fileExtensions: string[] = DEFAULT_SUPPORTED_EXTENSIONS,
graphQLFileExtensions: string[] = DEFAULT_SUPPORTED_GRAPHQL_EXTENSIONS,
logger: Logger = new Logger(),
): CachedContent[] {
// Check if the text content includes a GraphQLV query.
// If the text doesn't include GraphQL queries, do not proceed.
const ext = extname(uri);
if (fileExtensions.some(e => e === ext)) {
if (DEFAULT_TAGS.some(t => t === text)) {
return [];
}
const templates = findGraphQLTags(text, ext, uri, logger);
return templates.map(({ template, range }) => ({ query: template, range }));
}
if (graphQLFileExtensions.some(e => e === ext)) {
const query = text;
if (!query && query !== '') {
return [];
}
const lines = query.split('\n');
const range = new Range(
new Position(0, 0),
new Position(lines.length - 1, lines[lines.length - 1].length - 1),
);
return [{ query, range }];
}
return [{ query: text, range: null }];
}