vscode-apollo 1.19.3 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/.changeset/README.md +8 -0
  2. package/.changeset/config.json +14 -0
  3. package/.circleci/config.yml +82 -0
  4. package/.eslintrc.js +10 -0
  5. package/.gitattributes +1 -0
  6. package/.github/workflows/build-prs.yml +57 -0
  7. package/.github/workflows/release.yml +114 -0
  8. package/.gitleaks.toml +26 -0
  9. package/.nvmrc +1 -0
  10. package/.prettierrc +5 -0
  11. package/.vscode/launch.json +61 -0
  12. package/.vscode/settings.json +16 -0
  13. package/.vscode/tasks.json +18 -0
  14. package/.vscodeignore +17 -1
  15. package/CHANGELOG.md +178 -1
  16. package/LICENSE +2 -2
  17. package/README.md +9 -9
  18. package/codegen.yml +12 -0
  19. package/images/IconRun.svg +8 -0
  20. package/jest.config.ts +11 -0
  21. package/package.json +102 -22
  22. package/renovate.json +23 -0
  23. package/src/__mocks__/fs.js +3 -0
  24. package/src/__tests__/statusBar.test.ts +8 -7
  25. package/src/debug.ts +2 -5
  26. package/src/env/fetch/fetch.ts +32 -0
  27. package/src/env/fetch/global.ts +30 -0
  28. package/src/env/fetch/index.d.ts +2 -0
  29. package/src/env/fetch/index.ts +2 -0
  30. package/src/env/fetch/url.ts +9 -0
  31. package/src/env/index.ts +4 -0
  32. package/src/env/polyfills/array.ts +17 -0
  33. package/src/env/polyfills/index.ts +2 -0
  34. package/src/env/polyfills/object.ts +7 -0
  35. package/src/env/typescript-utility-types.ts +2 -0
  36. package/src/extension.ts +106 -37
  37. package/src/language-server/__tests__/diagnostics.test.ts +86 -0
  38. package/src/language-server/__tests__/document.test.ts +187 -0
  39. package/src/language-server/__tests__/fileSet.test.ts +46 -0
  40. package/src/language-server/__tests__/fixtures/starwarsSchema.ts +1917 -0
  41. package/src/language-server/config/__tests__/config.ts +128 -0
  42. package/src/language-server/config/__tests__/loadConfig.ts +508 -0
  43. package/src/language-server/config/__tests__/utils.ts +106 -0
  44. package/src/language-server/config/config.ts +219 -0
  45. package/src/language-server/config/index.ts +3 -0
  46. package/src/language-server/config/loadConfig.ts +228 -0
  47. package/src/language-server/config/utils.ts +56 -0
  48. package/src/language-server/diagnostics.ts +109 -0
  49. package/src/language-server/document.ts +277 -0
  50. package/src/language-server/engine/GraphQLDataSource.ts +124 -0
  51. package/src/language-server/engine/index.ts +105 -0
  52. package/src/language-server/engine/operations/frontendUrlRoot.ts +7 -0
  53. package/src/language-server/engine/operations/schemaTagsAndFieldStats.ts +24 -0
  54. package/src/language-server/errors/__tests__/NoMissingClientDirectives.test.ts +220 -0
  55. package/src/language-server/errors/logger.ts +58 -0
  56. package/src/language-server/errors/validation.ts +277 -0
  57. package/src/language-server/fileSet.ts +65 -0
  58. package/src/language-server/format.ts +48 -0
  59. package/src/language-server/graphqlTypes.ts +7176 -0
  60. package/src/language-server/index.ts +29 -0
  61. package/src/language-server/languageProvider.ts +798 -0
  62. package/src/language-server/loadingHandler.ts +64 -0
  63. package/src/language-server/project/base.ts +399 -0
  64. package/src/language-server/project/client.ts +602 -0
  65. package/src/language-server/project/defaultClientSchema.ts +45 -0
  66. package/src/language-server/project/service.ts +48 -0
  67. package/src/language-server/providers/schema/__tests__/file.ts +150 -0
  68. package/src/language-server/providers/schema/base.ts +15 -0
  69. package/src/language-server/providers/schema/endpoint.ts +157 -0
  70. package/src/language-server/providers/schema/engine.ts +197 -0
  71. package/src/language-server/providers/schema/file.ts +167 -0
  72. package/src/language-server/providers/schema/index.ts +75 -0
  73. package/src/language-server/server.ts +252 -0
  74. package/src/language-server/typings/codemirror.d.ts +4 -0
  75. package/src/language-server/typings/graphql.d.ts +27 -0
  76. package/src/language-server/utilities/__tests__/graphql.test.ts +411 -0
  77. package/src/language-server/utilities/__tests__/uri.ts +55 -0
  78. package/src/language-server/utilities/debouncer.ts +8 -0
  79. package/src/language-server/utilities/debug.ts +89 -0
  80. package/src/language-server/utilities/graphql.ts +432 -0
  81. package/src/language-server/utilities/index.ts +3 -0
  82. package/src/language-server/utilities/source.ts +182 -0
  83. package/src/language-server/utilities/uri.ts +19 -0
  84. package/src/language-server/workspace.ts +262 -0
  85. package/src/languageServerClient.ts +19 -12
  86. package/src/messages.ts +84 -0
  87. package/src/statusBar.ts +5 -5
  88. package/src/tools/__tests__/buildServiceDefinition.test.ts +491 -0
  89. package/src/tools/__tests__/snapshotSerializers/astSerializer.ts +19 -0
  90. package/src/tools/__tests__/snapshotSerializers/graphQLTypeSerializer.ts +14 -0
  91. package/src/tools/buildServiceDefinition.ts +241 -0
  92. package/src/tools/index.ts +6 -0
  93. package/src/tools/schema/index.ts +2 -0
  94. package/src/tools/schema/resolveObject.ts +18 -0
  95. package/src/tools/schema/resolverMap.ts +23 -0
  96. package/src/tools/utilities/graphql.ts +22 -0
  97. package/src/tools/utilities/index.ts +3 -0
  98. package/src/tools/utilities/invariant.ts +5 -0
  99. package/src/tools/utilities/predicates.ts +5 -0
  100. package/src/utils.ts +1 -16
  101. package/syntaxes/graphql.js.json +3 -3
  102. package/syntaxes/graphql.json +13 -9
  103. package/syntaxes/graphql.lua.json +51 -0
  104. package/syntaxes/graphql.rb.json +1 -1
  105. package/tsconfig.build.json +4 -0
  106. package/tsconfig.json +20 -7
  107. package/create-server-symlink.js +0 -8
  108. package/lib/debug.d.ts +0 -11
  109. package/lib/debug.d.ts.map +0 -1
  110. package/lib/debug.js +0 -48
  111. package/lib/debug.js.map +0 -1
  112. package/lib/extension.d.ts +0 -4
  113. package/lib/extension.d.ts.map +0 -1
  114. package/lib/extension.js +0 -187
  115. package/lib/extension.js.map +0 -1
  116. package/lib/languageServerClient.d.ts +0 -4
  117. package/lib/languageServerClient.d.ts.map +0 -1
  118. package/lib/languageServerClient.js +0 -57
  119. package/lib/languageServerClient.js.map +0 -1
  120. package/lib/statusBar.d.ts +0 -24
  121. package/lib/statusBar.d.ts.map +0 -1
  122. package/lib/statusBar.js +0 -46
  123. package/lib/statusBar.js.map +0 -1
  124. package/lib/testRunner/index.d.ts +0 -3
  125. package/lib/testRunner/index.d.ts.map +0 -1
  126. package/lib/testRunner/index.js +0 -49
  127. package/lib/testRunner/index.js.map +0 -1
  128. package/lib/testRunner/jest-config.d.ts +0 -14
  129. package/lib/testRunner/jest-config.d.ts.map +0 -1
  130. package/lib/testRunner/jest-config.js +0 -18
  131. package/lib/testRunner/jest-config.js.map +0 -1
  132. package/lib/testRunner/jest-vscode-environment.d.ts +0 -2
  133. package/lib/testRunner/jest-vscode-environment.d.ts.map +0 -1
  134. package/lib/testRunner/jest-vscode-environment.js +0 -19
  135. package/lib/testRunner/jest-vscode-environment.js.map +0 -1
  136. package/lib/testRunner/jest-vscode-framework-setup.d.ts +0 -1
  137. package/lib/testRunner/jest-vscode-framework-setup.d.ts.map +0 -1
  138. package/lib/testRunner/jest-vscode-framework-setup.js +0 -3
  139. package/lib/testRunner/jest-vscode-framework-setup.js.map +0 -1
  140. package/lib/testRunner/vscode-test-script.d.ts +0 -2
  141. package/lib/testRunner/vscode-test-script.d.ts.map +0 -1
  142. package/lib/testRunner/vscode-test-script.js +0 -23
  143. package/lib/testRunner/vscode-test-script.js.map +0 -1
  144. package/lib/utils.d.ts +0 -18
  145. package/lib/utils.d.ts.map +0 -1
  146. package/lib/utils.js +0 -52
  147. package/lib/utils.js.map +0 -1
  148. package/src/testRunner/README.md +0 -23
  149. package/src/testRunner/index.ts +0 -72
  150. package/src/testRunner/jest-config.ts +0 -17
  151. package/src/testRunner/jest-vscode-environment.ts +0 -25
  152. package/src/testRunner/jest-vscode-framework-setup.ts +0 -10
  153. package/src/testRunner/jest.d.ts +0 -37
  154. package/src/testRunner/vscode-test-script.ts +0 -38
  155. package/tsconfig.test.json +0 -4
  156. package/tsconfig.tsbuildinfo +0 -2486
@@ -0,0 +1,220 @@
1
+ import { NoMissingClientDirectives } from "../validation";
2
+ import { GraphQLClientProject } from "../../project/client";
3
+ import { basename } from "path";
4
+
5
+ import { vol } from "memfs";
6
+ import { LoadingHandler } from "../../loadingHandler";
7
+ import { ApolloConfig, ClientConfig } from "../../config";
8
+ import URI from "vscode-uri";
9
+
10
+ const serviceSchema = /* GraphQL */ `
11
+ type Query {
12
+ me: User
13
+ }
14
+
15
+ type User {
16
+ name: String
17
+ friends: [User]
18
+ }
19
+ `;
20
+ const clientSchema = /* GraphQL */ `
21
+ extend type Query {
22
+ isOnline: Boolean
23
+ }
24
+ extend type User {
25
+ isLiked: Boolean
26
+ localUser: User
27
+ }
28
+ `;
29
+ const a = /* GraphQL */ `
30
+ query a {
31
+ isOnline
32
+ me {
33
+ name
34
+ foo # added field missing in service schema to ensure it doesn't throw, see https://github.com/apollographql/vscode-graphql/pull/73
35
+ localUser @client {
36
+ friends {
37
+ isLiked
38
+ }
39
+ }
40
+ friends {
41
+ name
42
+ isLiked
43
+ }
44
+ }
45
+ }
46
+ `;
47
+
48
+ const b = /* GraphQL */ `
49
+ query b {
50
+ me {
51
+ ... {
52
+ isLiked
53
+ }
54
+ ... @client {
55
+ localUser {
56
+ name
57
+ }
58
+ }
59
+ }
60
+ }
61
+ `;
62
+
63
+ const c = /* GraphQL */ `
64
+ query c {
65
+ me {
66
+ ...isLiked
67
+ }
68
+ }
69
+ fragment localUser on User @client {
70
+ localUser {
71
+ name
72
+ }
73
+ }
74
+ fragment isLiked on User {
75
+ isLiked
76
+ ...localUser
77
+ }
78
+ `;
79
+
80
+ const d = /* GraphQL */ `
81
+ fragment isLiked on User {
82
+ isLiked
83
+ }
84
+ query d {
85
+ me {
86
+ ...isLiked
87
+ ...locaUser
88
+ }
89
+ }
90
+ fragment localUser on User @client {
91
+ localUser {
92
+ name
93
+ }
94
+ }
95
+ `;
96
+
97
+ const e = /* GraphQL */ `
98
+ fragment friends on User {
99
+ friends {
100
+ ...isLiked
101
+ ... on User @client {
102
+ localUser {
103
+ name
104
+ }
105
+ }
106
+ }
107
+ }
108
+ query e {
109
+ isOnline @client
110
+ me {
111
+ ...friends
112
+ }
113
+ }
114
+ fragment isLiked on User {
115
+ isLiked
116
+ }
117
+ `;
118
+
119
+ // TODO support inline fragment spreads
120
+ const f = /* GraphQL */ `
121
+ query f {
122
+ me {
123
+ ...isLiked @client
124
+ }
125
+ }
126
+ fragment isLiked on User {
127
+ isLiked
128
+ }
129
+ `;
130
+
131
+ const rootURI = URI.file(process.cwd());
132
+
133
+ const config = new ApolloConfig({
134
+ client: {
135
+ service: {
136
+ name: "server",
137
+ localSchemaFile: "./schema.graphql",
138
+ },
139
+ includes: ["./src/**.graphql"],
140
+ excludes: ["./__tests__"],
141
+ validationRules: [NoMissingClientDirectives],
142
+ },
143
+ engine: {},
144
+ }) as ClientConfig;
145
+
146
+ class MockLoadingHandler implements LoadingHandler {
147
+ handle<T>(_message: string, value: Promise<T>): Promise<T> {
148
+ return value;
149
+ }
150
+ handleSync<T>(_message: string, value: () => T): T {
151
+ return value();
152
+ }
153
+ showError(_message: string): void {}
154
+ }
155
+
156
+ jest.mock("fs");
157
+
158
+ describe("client state", () => {
159
+ beforeEach(() => {
160
+ vol.fromJSON({
161
+ "apollo.config.js": `module.exports = {
162
+ client: {
163
+ service: {
164
+ localSchemaFile: './schema.graphql'
165
+ }
166
+ }
167
+ }`,
168
+ "schema.graphql": serviceSchema,
169
+ "src/client-schema.graphql": clientSchema,
170
+ "src/a.graphql": a,
171
+ "src/b.graphql": b,
172
+ "src/c.graphql": c,
173
+ "src/d.graphql": d,
174
+ "src/e.graphql": e,
175
+ // "src/f.graphql": f,
176
+ });
177
+ });
178
+ afterEach(jest.restoreAllMocks);
179
+
180
+ it("should report validation errors for missing @client directives", async () => {
181
+ const project = new GraphQLClientProject({
182
+ config,
183
+ loadingHandler: new MockLoadingHandler(),
184
+ configFolderURI: rootURI,
185
+ });
186
+
187
+ const errors = Object.create(null);
188
+ project.onDiagnostics(({ diagnostics, uri }) => {
189
+ const path = basename(URI.parse(uri).path);
190
+ diagnostics.forEach(({ error }: any) => {
191
+ if (!errors[path]) errors[path] = [];
192
+ errors[path].push(error);
193
+ });
194
+ });
195
+
196
+ await project.whenReady;
197
+ await project.validate();
198
+
199
+ expect(errors).toMatchInlineSnapshot(`
200
+ Object {
201
+ "a.graphql": Array [
202
+ [GraphQLError: @client directive is missing on local field "isOnline"],
203
+ [GraphQLError: @client directive is missing on local field "isLiked"],
204
+ ],
205
+ "b.graphql": Array [
206
+ [GraphQLError: @client directive is missing on fragment around local fields "isLiked"],
207
+ ],
208
+ "c.graphql": Array [
209
+ [GraphQLError: @client directive is missing on fragment "isLiked" around local fields "isLiked,localUser"],
210
+ ],
211
+ "d.graphql": Array [
212
+ [GraphQLError: @client directive is missing on fragment "isLiked" around local fields "isLiked"],
213
+ ],
214
+ "e.graphql": Array [
215
+ [GraphQLError: @client directive is missing on fragment "isLiked" around local fields "isLiked"],
216
+ ],
217
+ }
218
+ `);
219
+ });
220
+ });
@@ -0,0 +1,58 @@
1
+ import { GraphQLError } from "graphql";
2
+ import path from "path";
3
+
4
+ // ToolError is used for errors that are part of the expected flow
5
+ // and for which a stack trace should not be printed
6
+
7
+ export class ToolError extends Error {
8
+ name: string = "ToolError";
9
+
10
+ constructor(message: string) {
11
+ super(message);
12
+ this.message = message;
13
+ }
14
+ }
15
+
16
+ const isRunningFromXcodeScript = process.env.XCODE_VERSION_ACTUAL;
17
+
18
+ export function logError(error: Error) {
19
+ if (error instanceof ToolError) {
20
+ logErrorMessage(error.message);
21
+ } else if (error instanceof GraphQLError) {
22
+ const fileName = error.source && error.source.name;
23
+ if (error.locations) {
24
+ for (const location of error.locations) {
25
+ logErrorMessage(error.message, fileName, location.line);
26
+ }
27
+ } else {
28
+ logErrorMessage(error.message, fileName);
29
+ }
30
+ } else {
31
+ console.error(error.stack);
32
+ }
33
+ }
34
+
35
+ export function logErrorMessage(
36
+ message: string,
37
+ fileName?: string,
38
+ lineNumber?: number
39
+ ) {
40
+ if (isRunningFromXcodeScript) {
41
+ if (fileName && lineNumber) {
42
+ // Prefixing error output with file name, line and 'error: ',
43
+ // so Xcode will associate it with the right file and display the error inline
44
+ console.error(`${fileName}:${lineNumber}: error: ${message}`);
45
+ } else {
46
+ // Prefixing error output with 'error: ', so Xcode will display it as an error
47
+ console.error(`error: ${message}`);
48
+ }
49
+ } else {
50
+ if (fileName) {
51
+ const truncatedFileName =
52
+ "/" + fileName.split(path.sep).slice(-4).join(path.sep);
53
+ console.error(`...${truncatedFileName}: ${message}`);
54
+ } else {
55
+ console.error(`error: ${message}`);
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,277 @@
1
+ import {
2
+ specifiedRules,
3
+ NoUnusedFragmentsRule,
4
+ GraphQLError,
5
+ FieldNode,
6
+ ValidationContext,
7
+ GraphQLSchema,
8
+ DocumentNode,
9
+ OperationDefinitionNode,
10
+ TypeInfo,
11
+ FragmentDefinitionNode,
12
+ visit,
13
+ visitWithTypeInfo,
14
+ visitInParallel,
15
+ getLocation,
16
+ InlineFragmentNode,
17
+ Kind,
18
+ isObjectType,
19
+ } from "graphql";
20
+
21
+ import { TextEdit } from "vscode-languageserver";
22
+
23
+ import { ToolError, logError } from "./logger";
24
+ import { ValidationRule } from "graphql/validation/ValidationContext";
25
+ import { positionFromSourceLocation } from "../utilities/source";
26
+ import {
27
+ buildExecutionContext,
28
+ ExecutionContext,
29
+ } from "graphql/execution/execute";
30
+ import { hasClientDirective, simpleCollectFields } from "../utilities/graphql";
31
+ import { Debug } from "../utilities";
32
+
33
+ export interface CodeActionInfo {
34
+ message: string;
35
+ edits: TextEdit[];
36
+ }
37
+
38
+ const specifiedRulesToBeRemoved = [NoUnusedFragmentsRule];
39
+
40
+ export const defaultValidationRules: ValidationRule[] = [
41
+ NoAnonymousQueries,
42
+ NoTypenameAlias,
43
+ NoMissingClientDirectives,
44
+ ...specifiedRules.filter((rule) => !specifiedRulesToBeRemoved.includes(rule)),
45
+ ];
46
+
47
+ export function getValidationErrors(
48
+ schema: GraphQLSchema,
49
+ document: DocumentNode,
50
+ fragments?: { [fragmentName: string]: FragmentDefinitionNode },
51
+ rules: ValidationRule[] = defaultValidationRules
52
+ ) {
53
+ const typeInfo = new TypeInfo(schema);
54
+
55
+ // The 4th argument to `ValidationContext` is an `onError` callback. This was
56
+ // introduced by https://github.com/graphql/graphql-js/pull/2074 and first
57
+ // published in graphql@14.5.0. It is meant to replace the `getErrors` method
58
+ // which was previously used. Since we support versions of graphql older than
59
+ // that, it's possible that this callback will not be invoked and we'll need
60
+ // to resort to using `getErrors`. Therefore, although we'll collect errors
61
+ // via this callback, if `getErrors` is present on the context we create,
62
+ // we'll go ahead and use that instead.
63
+ const errors: GraphQLError[] = [];
64
+ const onError = (err: GraphQLError) => errors.push(err);
65
+ const context = new ValidationContext(schema, document, typeInfo, onError);
66
+
67
+ if (fragments) {
68
+ (context as any)._fragments = fragments;
69
+ }
70
+
71
+ const visitors = rules.map((rule) => rule(context));
72
+ // Visit the whole document with each instance of all provided rules.
73
+ visit(document, visitWithTypeInfo(typeInfo, visitInParallel(visitors)));
74
+
75
+ // @ts-ignore
76
+ // `getErrors` is gone in `graphql@15`, but we still support older versions.
77
+ if (typeof context.getErrors === "function") return context.getErrors();
78
+
79
+ // If `getErrors` doesn't exist, we must be on a `graphql@15` or higher,
80
+ // so we'll use the errors we collected via the `onError` callback.
81
+ return errors;
82
+ }
83
+
84
+ export function validateQueryDocument(
85
+ schema: GraphQLSchema,
86
+ document: DocumentNode
87
+ ) {
88
+ try {
89
+ const validationErrors = getValidationErrors(schema, document);
90
+ if (validationErrors && validationErrors.length > 0) {
91
+ for (const error of validationErrors) {
92
+ logError(error);
93
+ }
94
+ return Debug.error("Validation of GraphQL query document failed");
95
+ }
96
+ } catch (e) {
97
+ console.error(e);
98
+ throw e;
99
+ }
100
+ }
101
+
102
+ export function NoAnonymousQueries(context: ValidationContext) {
103
+ return {
104
+ OperationDefinition(node: OperationDefinitionNode) {
105
+ if (!node.name) {
106
+ context.reportError(
107
+ new GraphQLError("Apollo does not support anonymous operations", [
108
+ node,
109
+ ])
110
+ );
111
+ }
112
+ return false;
113
+ },
114
+ };
115
+ }
116
+
117
+ export function NoTypenameAlias(context: ValidationContext) {
118
+ return {
119
+ Field(node: FieldNode) {
120
+ const aliasName = node.alias && node.alias.value;
121
+ if (aliasName == "__typename") {
122
+ context.reportError(
123
+ new GraphQLError(
124
+ "Apollo needs to be able to insert __typename when needed, please do not use it as an alias",
125
+ [node]
126
+ )
127
+ );
128
+ }
129
+ },
130
+ };
131
+ }
132
+
133
+ function hasClientSchema(schema: GraphQLSchema): boolean {
134
+ const query = schema.getQueryType();
135
+ const mutation = schema.getMutationType();
136
+ const subscription = schema.getSubscriptionType();
137
+
138
+ return Boolean(
139
+ (query && query.clientSchema) ||
140
+ (mutation && mutation.clientSchema) ||
141
+ (subscription && subscription.clientSchema)
142
+ );
143
+ }
144
+
145
+ export function NoMissingClientDirectives(context: ValidationContext) {
146
+ const root = context.getDocument();
147
+ const schema = context.getSchema();
148
+ // early return if we don't have any client fields on the schema
149
+ if (!hasClientSchema(schema)) return {};
150
+
151
+ // this isn't really execution context, but it does group the fragments and operations
152
+ // together correctly
153
+ // XXX we have a simplified version of this in @apollo/gateway that we could probably use
154
+ // intead of this
155
+ const executionContext = buildExecutionContext(
156
+ schema,
157
+ root,
158
+ Object.create(null),
159
+ Object.create(null),
160
+ undefined,
161
+ undefined,
162
+ undefined
163
+ );
164
+ function visitor(
165
+ node: FieldNode | InlineFragmentNode | FragmentDefinitionNode
166
+ ) {
167
+ // In cases where we are looking at a FragmentDefinition, there is no parent type
168
+ // but instead, the FragmentDefinition contains the type that we can read from the
169
+ // schema
170
+ const parentType =
171
+ node.kind === Kind.FRAGMENT_DEFINITION
172
+ ? schema.getType(node.typeCondition.name.value)
173
+ : context.getParentType();
174
+
175
+ const fieldDef = context.getFieldDef();
176
+
177
+ // if we don't have a type to check then we can early return
178
+ if (!parentType) return;
179
+
180
+ // here we collect all of the fields on a type that are marked "local"
181
+ const clientFields =
182
+ parentType &&
183
+ isObjectType(parentType) &&
184
+ parentType.clientSchema &&
185
+ parentType.clientSchema.localFields;
186
+
187
+ // XXXX in the case of a fragment spread, the directive could be on the fragment definition
188
+ let clientDirectivePresent = hasClientDirective(node);
189
+
190
+ let message = "@client directive is missing on ";
191
+ let selectsClientFieldSet = false;
192
+ switch (node.kind) {
193
+ case Kind.FIELD:
194
+ // fields are simple because we can just see if the name exists in the local fields
195
+ // array on the parent type
196
+ selectsClientFieldSet = Boolean(
197
+ clientFields && clientFields.includes(fieldDef?.name || "")
198
+ );
199
+ message += `local field "${node.name.value}"`;
200
+ break;
201
+ case Kind.INLINE_FRAGMENT:
202
+ case Kind.FRAGMENT_DEFINITION:
203
+ // XXX why isn't this type checking below?
204
+ if (Array.isArray(executionContext)) break;
205
+
206
+ const fields = simpleCollectFields(
207
+ executionContext as ExecutionContext,
208
+ node.selectionSet,
209
+ Object.create(null),
210
+ Object.create(null)
211
+ );
212
+
213
+ // once we have a list of fields on the fragment, we can compare them
214
+ // to the list of types. The fields within a fragment need to be a
215
+ // subset of the overall local fields types
216
+ const fieldNames = Object.entries(fields).map(([name]) => name);
217
+ selectsClientFieldSet = fieldNames.every(
218
+ (field) => clientFields && clientFields.includes(field)
219
+ );
220
+ message += `fragment ${
221
+ "name" in node ? `"${node.name.value}" ` : ""
222
+ }around local fields "${fieldNames.join(",")}"`;
223
+ break;
224
+ }
225
+
226
+ // if the field's parent is part of the client schema and that type
227
+ // includes a field with the same name as this node, we can see
228
+ // if it has an @client directive to resolve locally
229
+ if (selectsClientFieldSet && !clientDirectivePresent) {
230
+ let extensions: { [key: string]: any } | null = null;
231
+ const name = "name" in node && node.name;
232
+ // TODO support code actions for inline fragments, fragment spreads, and fragment definitions
233
+ if (name && name.loc) {
234
+ let { source, end: locToInsertDirective } = name.loc;
235
+ if (
236
+ "arguments" in node &&
237
+ node.arguments &&
238
+ node.arguments.length !== 0
239
+ ) {
240
+ // must insert directive after field arguments
241
+ const endOfArgs = source.body.indexOf(")", locToInsertDirective);
242
+ locToInsertDirective = endOfArgs + 1;
243
+ }
244
+ const codeAction: CodeActionInfo = {
245
+ message: `Add @client directive to "${name.value}"`,
246
+ edits: [
247
+ TextEdit.insert(
248
+ positionFromSourceLocation(
249
+ source,
250
+ getLocation(source, locToInsertDirective)
251
+ ),
252
+ " @client"
253
+ ),
254
+ ],
255
+ };
256
+ extensions = { codeAction };
257
+ }
258
+
259
+ context.reportError(
260
+ new GraphQLError(message, [node], null, null, null, null, extensions)
261
+ );
262
+ }
263
+
264
+ // if we have selected a client field, no need to continue to recurse
265
+ if (selectsClientFieldSet) {
266
+ return false;
267
+ }
268
+
269
+ return;
270
+ }
271
+ return {
272
+ InlineFragment: visitor,
273
+ FragmentDefinition: visitor,
274
+ Field: visitor,
275
+ // TODO support directives on FragmentSpread
276
+ };
277
+ }
@@ -0,0 +1,65 @@
1
+ import minimatch from "minimatch";
2
+ import glob from "glob";
3
+ import { invariant } from "../tools";
4
+ import URI from "vscode-uri";
5
+ import { normalizeURI } from "./utilities";
6
+ import { resolve } from "path";
7
+
8
+ export class FileSet {
9
+ private rootURI: URI;
10
+ private includes: string[];
11
+ private excludes: string[];
12
+
13
+ constructor({
14
+ rootURI,
15
+ includes,
16
+ excludes,
17
+ configURI,
18
+ }: {
19
+ rootURI: URI;
20
+ includes: string[];
21
+ excludes: string[];
22
+ configURI?: URI;
23
+ }) {
24
+ invariant(rootURI, `Must provide "rootURI".`);
25
+ invariant(includes, `Must provide "includes".`);
26
+ invariant(excludes, `Must provide "excludes".`);
27
+
28
+ this.rootURI = rootURI;
29
+ this.includes = includes;
30
+ this.excludes = excludes;
31
+ }
32
+
33
+ includesFile(filePath: string): boolean {
34
+ const normalizedFilePath = normalizeURI(filePath);
35
+
36
+ return (
37
+ this.includes.some((include) => {
38
+ return minimatch(
39
+ normalizedFilePath,
40
+ resolve(this.rootURI.fsPath, include)
41
+ );
42
+ }) &&
43
+ !this.excludes.some((exclude) => {
44
+ return minimatch(
45
+ normalizedFilePath,
46
+ resolve(this.rootURI.fsPath, exclude)
47
+ );
48
+ })
49
+ );
50
+ }
51
+
52
+ allFiles(): string[] {
53
+ // since glob.sync takes a single pattern, but we allow an array of `includes`, we can join all the
54
+ // `includes` globs into a single pattern and pass to glob.sync. The `ignore` option does, however, allow
55
+ // an array of globs to ignore, so we can pass it in directly
56
+ const joinedIncludes = `{${this.includes.join(",")}}`;
57
+ return glob
58
+ .sync(joinedIncludes, {
59
+ cwd: this.rootURI.fsPath,
60
+ absolute: true,
61
+ ignore: this.excludes,
62
+ })
63
+ .map(normalizeURI);
64
+ }
65
+ }
@@ -0,0 +1,48 @@
1
+ import moment from "moment";
2
+
3
+ export function formatMS(
4
+ ms: number,
5
+ d: number,
6
+ allowMicros = false,
7
+ allowNanos = true
8
+ ) {
9
+ if (ms === 0 || ms === null) return "0";
10
+ const bounds = [
11
+ moment.duration(1, "hour").asMilliseconds(),
12
+ moment.duration(1, "minute").asMilliseconds(),
13
+ moment.duration(1, "second").asMilliseconds(),
14
+ 1,
15
+ 0.001,
16
+ 0.000001,
17
+ ];
18
+ const units = ["hr", "min", "s", "ms", "μs", "ns"];
19
+
20
+ const makeSmallNumbersNice = (f: number) => {
21
+ if (f >= 100) return f.toFixed(0);
22
+ if (f >= 10) return f.toFixed(1);
23
+ if (f === 0) return "0";
24
+ return f.toFixed(2);
25
+ };
26
+
27
+ const bound = bounds.find((b) => b <= ms) || bounds[bounds.length - 1];
28
+ const boundIndex = bounds.indexOf(bound);
29
+ const unit = boundIndex >= 0 ? units[boundIndex] : "";
30
+
31
+ if ((unit === "μs" || unit === "ns") && !allowMicros) {
32
+ return "< 1ms";
33
+ }
34
+ if (unit === "ns" && !allowNanos) {
35
+ return "< 1µs";
36
+ }
37
+ const value =
38
+ typeof d !== "undefined"
39
+ ? (ms / bound).toFixed(d)
40
+ : makeSmallNumbersNice(ms / bound);
41
+
42
+ // if something is rounded to 1000 and not reduced this will catch and reduce it
43
+ if ((value === "1000" || value === "1000.0") && boundIndex >= 1) {
44
+ return `1${units[boundIndex - 1]}`;
45
+ }
46
+
47
+ return `${value}${unit}`;
48
+ }