relay-compiler 12.0.0 → 13.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (262) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -0
  3. package/cli.js +23 -0
  4. package/index.js +22 -4
  5. package/linux-x64/relay +0 -0
  6. package/macos-arm64/relay +0 -0
  7. package/macos-x64/relay +0 -0
  8. package/package.json +2 -26
  9. package/win-x64/relay.exe +0 -0
  10. package/bin/RelayCompilerBin.js.flow +0 -169
  11. package/bin/RelayCompilerMain.js.flow +0 -515
  12. package/bin/__fixtures__/plugin-module.js.flow +0 -17
  13. package/bin/relay-compiler +0 -19066
  14. package/codegen/CodegenDirectory.js.flow +0 -375
  15. package/codegen/CodegenRunner.js.flow +0 -432
  16. package/codegen/CodegenTypes.js.flow +0 -28
  17. package/codegen/CodegenWatcher.js.flow +0 -254
  18. package/codegen/NormalizationCodeGenerator.js.flow +0 -566
  19. package/codegen/ReaderCodeGenerator.js.flow +0 -512
  20. package/codegen/RelayCodeGenerator.js.flow +0 -85
  21. package/codegen/RelayFileWriter.js.flow +0 -367
  22. package/codegen/SourceControl.js.flow +0 -58
  23. package/codegen/compileRelayArtifacts.js.flow +0 -182
  24. package/codegen/createPrintRequireModuleDependency.js.flow +0 -19
  25. package/codegen/sortObjectByKey.js.flow +0 -25
  26. package/codegen/writeRelayGeneratedFile.js.flow +0 -239
  27. package/core/ASTCache.js.flow +0 -74
  28. package/core/ASTConvert.js.flow +0 -233
  29. package/core/CompilerContext.js.flow +0 -191
  30. package/core/CompilerError.js.flow +0 -255
  31. package/core/DotGraphQLParser.js.flow +0 -39
  32. package/core/GraphQLCompilerProfiler.js.flow +0 -341
  33. package/core/GraphQLDerivedFromMetadata.js.flow +0 -36
  34. package/core/GraphQLWatchmanClient.js.flow +0 -111
  35. package/core/IR.js.flow +0 -326
  36. package/core/IRPrinter.js.flow +0 -478
  37. package/core/IRTransformer.js.flow +0 -377
  38. package/core/IRValidator.js.flow +0 -260
  39. package/core/IRVisitor.js.flow +0 -150
  40. package/core/JSModuleParser.js.flow +0 -24
  41. package/core/RelayCompilerScope.js.flow +0 -199
  42. package/core/RelayFindGraphQLTags.js.flow +0 -119
  43. package/core/RelayGraphQLEnumsGenerator.js.flow +0 -55
  44. package/core/RelayIRTransforms.js.flow +0 -138
  45. package/core/RelayParser.js.flow +0 -1734
  46. package/core/RelaySourceModuleParser.js.flow +0 -135
  47. package/core/Schema.js.flow +0 -2037
  48. package/core/SchemaUtils.js.flow +0 -120
  49. package/core/filterContextForNode.js.flow +0 -50
  50. package/core/getFieldDefinition.js.flow +0 -156
  51. package/core/getIdentifierForArgumentValue.js.flow +0 -49
  52. package/core/getIdentifierForSelection.js.flow +0 -69
  53. package/core/getLiteralArgumentValues.js.flow +0 -32
  54. package/core/getNormalizationOperationName.js.flow +0 -19
  55. package/core/inferRootArgumentDefinitions.js.flow +0 -323
  56. package/index.js.flow +0 -200
  57. package/language/RelayLanguagePluginInterface.js.flow +0 -283
  58. package/language/javascript/FindGraphQLTags.js.flow +0 -137
  59. package/language/javascript/RelayFlowBabelFactories.js.flow +0 -176
  60. package/language/javascript/RelayFlowGenerator.js.flow +0 -1100
  61. package/language/javascript/RelayFlowTypeTransformers.js.flow +0 -184
  62. package/language/javascript/RelayLanguagePluginJavaScript.js.flow +0 -34
  63. package/language/javascript/formatGeneratedModule.js.flow +0 -65
  64. package/lib/bin/RelayCompilerBin.js +0 -143
  65. package/lib/bin/RelayCompilerMain.js +0 -486
  66. package/lib/bin/__fixtures__/plugin-module.js +0 -16
  67. package/lib/codegen/CodegenDirectory.js +0 -336
  68. package/lib/codegen/CodegenRunner.js +0 -433
  69. package/lib/codegen/CodegenTypes.js +0 -11
  70. package/lib/codegen/CodegenWatcher.js +0 -271
  71. package/lib/codegen/NormalizationCodeGenerator.js +0 -480
  72. package/lib/codegen/ReaderCodeGenerator.js +0 -472
  73. package/lib/codegen/RelayCodeGenerator.js +0 -68
  74. package/lib/codegen/RelayFileWriter.js +0 -270
  75. package/lib/codegen/SourceControl.js +0 -60
  76. package/lib/codegen/compileRelayArtifacts.js +0 -157
  77. package/lib/codegen/createPrintRequireModuleDependency.js +0 -19
  78. package/lib/codegen/sortObjectByKey.js +0 -41
  79. package/lib/codegen/writeRelayGeneratedFile.js +0 -208
  80. package/lib/core/ASTCache.js +0 -70
  81. package/lib/core/ASTConvert.js +0 -198
  82. package/lib/core/CompilerContext.js +0 -165
  83. package/lib/core/CompilerError.js +0 -251
  84. package/lib/core/DotGraphQLParser.js +0 -40
  85. package/lib/core/GraphQLCompilerProfiler.js +0 -299
  86. package/lib/core/GraphQLDerivedFromMetadata.js +0 -31
  87. package/lib/core/GraphQLWatchmanClient.js +0 -150
  88. package/lib/core/IR.js +0 -11
  89. package/lib/core/IRPrinter.js +0 -389
  90. package/lib/core/IRTransformer.js +0 -345
  91. package/lib/core/IRValidator.js +0 -226
  92. package/lib/core/IRVisitor.js +0 -45
  93. package/lib/core/JSModuleParser.js +0 -18
  94. package/lib/core/RelayCompilerScope.js +0 -149
  95. package/lib/core/RelayFindGraphQLTags.js +0 -79
  96. package/lib/core/RelayGraphQLEnumsGenerator.js +0 -50
  97. package/lib/core/RelayIRTransforms.js +0 -109
  98. package/lib/core/RelayParser.js +0 -1382
  99. package/lib/core/RelaySourceModuleParser.js +0 -104
  100. package/lib/core/Schema.js +0 -1877
  101. package/lib/core/SchemaUtils.js +0 -98
  102. package/lib/core/filterContextForNode.js +0 -49
  103. package/lib/core/getFieldDefinition.js +0 -145
  104. package/lib/core/getIdentifierForArgumentValue.js +0 -53
  105. package/lib/core/getIdentifierForSelection.js +0 -48
  106. package/lib/core/getLiteralArgumentValues.js +0 -26
  107. package/lib/core/getNormalizationOperationName.js +0 -17
  108. package/lib/core/inferRootArgumentDefinitions.js +0 -351
  109. package/lib/index.js +0 -178
  110. package/lib/language/RelayLanguagePluginInterface.js +0 -14
  111. package/lib/language/javascript/FindGraphQLTags.js +0 -126
  112. package/lib/language/javascript/RelayFlowBabelFactories.js +0 -160
  113. package/lib/language/javascript/RelayFlowGenerator.js +0 -857
  114. package/lib/language/javascript/RelayFlowTypeTransformers.js +0 -119
  115. package/lib/language/javascript/RelayLanguagePluginJavaScript.js +0 -30
  116. package/lib/language/javascript/formatGeneratedModule.js +0 -36
  117. package/lib/reporters/ConsoleReporter.js +0 -61
  118. package/lib/reporters/MultiReporter.js +0 -45
  119. package/lib/reporters/Reporter.js +0 -11
  120. package/lib/runner/Artifacts.js +0 -323
  121. package/lib/runner/BufferedFilesystem.js +0 -261
  122. package/lib/runner/GraphQLASTNodeGroup.js +0 -256
  123. package/lib/runner/GraphQLASTUtils.js +0 -23
  124. package/lib/runner/GraphQLNodeMap.js +0 -81
  125. package/lib/runner/Sources.js +0 -271
  126. package/lib/runner/StrictMap.js +0 -134
  127. package/lib/runner/compileArtifacts.js +0 -39
  128. package/lib/runner/extractAST.js +0 -77
  129. package/lib/runner/getChangedNodeNames.js +0 -82
  130. package/lib/runner/getSchemaInstance.js +0 -30
  131. package/lib/runner/types.js +0 -12
  132. package/lib/transforms/ApplyFragmentArgumentTransform.js +0 -393
  133. package/lib/transforms/ClientExtensionsTransform.js +0 -222
  134. package/lib/transforms/ConnectionTransform.js +0 -643
  135. package/lib/transforms/DeclarativeConnectionMutationTransform.js +0 -221
  136. package/lib/transforms/DeferStreamTransform.js +0 -247
  137. package/lib/transforms/DisallowIdAsAlias.js +0 -41
  138. package/lib/transforms/DisallowTypenameOnRoot.js +0 -53
  139. package/lib/transforms/FieldHandleTransform.js +0 -81
  140. package/lib/transforms/FilterCompilerDirectivesTransform.js +0 -29
  141. package/lib/transforms/FilterDirectivesTransform.js +0 -41
  142. package/lib/transforms/FlattenTransform.js +0 -308
  143. package/lib/transforms/GenerateIDFieldTransform.js +0 -137
  144. package/lib/transforms/GenerateTypeNameTransform.js +0 -155
  145. package/lib/transforms/InlineDataFragmentTransform.js +0 -104
  146. package/lib/transforms/InlineFragmentsTransform.js +0 -63
  147. package/lib/transforms/MaskTransform.js +0 -121
  148. package/lib/transforms/MatchTransform.js +0 -438
  149. package/lib/transforms/ReactFlightComponentTransform.js +0 -161
  150. package/lib/transforms/RefetchableFragmentTransform.js +0 -249
  151. package/lib/transforms/RelayDirectiveTransform.js +0 -85
  152. package/lib/transforms/RequiredFieldTransform.js +0 -373
  153. package/lib/transforms/SkipClientExtensionsTransform.js +0 -49
  154. package/lib/transforms/SkipHandleFieldTransform.js +0 -45
  155. package/lib/transforms/SkipRedundantNodesTransform.js +0 -255
  156. package/lib/transforms/SkipSplitOperationTransform.js +0 -32
  157. package/lib/transforms/SkipUnreachableNodeTransform.js +0 -158
  158. package/lib/transforms/SkipUnusedVariablesTransform.js +0 -74
  159. package/lib/transforms/SplitModuleImportTransform.js +0 -85
  160. package/lib/transforms/TestOperationTransform.js +0 -145
  161. package/lib/transforms/TransformUtils.js +0 -21
  162. package/lib/transforms/ValidateGlobalVariablesTransform.js +0 -91
  163. package/lib/transforms/ValidateRequiredArgumentsTransform.js +0 -118
  164. package/lib/transforms/ValidateServerOnlyDirectivesTransform.js +0 -111
  165. package/lib/transforms/ValidateUnusedVariablesTransform.js +0 -96
  166. package/lib/transforms/query-generators/FetchableQueryGenerator.js +0 -157
  167. package/lib/transforms/query-generators/NodeQueryGenerator.js +0 -166
  168. package/lib/transforms/query-generators/QueryQueryGenerator.js +0 -48
  169. package/lib/transforms/query-generators/ViewerQueryGenerator.js +0 -77
  170. package/lib/transforms/query-generators/index.js +0 -60
  171. package/lib/transforms/query-generators/utils.js +0 -92
  172. package/lib/util/CodeMarker.js +0 -80
  173. package/lib/util/DefaultHandleKey.js +0 -15
  174. package/lib/util/RelayCompilerCache.js +0 -98
  175. package/lib/util/Rollout.js +0 -40
  176. package/lib/util/TimeReporter.js +0 -83
  177. package/lib/util/areEqualArgValues.js +0 -135
  178. package/lib/util/argumentContainsVariables.js +0 -37
  179. package/lib/util/dedupeJSONStringify.js +0 -160
  180. package/lib/util/generateAbstractTypeRefinementKey.js +0 -24
  181. package/lib/util/getDefinitionNodeHash.js +0 -22
  182. package/lib/util/getModuleName.js +0 -32
  183. package/lib/util/joinArgumentDefinitions.js +0 -66
  184. package/lib/util/md5.js +0 -17
  185. package/lib/util/murmurHash.js +0 -86
  186. package/lib/util/nullthrowsOSS.js +0 -23
  187. package/lib/util/orList.js +0 -36
  188. package/lib/util/partitionArray.js +0 -35
  189. package/relay-compiler.js +0 -17
  190. package/relay-compiler.min.js +0 -22
  191. package/reporters/ConsoleReporter.js.flow +0 -81
  192. package/reporters/MultiReporter.js.flow +0 -43
  193. package/reporters/Reporter.js.flow +0 -19
  194. package/runner/Artifacts.js.flow +0 -219
  195. package/runner/BufferedFilesystem.js.flow +0 -194
  196. package/runner/GraphQLASTNodeGroup.js.flow +0 -176
  197. package/runner/GraphQLASTUtils.js.flow +0 -26
  198. package/runner/GraphQLNodeMap.js.flow +0 -55
  199. package/runner/Sources.js.flow +0 -228
  200. package/runner/StrictMap.js.flow +0 -96
  201. package/runner/compileArtifacts.js.flow +0 -76
  202. package/runner/extractAST.js.flow +0 -100
  203. package/runner/getChangedNodeNames.js.flow +0 -48
  204. package/runner/getSchemaInstance.js.flow +0 -36
  205. package/runner/types.js.flow +0 -37
  206. package/transforms/ApplyFragmentArgumentTransform.js.flow +0 -526
  207. package/transforms/ClientExtensionsTransform.js.flow +0 -226
  208. package/transforms/ConnectionTransform.js.flow +0 -859
  209. package/transforms/DeclarativeConnectionMutationTransform.js.flow +0 -250
  210. package/transforms/DeferStreamTransform.js.flow +0 -266
  211. package/transforms/DisallowIdAsAlias.js.flow +0 -48
  212. package/transforms/DisallowTypenameOnRoot.js.flow +0 -45
  213. package/transforms/FieldHandleTransform.js.flow +0 -81
  214. package/transforms/FilterCompilerDirectivesTransform.js.flow +0 -33
  215. package/transforms/FilterDirectivesTransform.js.flow +0 -45
  216. package/transforms/FlattenTransform.js.flow +0 -462
  217. package/transforms/GenerateIDFieldTransform.js.flow +0 -154
  218. package/transforms/GenerateTypeNameTransform.js.flow +0 -167
  219. package/transforms/InlineDataFragmentTransform.js.flow +0 -129
  220. package/transforms/InlineFragmentsTransform.js.flow +0 -73
  221. package/transforms/MaskTransform.js.flow +0 -130
  222. package/transforms/MatchTransform.js.flow +0 -593
  223. package/transforms/ReactFlightComponentTransform.js.flow +0 -198
  224. package/transforms/RefetchableFragmentTransform.js.flow +0 -272
  225. package/transforms/RelayDirectiveTransform.js.flow +0 -99
  226. package/transforms/RequiredFieldTransform.js.flow +0 -419
  227. package/transforms/SkipClientExtensionsTransform.js.flow +0 -57
  228. package/transforms/SkipHandleFieldTransform.js.flow +0 -45
  229. package/transforms/SkipRedundantNodesTransform.js.flow +0 -259
  230. package/transforms/SkipSplitOperationTransform.js.flow +0 -37
  231. package/transforms/SkipUnreachableNodeTransform.js.flow +0 -149
  232. package/transforms/SkipUnusedVariablesTransform.js.flow +0 -59
  233. package/transforms/SplitModuleImportTransform.js.flow +0 -101
  234. package/transforms/TestOperationTransform.js.flow +0 -143
  235. package/transforms/TransformUtils.js.flow +0 -26
  236. package/transforms/ValidateGlobalVariablesTransform.js.flow +0 -81
  237. package/transforms/ValidateRequiredArgumentsTransform.js.flow +0 -131
  238. package/transforms/ValidateServerOnlyDirectivesTransform.js.flow +0 -115
  239. package/transforms/ValidateUnusedVariablesTransform.js.flow +0 -89
  240. package/transforms/query-generators/FetchableQueryGenerator.js.flow +0 -189
  241. package/transforms/query-generators/NodeQueryGenerator.js.flow +0 -219
  242. package/transforms/query-generators/QueryQueryGenerator.js.flow +0 -57
  243. package/transforms/query-generators/ViewerQueryGenerator.js.flow +0 -97
  244. package/transforms/query-generators/index.js.flow +0 -90
  245. package/transforms/query-generators/utils.js.flow +0 -76
  246. package/util/CodeMarker.js.flow +0 -79
  247. package/util/DefaultHandleKey.js.flow +0 -17
  248. package/util/RelayCompilerCache.js.flow +0 -88
  249. package/util/Rollout.js.flow +0 -39
  250. package/util/TimeReporter.js.flow +0 -79
  251. package/util/areEqualArgValues.js.flow +0 -126
  252. package/util/argumentContainsVariables.js.flow +0 -38
  253. package/util/dedupeJSONStringify.js.flow +0 -152
  254. package/util/generateAbstractTypeRefinementKey.js.flow +0 -29
  255. package/util/getDefinitionNodeHash.js.flow +0 -25
  256. package/util/getModuleName.js.flow +0 -39
  257. package/util/joinArgumentDefinitions.js.flow +0 -105
  258. package/util/md5.js.flow +0 -22
  259. package/util/murmurHash.js.flow +0 -94
  260. package/util/nullthrowsOSS.js.flow +0 -25
  261. package/util/orList.js.flow +0 -37
  262. package/util/partitionArray.js.flow +0 -37
@@ -1,191 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- const Profiler = require('./GraphQLCompilerProfiler');
16
-
17
- const invariant = require('invariant');
18
-
19
- const {createUserError} = require('./CompilerError');
20
- // $FlowFixMe[untyped-import] - immutable.js is not flow-typed
21
- const {OrderedMap: ImmutableOrderedMap} = require('immutable');
22
-
23
- import type {Reporter} from '../reporters/Reporter';
24
- import type {Fragment, Location, Root, SplitOperation} from './IR';
25
- import type {Schema} from './Schema';
26
-
27
- export type IRTransform = CompilerContext => CompilerContext;
28
-
29
- export type CompilerContextDocument = Fragment | Root | SplitOperation;
30
-
31
- /**
32
- * An immutable representation of a corpus of documents being compiled together.
33
- * For each document, the context stores the IR and any validation errors.
34
- */
35
- class CompilerContext {
36
- _isMutable: boolean;
37
- // $FlowFixMe[value-as-type]
38
- _documents: ImmutableOrderedMap<string, CompilerContextDocument>;
39
- _withTransform: WeakMap<IRTransform, CompilerContext>;
40
- +_schema: Schema;
41
-
42
- constructor(schema: Schema) {
43
- this._isMutable = false;
44
- this._documents = new ImmutableOrderedMap();
45
- this._withTransform = new WeakMap();
46
- this._schema = schema;
47
- }
48
-
49
- /**
50
- * Returns the documents for the context in the order they were added.
51
- */
52
- documents(): Array<CompilerContextDocument> {
53
- return this._documents.toArray();
54
- }
55
-
56
- forEachDocument(fn: CompilerContextDocument => void): void {
57
- this._documents.forEach(fn);
58
- }
59
-
60
- replace(node: CompilerContextDocument): CompilerContext {
61
- return this._update(
62
- this._documents.update(node.name, existing => {
63
- invariant(
64
- existing,
65
- 'CompilerContext: Expected to replace existing node %s, but ' +
66
- 'one was not found in the context.',
67
- node.name,
68
- );
69
- return node;
70
- }),
71
- );
72
- }
73
-
74
- add(node: CompilerContextDocument): CompilerContext {
75
- return this._update(
76
- this._documents.update(node.name, existing => {
77
- invariant(
78
- !existing,
79
- 'CompilerContext: Duplicate document named `%s`. GraphQL ' +
80
- 'fragments and roots must have unique names.',
81
- node.name,
82
- );
83
- return node;
84
- }),
85
- );
86
- }
87
-
88
- addAll(nodes: $ReadOnlyArray<CompilerContextDocument>): CompilerContext {
89
- return this.withMutations(mutable =>
90
- nodes.reduce((ctx, definition) => ctx.add(definition), mutable),
91
- );
92
- }
93
-
94
- /**
95
- * Apply a list of compiler transforms and return a new compiler context.
96
- */
97
- applyTransforms(
98
- transforms: $ReadOnlyArray<IRTransform>,
99
- reporter?: Reporter,
100
- ): CompilerContext {
101
- return Profiler.run('applyTransforms', () =>
102
- transforms.reduce(
103
- (ctx, transform) => ctx.applyTransform(transform, reporter),
104
- this,
105
- ),
106
- );
107
- }
108
-
109
- /**
110
- * Applies a transform to this context, returning a new context.
111
- *
112
- * This is memoized such that applying the same sequence of transforms will
113
- * not result in duplicated work.
114
- */
115
- applyTransform(transform: IRTransform, reporter?: Reporter): CompilerContext {
116
- let transformed = this._withTransform.get(transform);
117
- if (!transformed) {
118
- const start = process.hrtime();
119
- transformed = Profiler.instrument(transform)(this);
120
- const delta = process.hrtime(start);
121
- const deltaMs = Math.round((delta[0] * 1e9 + delta[1]) / 1e6);
122
- reporter && reporter.reportTime(transform.name, deltaMs);
123
- this._withTransform.set(transform, transformed);
124
- }
125
- return transformed;
126
- }
127
-
128
- get(name: string): ?CompilerContextDocument {
129
- return this._documents.get(name);
130
- }
131
-
132
- getFragment(name: string, referencedFrom?: ?Location): Fragment {
133
- const node = this._documents.get(name);
134
- if (node == null) {
135
- throw createUserError(
136
- `Cannot find fragment '${name}'.`,
137
- referencedFrom != null ? [referencedFrom] : null,
138
- );
139
- } else if (node.kind !== 'Fragment') {
140
- throw createUserError(
141
- `Cannot find fragment '${name}', a document with this name exists ` +
142
- 'but is not a fragment.',
143
- [node.loc, referencedFrom].filter(Boolean),
144
- );
145
- }
146
- return node;
147
- }
148
-
149
- getRoot(name: string): Root {
150
- const node = this._documents.get(name);
151
- if (node == null) {
152
- throw createUserError(`Cannot find root '${name}'.`);
153
- } else if (node.kind !== 'Root') {
154
- throw createUserError(
155
- `Cannot find root '${name}', a document with this name exists but ` +
156
- 'is not a root.',
157
- [node.loc],
158
- );
159
- }
160
- return node;
161
- }
162
-
163
- remove(name: string): CompilerContext {
164
- return this._update(this._documents.delete(name));
165
- }
166
-
167
- withMutations(fn: CompilerContext => CompilerContext): CompilerContext {
168
- const mutableCopy = this._update(this._documents.asMutable());
169
- mutableCopy._isMutable = true;
170
- const result = fn(mutableCopy);
171
- result._isMutable = false;
172
- result._documents = result._documents.asImmutable();
173
- return this._documents === result._documents ? this : result;
174
- }
175
-
176
- _update(
177
- documents: ImmutableOrderedMap<string, CompilerContextDocument>,
178
- ): CompilerContext {
179
- const context = this._isMutable
180
- ? this
181
- : new CompilerContext(this.getSchema());
182
- context._documents = documents;
183
- return context;
184
- }
185
-
186
- getSchema(): Schema {
187
- return this._schema;
188
- }
189
- }
190
-
191
- module.exports = CompilerContext;
@@ -1,255 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- const {GraphQLError} = require('graphql');
16
-
17
- import type {Location} from './IR';
18
- import type {ASTNode, Source, SourceLocation} from 'graphql';
19
-
20
- // Combined results of multiple user errors
21
- export opaque type CombinedUserError: Error = Error;
22
-
23
- // Error describing invalid application code from which the compiler
24
- // can recover, ie which does not prevent processing of other inputs.
25
- export opaque type UserError: Error = GraphQLError;
26
-
27
- // Error describing invalid application code from which the compiler
28
- // *cannot* recover, ie where the validity of subsequent inputs cannot
29
- // be determined. Try to avoid these errors.
30
- export opaque type NonRecoverableUserError: Error = Error;
31
-
32
- // Error describing a bug in the compiler
33
- export opaque type CompilerError: Error = Error;
34
-
35
- /**
36
- * Creates an error describing invalid application code (GraphQL/Schema)
37
- * that must be fixed by the end developer. This should only be used
38
- * for local errors that don't affect processing of other user code.
39
- */
40
- function createUserError(
41
- message: string,
42
- locations?: ?$ReadOnlyArray<Location>,
43
- nodes?: ?$ReadOnlyArray<ASTNode>,
44
- ): UserError {
45
- let messageWithLocations = message;
46
- if (locations != null) {
47
- const printedLocations = printLocations(locations);
48
- messageWithLocations =
49
- printedLocations.length === 0
50
- ? message
51
- : [message, ...printedLocations].join('\n\n') + '\n';
52
- }
53
- return new GraphQLError(messageWithLocations, nodes ?? []);
54
- }
55
-
56
- /**
57
- * Similar to createUserError but for errors that are *not* recoverable:
58
- * the compiler should not continue to process other inputs because their
59
- * validity can't be determined.
60
- */
61
- function createNonRecoverableUserError(
62
- message: string,
63
- locations?: ?$ReadOnlyArray<Location>,
64
- nodes?: ?$ReadOnlyArray<ASTNode>,
65
- ): NonRecoverableUserError {
66
- let messageWithLocations = message;
67
- if (locations != null) {
68
- const printedLocations = printLocations(locations);
69
- messageWithLocations =
70
- printedLocations.length === 0
71
- ? message
72
- : [message, ...printedLocations].join('\n\n') + '\n';
73
- }
74
- const error = new GraphQLError(messageWithLocations, nodes ?? []);
75
- return new Error(error.message);
76
- }
77
-
78
- /**
79
- * Creates an error describing a problem with the compiler itself - such
80
- * as a broken invariant - that must be fixed within the compiler.
81
- */
82
- function createCompilerError(
83
- message: string,
84
- locations?: ?$ReadOnlyArray<Location>,
85
- nodes?: ?$ReadOnlyArray<ASTNode>,
86
- ): CompilerError {
87
- let messageWithLocations = message;
88
- if (locations != null) {
89
- const printedLocations = printLocations(locations);
90
- messageWithLocations =
91
- printedLocations.length === 0
92
- ? message
93
- : [message, ...printedLocations].join('\n\n') + '\n';
94
- }
95
- const error = new GraphQLError(
96
- `Internal Error: ${messageWithLocations}`,
97
- nodes ?? [],
98
- );
99
- return new Error(error.message);
100
- }
101
-
102
- /**
103
- * Iterates over the elements of some iterable value, calling the
104
- * supplied callback for each item with a guard for user errors.
105
- *
106
- * Non-user errors abort the iteration and are instantly rethrown.
107
- * User errors are collected and rethrown at the end, if multiple user errors
108
- * occur, a combined error is thrown.
109
- */
110
- function eachWithCombinedError<T>(iterable: Iterable<T>, fn: T => void): void {
111
- const errors: Array<UserError> = [];
112
- for (const item of iterable) {
113
- try {
114
- fn(item);
115
- } catch (error) {
116
- if (error instanceof GraphQLError) {
117
- errors.push(error);
118
- } else {
119
- throw error;
120
- }
121
- }
122
- }
123
- if (errors.length > 0) {
124
- if (errors.length === 1) {
125
- throw createUserError(
126
- String(errors[0])
127
- .split('\n')
128
- .map((line, index) => (index === 0 ? `- ${line}` : ` ${line}`))
129
- .join('\n'),
130
- );
131
- }
132
- throw createUserError(
133
- `Encountered ${errors.length} errors:\n` +
134
- errors
135
- .map(error =>
136
- String(error)
137
- .split('\n')
138
- .map((line, index) => (index === 0 ? `- ${line}` : ` ${line}`))
139
- .join('\n'),
140
- )
141
- .join('\n'),
142
- );
143
- }
144
- }
145
-
146
- function printLocations(locations: $ReadOnlyArray<Location>): Array<string> {
147
- const printedLocations = [];
148
- for (const location of locations) {
149
- let sourceLocation = location;
150
- while (sourceLocation.kind === 'Derived') {
151
- sourceLocation = sourceLocation.source;
152
- }
153
- switch (sourceLocation.kind) {
154
- case 'Source': {
155
- // source location
156
- const prefix =
157
- sourceLocation === location ? 'Source: ' : 'Source (derived): ';
158
- printedLocations.push(
159
- prefix +
160
- highlightSourceAtLocation(
161
- sourceLocation.source,
162
- getLocation(sourceLocation.source, sourceLocation.start),
163
- ),
164
- );
165
- break;
166
- }
167
- case 'Generated': {
168
- printedLocations.push('Source: (generated)');
169
- break;
170
- }
171
- case 'Unknown': {
172
- printedLocations.push('Source: (unknown)');
173
- break;
174
- }
175
- default: {
176
- (sourceLocation: empty);
177
- throw createCompilerError(
178
- `CompilerError: cannot print location '${String(sourceLocation)}'.`,
179
- );
180
- }
181
- }
182
- }
183
- return printedLocations;
184
- }
185
-
186
- /**
187
- * Render a helpful description of the location of the error in the GraphQL
188
- * Source document.
189
- */
190
- function highlightSourceAtLocation(
191
- source: Source,
192
- location: SourceLocation,
193
- ): string {
194
- const firstLineColumnOffset = source.locationOffset.column - 1;
195
- const body = whitespace(firstLineColumnOffset) + source.body;
196
-
197
- const lineIndex = location.line - 1;
198
- const lineOffset = source.locationOffset.line - 1;
199
- const lineNum = location.line + lineOffset;
200
-
201
- const columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
202
- const columnNum = location.column + columnOffset;
203
-
204
- const lines = body.split(/\r\n|[\n\r]/g);
205
- return (
206
- `${source.name} (${lineNum}:${columnNum})\n` +
207
- printPrefixedLines([
208
- // Lines specified like this: ["prefix", "string"],
209
- [`${lineNum - 1}: `, lines[lineIndex - 1]],
210
- [`${lineNum}: `, lines[lineIndex]],
211
- ['', whitespace(columnNum - 1) + '^'],
212
- [`${lineNum + 1}: `, lines[lineIndex + 1]],
213
- ])
214
- );
215
- }
216
-
217
- function printPrefixedLines(lines: Array<[string, string]>): string {
218
- const existingLines = lines.filter(([_, line]) => line !== undefined);
219
-
220
- let padLen = 0;
221
- for (const [prefix] of existingLines) {
222
- padLen = Math.max(padLen, prefix.length);
223
- }
224
-
225
- return existingLines
226
- .map(([prefix, line]) => lpad(padLen, prefix) + line)
227
- .join('\n');
228
- }
229
-
230
- function whitespace(len: number): string {
231
- return Array(len + 1).join(' ');
232
- }
233
-
234
- function lpad(len: number, str: string): string {
235
- return whitespace(len - str.length) + str;
236
- }
237
-
238
- function getLocation(source: Source, position: number): SourceLocation {
239
- const lineRegexp = /\r\n|[\n\r]/g;
240
- let line = 1;
241
- let column = position + 1;
242
- let match;
243
- while ((match = lineRegexp.exec(source.body)) && match.index < position) {
244
- line += 1;
245
- column = position + 1 - (match.index + match[0].length);
246
- }
247
- return {line, column};
248
- }
249
-
250
- module.exports = {
251
- createCompilerError,
252
- createNonRecoverableUserError,
253
- createUserError,
254
- eachWithCombinedError,
255
- };
@@ -1,39 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- const ASTCache = require('./ASTCache');
16
-
17
- const fs = require('fs');
18
- const path = require('path');
19
-
20
- const {parse, Source} = require('graphql');
21
-
22
- import type {File} from '../codegen/CodegenTypes';
23
- import type {DocumentNode} from 'graphql';
24
-
25
- function parseFile(baseDir: string, file: File): ?DocumentNode {
26
- const text = fs.readFileSync(path.join(baseDir, file.relPath), 'utf8');
27
- return parse(new Source(text, file.relPath), {
28
- experimentalFragmentVariables: true,
29
- });
30
- }
31
-
32
- function getParser(baseDir: string): ASTCache {
33
- return new ASTCache({baseDir, parse: parseFile});
34
- }
35
-
36
- module.exports = {
37
- parseFile,
38
- getParser,
39
- };