relay-compiler 11.0.0 → 13.0.0-rc.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (259) hide show
  1. package/cli.js +23 -0
  2. package/index.js +19 -3
  3. package/linux-x64/relay +0 -0
  4. package/macos-x64/relay +0 -0
  5. package/package.json +2 -25
  6. package/win-x64/relay.exe +0 -0
  7. package/bin/RelayCompilerBin.js.flow +0 -169
  8. package/bin/RelayCompilerMain.js.flow +0 -515
  9. package/bin/__fixtures__/plugin-module.js.flow +0 -17
  10. package/bin/relay-compiler +0 -19007
  11. package/codegen/CodegenDirectory.js.flow +0 -375
  12. package/codegen/CodegenRunner.js.flow +0 -432
  13. package/codegen/CodegenTypes.js.flow +0 -28
  14. package/codegen/CodegenWatcher.js.flow +0 -254
  15. package/codegen/NormalizationCodeGenerator.js.flow +0 -571
  16. package/codegen/ReaderCodeGenerator.js.flow +0 -512
  17. package/codegen/RelayCodeGenerator.js.flow +0 -85
  18. package/codegen/RelayFileWriter.js.flow +0 -367
  19. package/codegen/SourceControl.js.flow +0 -58
  20. package/codegen/compileRelayArtifacts.js.flow +0 -182
  21. package/codegen/createPrintRequireModuleDependency.js.flow +0 -21
  22. package/codegen/sortObjectByKey.js.flow +0 -25
  23. package/codegen/writeRelayGeneratedFile.js.flow +0 -239
  24. package/core/ASTCache.js.flow +0 -74
  25. package/core/ASTConvert.js.flow +0 -233
  26. package/core/CompilerContext.js.flow +0 -191
  27. package/core/CompilerError.js.flow +0 -255
  28. package/core/DotGraphQLParser.js.flow +0 -39
  29. package/core/GraphQLCompilerProfiler.js.flow +0 -341
  30. package/core/GraphQLDerivedFromMetadata.js.flow +0 -36
  31. package/core/GraphQLWatchmanClient.js.flow +0 -111
  32. package/core/IR.js.flow +0 -326
  33. package/core/IRPrinter.js.flow +0 -478
  34. package/core/IRTransformer.js.flow +0 -377
  35. package/core/IRValidator.js.flow +0 -260
  36. package/core/IRVisitor.js.flow +0 -150
  37. package/core/JSModuleParser.js.flow +0 -24
  38. package/core/RelayCompilerScope.js.flow +0 -199
  39. package/core/RelayFindGraphQLTags.js.flow +0 -119
  40. package/core/RelayGraphQLEnumsGenerator.js.flow +0 -55
  41. package/core/RelayIRTransforms.js.flow +0 -138
  42. package/core/RelayParser.js.flow +0 -1734
  43. package/core/RelaySourceModuleParser.js.flow +0 -135
  44. package/core/Schema.js.flow +0 -2037
  45. package/core/SchemaUtils.js.flow +0 -120
  46. package/core/filterContextForNode.js.flow +0 -50
  47. package/core/getFieldDefinition.js.flow +0 -156
  48. package/core/getIdentifierForArgumentValue.js.flow +0 -49
  49. package/core/getIdentifierForSelection.js.flow +0 -69
  50. package/core/getLiteralArgumentValues.js.flow +0 -32
  51. package/core/getNormalizationOperationName.js.flow +0 -19
  52. package/core/inferRootArgumentDefinitions.js.flow +0 -323
  53. package/index.js.flow +0 -200
  54. package/language/RelayLanguagePluginInterface.js.flow +0 -283
  55. package/language/javascript/FindGraphQLTags.js.flow +0 -137
  56. package/language/javascript/RelayFlowBabelFactories.js.flow +0 -176
  57. package/language/javascript/RelayFlowGenerator.js.flow +0 -1100
  58. package/language/javascript/RelayFlowTypeTransformers.js.flow +0 -184
  59. package/language/javascript/RelayLanguagePluginJavaScript.js.flow +0 -34
  60. package/language/javascript/formatGeneratedModule.js.flow +0 -65
  61. package/lib/bin/RelayCompilerBin.js +0 -143
  62. package/lib/bin/RelayCompilerMain.js +0 -486
  63. package/lib/bin/__fixtures__/plugin-module.js +0 -16
  64. package/lib/codegen/CodegenDirectory.js +0 -336
  65. package/lib/codegen/CodegenRunner.js +0 -433
  66. package/lib/codegen/CodegenTypes.js +0 -11
  67. package/lib/codegen/CodegenWatcher.js +0 -271
  68. package/lib/codegen/NormalizationCodeGenerator.js +0 -481
  69. package/lib/codegen/ReaderCodeGenerator.js +0 -472
  70. package/lib/codegen/RelayCodeGenerator.js +0 -68
  71. package/lib/codegen/RelayFileWriter.js +0 -270
  72. package/lib/codegen/SourceControl.js +0 -60
  73. package/lib/codegen/compileRelayArtifacts.js +0 -157
  74. package/lib/codegen/createPrintRequireModuleDependency.js +0 -19
  75. package/lib/codegen/sortObjectByKey.js +0 -41
  76. package/lib/codegen/writeRelayGeneratedFile.js +0 -208
  77. package/lib/core/ASTCache.js +0 -70
  78. package/lib/core/ASTConvert.js +0 -198
  79. package/lib/core/CompilerContext.js +0 -165
  80. package/lib/core/CompilerError.js +0 -251
  81. package/lib/core/DotGraphQLParser.js +0 -40
  82. package/lib/core/GraphQLCompilerProfiler.js +0 -299
  83. package/lib/core/GraphQLDerivedFromMetadata.js +0 -31
  84. package/lib/core/GraphQLWatchmanClient.js +0 -150
  85. package/lib/core/IR.js +0 -11
  86. package/lib/core/IRPrinter.js +0 -389
  87. package/lib/core/IRTransformer.js +0 -345
  88. package/lib/core/IRValidator.js +0 -226
  89. package/lib/core/IRVisitor.js +0 -45
  90. package/lib/core/JSModuleParser.js +0 -18
  91. package/lib/core/RelayCompilerScope.js +0 -149
  92. package/lib/core/RelayFindGraphQLTags.js +0 -79
  93. package/lib/core/RelayGraphQLEnumsGenerator.js +0 -50
  94. package/lib/core/RelayIRTransforms.js +0 -109
  95. package/lib/core/RelayParser.js +0 -1382
  96. package/lib/core/RelaySourceModuleParser.js +0 -104
  97. package/lib/core/Schema.js +0 -1877
  98. package/lib/core/SchemaUtils.js +0 -98
  99. package/lib/core/filterContextForNode.js +0 -49
  100. package/lib/core/getFieldDefinition.js +0 -145
  101. package/lib/core/getIdentifierForArgumentValue.js +0 -53
  102. package/lib/core/getIdentifierForSelection.js +0 -48
  103. package/lib/core/getLiteralArgumentValues.js +0 -26
  104. package/lib/core/getNormalizationOperationName.js +0 -17
  105. package/lib/core/inferRootArgumentDefinitions.js +0 -351
  106. package/lib/index.js +0 -178
  107. package/lib/language/RelayLanguagePluginInterface.js +0 -14
  108. package/lib/language/javascript/FindGraphQLTags.js +0 -126
  109. package/lib/language/javascript/RelayFlowBabelFactories.js +0 -160
  110. package/lib/language/javascript/RelayFlowGenerator.js +0 -857
  111. package/lib/language/javascript/RelayFlowTypeTransformers.js +0 -119
  112. package/lib/language/javascript/RelayLanguagePluginJavaScript.js +0 -30
  113. package/lib/language/javascript/formatGeneratedModule.js +0 -36
  114. package/lib/reporters/ConsoleReporter.js +0 -61
  115. package/lib/reporters/MultiReporter.js +0 -45
  116. package/lib/reporters/Reporter.js +0 -11
  117. package/lib/runner/Artifacts.js +0 -323
  118. package/lib/runner/BufferedFilesystem.js +0 -261
  119. package/lib/runner/GraphQLASTNodeGroup.js +0 -256
  120. package/lib/runner/GraphQLASTUtils.js +0 -23
  121. package/lib/runner/GraphQLNodeMap.js +0 -81
  122. package/lib/runner/Sources.js +0 -271
  123. package/lib/runner/StrictMap.js +0 -134
  124. package/lib/runner/compileArtifacts.js +0 -39
  125. package/lib/runner/extractAST.js +0 -77
  126. package/lib/runner/getChangedNodeNames.js +0 -82
  127. package/lib/runner/getSchemaInstance.js +0 -30
  128. package/lib/runner/types.js +0 -12
  129. package/lib/transforms/ApplyFragmentArgumentTransform.js +0 -393
  130. package/lib/transforms/ClientExtensionsTransform.js +0 -221
  131. package/lib/transforms/ConnectionTransform.js +0 -639
  132. package/lib/transforms/DeclarativeConnectionMutationTransform.js +0 -218
  133. package/lib/transforms/DeferStreamTransform.js +0 -246
  134. package/lib/transforms/DisallowIdAsAlias.js +0 -40
  135. package/lib/transforms/DisallowTypenameOnRoot.js +0 -53
  136. package/lib/transforms/FieldHandleTransform.js +0 -79
  137. package/lib/transforms/FilterCompilerDirectivesTransform.js +0 -29
  138. package/lib/transforms/FilterDirectivesTransform.js +0 -41
  139. package/lib/transforms/FlattenTransform.js +0 -306
  140. package/lib/transforms/GenerateIDFieldTransform.js +0 -135
  141. package/lib/transforms/GenerateTypeNameTransform.js +0 -149
  142. package/lib/transforms/InlineDataFragmentTransform.js +0 -100
  143. package/lib/transforms/InlineFragmentsTransform.js +0 -61
  144. package/lib/transforms/MaskTransform.js +0 -117
  145. package/lib/transforms/MatchTransform.js +0 -434
  146. package/lib/transforms/ReactFlightComponentTransform.js +0 -158
  147. package/lib/transforms/RefetchableFragmentTransform.js +0 -249
  148. package/lib/transforms/RelayDirectiveTransform.js +0 -83
  149. package/lib/transforms/RequiredFieldTransform.js +0 -369
  150. package/lib/transforms/SkipClientExtensionsTransform.js +0 -46
  151. package/lib/transforms/SkipHandleFieldTransform.js +0 -44
  152. package/lib/transforms/SkipRedundantNodesTransform.js +0 -254
  153. package/lib/transforms/SkipSplitOperationTransform.js +0 -32
  154. package/lib/transforms/SkipUnreachableNodeTransform.js +0 -158
  155. package/lib/transforms/SkipUnusedVariablesTransform.js +0 -74
  156. package/lib/transforms/SplitModuleImportTransform.js +0 -82
  157. package/lib/transforms/TestOperationTransform.js +0 -144
  158. package/lib/transforms/TransformUtils.js +0 -21
  159. package/lib/transforms/ValidateGlobalVariablesTransform.js +0 -91
  160. package/lib/transforms/ValidateRequiredArgumentsTransform.js +0 -114
  161. package/lib/transforms/ValidateServerOnlyDirectivesTransform.js +0 -108
  162. package/lib/transforms/ValidateUnusedVariablesTransform.js +0 -96
  163. package/lib/transforms/query-generators/FetchableQueryGenerator.js +0 -157
  164. package/lib/transforms/query-generators/NodeQueryGenerator.js +0 -166
  165. package/lib/transforms/query-generators/QueryQueryGenerator.js +0 -48
  166. package/lib/transforms/query-generators/ViewerQueryGenerator.js +0 -77
  167. package/lib/transforms/query-generators/index.js +0 -60
  168. package/lib/transforms/query-generators/utils.js +0 -92
  169. package/lib/util/CodeMarker.js +0 -80
  170. package/lib/util/DefaultHandleKey.js +0 -15
  171. package/lib/util/RelayCompilerCache.js +0 -98
  172. package/lib/util/Rollout.js +0 -40
  173. package/lib/util/TimeReporter.js +0 -83
  174. package/lib/util/areEqualOSS.js +0 -133
  175. package/lib/util/argumentContainsVariables.js +0 -37
  176. package/lib/util/dedupeJSONStringify.js +0 -160
  177. package/lib/util/generateAbstractTypeRefinementKey.js +0 -24
  178. package/lib/util/getDefinitionNodeHash.js +0 -22
  179. package/lib/util/getModuleName.js +0 -32
  180. package/lib/util/joinArgumentDefinitions.js +0 -66
  181. package/lib/util/md5.js +0 -17
  182. package/lib/util/murmurHash.js +0 -86
  183. package/lib/util/nullthrowsOSS.js +0 -23
  184. package/lib/util/orList.js +0 -36
  185. package/lib/util/partitionArray.js +0 -35
  186. package/relay-compiler.js +0 -17
  187. package/relay-compiler.min.js +0 -22
  188. package/reporters/ConsoleReporter.js.flow +0 -81
  189. package/reporters/MultiReporter.js.flow +0 -43
  190. package/reporters/Reporter.js.flow +0 -19
  191. package/runner/Artifacts.js.flow +0 -219
  192. package/runner/BufferedFilesystem.js.flow +0 -194
  193. package/runner/GraphQLASTNodeGroup.js.flow +0 -176
  194. package/runner/GraphQLASTUtils.js.flow +0 -26
  195. package/runner/GraphQLNodeMap.js.flow +0 -55
  196. package/runner/Sources.js.flow +0 -228
  197. package/runner/StrictMap.js.flow +0 -96
  198. package/runner/compileArtifacts.js.flow +0 -76
  199. package/runner/extractAST.js.flow +0 -100
  200. package/runner/getChangedNodeNames.js.flow +0 -48
  201. package/runner/getSchemaInstance.js.flow +0 -36
  202. package/runner/types.js.flow +0 -37
  203. package/transforms/ApplyFragmentArgumentTransform.js.flow +0 -526
  204. package/transforms/ClientExtensionsTransform.js.flow +0 -225
  205. package/transforms/ConnectionTransform.js.flow +0 -855
  206. package/transforms/DeclarativeConnectionMutationTransform.js.flow +0 -247
  207. package/transforms/DeferStreamTransform.js.flow +0 -265
  208. package/transforms/DisallowIdAsAlias.js.flow +0 -47
  209. package/transforms/DisallowTypenameOnRoot.js.flow +0 -45
  210. package/transforms/FieldHandleTransform.js.flow +0 -79
  211. package/transforms/FilterCompilerDirectivesTransform.js.flow +0 -33
  212. package/transforms/FilterDirectivesTransform.js.flow +0 -45
  213. package/transforms/FlattenTransform.js.flow +0 -457
  214. package/transforms/GenerateIDFieldTransform.js.flow +0 -152
  215. package/transforms/GenerateTypeNameTransform.js.flow +0 -161
  216. package/transforms/InlineDataFragmentTransform.js.flow +0 -125
  217. package/transforms/InlineFragmentsTransform.js.flow +0 -71
  218. package/transforms/MaskTransform.js.flow +0 -126
  219. package/transforms/MatchTransform.js.flow +0 -589
  220. package/transforms/ReactFlightComponentTransform.js.flow +0 -195
  221. package/transforms/RefetchableFragmentTransform.js.flow +0 -272
  222. package/transforms/RelayDirectiveTransform.js.flow +0 -97
  223. package/transforms/RequiredFieldTransform.js.flow +0 -415
  224. package/transforms/SkipClientExtensionsTransform.js.flow +0 -54
  225. package/transforms/SkipHandleFieldTransform.js.flow +0 -44
  226. package/transforms/SkipRedundantNodesTransform.js.flow +0 -258
  227. package/transforms/SkipSplitOperationTransform.js.flow +0 -37
  228. package/transforms/SkipUnreachableNodeTransform.js.flow +0 -149
  229. package/transforms/SkipUnusedVariablesTransform.js.flow +0 -59
  230. package/transforms/SplitModuleImportTransform.js.flow +0 -98
  231. package/transforms/TestOperationTransform.js.flow +0 -142
  232. package/transforms/TransformUtils.js.flow +0 -26
  233. package/transforms/ValidateGlobalVariablesTransform.js.flow +0 -81
  234. package/transforms/ValidateRequiredArgumentsTransform.js.flow +0 -127
  235. package/transforms/ValidateServerOnlyDirectivesTransform.js.flow +0 -112
  236. package/transforms/ValidateUnusedVariablesTransform.js.flow +0 -89
  237. package/transforms/query-generators/FetchableQueryGenerator.js.flow +0 -189
  238. package/transforms/query-generators/NodeQueryGenerator.js.flow +0 -219
  239. package/transforms/query-generators/QueryQueryGenerator.js.flow +0 -57
  240. package/transforms/query-generators/ViewerQueryGenerator.js.flow +0 -97
  241. package/transforms/query-generators/index.js.flow +0 -90
  242. package/transforms/query-generators/utils.js.flow +0 -76
  243. package/util/CodeMarker.js.flow +0 -79
  244. package/util/DefaultHandleKey.js.flow +0 -17
  245. package/util/RelayCompilerCache.js.flow +0 -88
  246. package/util/Rollout.js.flow +0 -39
  247. package/util/TimeReporter.js.flow +0 -79
  248. package/util/areEqualOSS.js.flow +0 -123
  249. package/util/argumentContainsVariables.js.flow +0 -38
  250. package/util/dedupeJSONStringify.js.flow +0 -152
  251. package/util/generateAbstractTypeRefinementKey.js.flow +0 -29
  252. package/util/getDefinitionNodeHash.js.flow +0 -25
  253. package/util/getModuleName.js.flow +0 -39
  254. package/util/joinArgumentDefinitions.js.flow +0 -105
  255. package/util/md5.js.flow +0 -22
  256. package/util/murmurHash.js.flow +0 -94
  257. package/util/nullthrowsOSS.js.flow +0 -25
  258. package/util/orList.js.flow +0 -37
  259. package/util/partitionArray.js.flow +0 -37
@@ -1,855 +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-local
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- const IRTransformer = require('../core/IRTransformer');
16
- const RelayParser = require('../core/RelayParser');
17
- const SchemaUtils = require('../core/SchemaUtils');
18
-
19
- const getLiteralArgumentValues = require('../core/getLiteralArgumentValues');
20
-
21
- const {createCompilerError, createUserError} = require('../core/CompilerError');
22
- const {parse} = require('graphql');
23
- const {ConnectionInterface, RelayFeatureFlags} = require('relay-runtime');
24
-
25
- import type CompilerContext from '../core/CompilerContext';
26
- import type {
27
- Argument,
28
- Directive,
29
- Fragment,
30
- Handle,
31
- InlineFragment,
32
- LinkedField,
33
- Root,
34
- Selection,
35
- Variable,
36
- Location,
37
- Defer,
38
- } from '../core/IR';
39
- import type {Schema, CompositeTypeID} from '../core/Schema';
40
- import type {ConnectionMetadata} from 'relay-runtime';
41
-
42
- type Options = {
43
- documentName: string,
44
- // The current path
45
- path: Array<?string>,
46
- // Metadata recorded for @connection fields
47
- connectionMetadata: Array<ConnectionMetadata>,
48
- ...
49
- };
50
-
51
- type ConnectionArguments = {|
52
- handler: ?string,
53
- key: string,
54
- dynamicKey: Variable | null,
55
- filters: ?$ReadOnlyArray<string>,
56
- stream: ?{|
57
- if: ?Argument,
58
- initialCount: ?Argument,
59
- useCustomizedBatch: ?Argument,
60
- label: string,
61
- |},
62
- |};
63
-
64
- const AFTER = 'after';
65
- const BEFORE = 'before';
66
- const FIRST = 'first';
67
- const KEY = 'key';
68
- const LAST = 'last';
69
-
70
- const CONNECTION = 'connection';
71
- const STREAM_CONNECTION = 'stream_connection';
72
- const HANDLER = 'handler';
73
-
74
- /**
75
- * @public
76
- *
77
- * Transforms fields with the `@connection` directive:
78
- * - Verifies that the field type is connection-like.
79
- * - Adds a `handle` property to the field, either the user-provided `handle`
80
- * argument or the default value "connection".
81
- * - Inserts a sub-fragment on the field to ensure that standard connection
82
- * fields are fetched (e.g. cursors, node ids, page info).
83
- */
84
- function connectionTransform(context: CompilerContext): CompilerContext {
85
- return IRTransformer.transform(
86
- context,
87
- {
88
- Fragment: visitFragmentOrRoot,
89
- LinkedField: visitLinkedField,
90
- Root: visitFragmentOrRoot,
91
- },
92
- node => ({
93
- documentName: node.name,
94
- path: [],
95
- connectionMetadata: [],
96
- }),
97
- );
98
- }
99
-
100
- const SCHEMA_EXTENSION = `
101
- directive @connection(
102
- key: String!
103
- filters: [String]
104
- handler: String
105
- dynamicKey_UNSTABLE: String
106
- ) on FIELD
107
-
108
- directive @stream_connection(
109
- key: String!
110
- filters: [String]
111
- handler: String
112
- initial_count: Int!
113
- if: Boolean = true
114
- use_customized_batch: Boolean = false
115
- dynamicKey_UNSTABLE: String
116
- ) on FIELD
117
- `;
118
-
119
- /**
120
- * @internal
121
- */
122
- function visitFragmentOrRoot<N: Fragment | Root>(
123
- node: N,
124
- options: Options,
125
- ): ?N {
126
- const transformedNode = this.traverse(node, options);
127
- const connectionMetadata = options.connectionMetadata;
128
- if (connectionMetadata.length) {
129
- return {
130
- ...transformedNode,
131
- metadata: {
132
- ...transformedNode.metadata,
133
- connection: connectionMetadata,
134
- },
135
- };
136
- }
137
- return transformedNode;
138
- }
139
-
140
- /**
141
- * @internal
142
- */
143
- function visitLinkedField(field: LinkedField, options: Options): LinkedField {
144
- const context: CompilerContext = this.getContext();
145
- const schema = context.getSchema();
146
-
147
- const nullableType = schema.getNullableType(field.type);
148
-
149
- const isPlural = schema.isList(nullableType);
150
- const path = options.path.concat(isPlural ? null : field.alias || field.name);
151
- let transformedField: LinkedField = this.traverse(field, {
152
- ...options,
153
- path,
154
- });
155
- const connectionDirective = field.directives.find(
156
- directive =>
157
- directive.name === CONNECTION || directive.name === STREAM_CONNECTION,
158
- );
159
- if (!connectionDirective) {
160
- return transformedField;
161
- }
162
- if (!schema.isObject(nullableType) && !schema.isInterface(nullableType)) {
163
- throw new createUserError(
164
- `@${connectionDirective.name} used on invalid field '${field.name}'. ` +
165
- 'Expected the return type to be a non-plural interface or object, ' +
166
- `got '${schema.getTypeString(field.type)}'.`,
167
- [transformedField.loc],
168
- );
169
- }
170
-
171
- validateConnectionSelection(transformedField);
172
- validateConnectionType(
173
- schema,
174
- transformedField,
175
- schema.assertCompositeType(nullableType),
176
- connectionDirective,
177
- );
178
-
179
- const connectionArguments = buildConnectionArguments(
180
- transformedField,
181
- connectionDirective,
182
- );
183
-
184
- const connectionMetadata = buildConnectionMetadata(
185
- transformedField,
186
- path,
187
- connectionArguments.stream != null,
188
- );
189
- options.connectionMetadata.push(connectionMetadata);
190
-
191
- const handle: Handle = {
192
- name: connectionArguments.handler ?? CONNECTION,
193
- key: connectionArguments.key,
194
- dynamicKey: connectionArguments.dynamicKey,
195
- filters: connectionArguments.filters,
196
- };
197
-
198
- const {direction} = connectionMetadata;
199
- if (direction != null) {
200
- const selections = transformConnectionSelections(
201
- this.getContext(),
202
- transformedField,
203
- schema.assertCompositeType(nullableType),
204
- direction,
205
- connectionArguments,
206
- connectionDirective.loc,
207
- options.documentName,
208
- );
209
- transformedField = {
210
- ...transformedField,
211
- selections,
212
- };
213
- }
214
- return {
215
- ...transformedField,
216
- directives: transformedField.directives.filter(
217
- directive => directive !== connectionDirective,
218
- ),
219
- connection: true,
220
- handles: transformedField.handles
221
- ? [...transformedField.handles, handle]
222
- : [handle],
223
- };
224
- }
225
-
226
- function buildConnectionArguments(
227
- field: LinkedField,
228
- connectionDirective: Directive,
229
- ): ConnectionArguments {
230
- const {
231
- handler,
232
- key,
233
- label,
234
- filters: literalFilters,
235
- } = getLiteralArgumentValues(connectionDirective.args);
236
- if (handler != null && typeof handler !== 'string') {
237
- const handleArg = connectionDirective.args.find(
238
- arg => arg.name === 'handler',
239
- );
240
- throw createUserError(
241
- `Expected the ${HANDLER} argument to @${connectionDirective.name} to ` +
242
- `be a string literal for field ${field.name}.`,
243
- [handleArg?.value?.loc ?? connectionDirective.loc],
244
- );
245
- }
246
- if (typeof key !== 'string') {
247
- const keyArg = connectionDirective.args.find(arg => arg.name === 'key');
248
- throw createUserError(
249
- `Expected the ${KEY} argument to @${connectionDirective.name} to be a ` +
250
- `string literal for field ${field.name}.`,
251
- [keyArg?.value?.loc ?? connectionDirective.loc],
252
- );
253
- }
254
- const postfix = field.alias || field.name;
255
- if (!key.endsWith('_' + postfix)) {
256
- const keyArg = connectionDirective.args.find(arg => arg.name === 'key');
257
- throw createUserError(
258
- `Expected the ${KEY} argument to @${connectionDirective.name} to be of ` +
259
- `form <SomeName>_${postfix}, got '${key}'. ` +
260
- 'For a detailed explanation, check out ' +
261
- 'https://relay.dev/docs/en/pagination-container#connection',
262
- [keyArg?.value?.loc ?? connectionDirective.loc],
263
- );
264
- }
265
- if (
266
- literalFilters != null &&
267
- (!Array.isArray(literalFilters) ||
268
- literalFilters.some(filter => typeof filter !== 'string'))
269
- ) {
270
- const filtersArg = connectionDirective.args.find(
271
- arg => arg.name === 'filters',
272
- );
273
- throw createUserError(
274
- `Expected the 'filters' argument to @${connectionDirective.name} to be ` +
275
- 'a string literal.',
276
- [filtersArg?.value?.loc ?? connectionDirective.loc],
277
- );
278
- }
279
-
280
- let filters = literalFilters;
281
- if (filters == null) {
282
- const generatedFilters = field.args
283
- .filter(
284
- arg =>
285
- !ConnectionInterface.isConnectionCall({
286
- name: arg.name,
287
- value: null,
288
- }),
289
- )
290
- .map(arg => arg.name);
291
- filters = generatedFilters.length !== 0 ? generatedFilters : null;
292
- }
293
-
294
- let stream = null;
295
- if (connectionDirective.name === STREAM_CONNECTION) {
296
- const initialCountArg = connectionDirective.args.find(
297
- arg => arg.name === 'initial_count',
298
- );
299
- const useCustomizedBatchArg = connectionDirective.args.find(
300
- arg => arg.name === 'use_customized_batch',
301
- );
302
- const ifArg = connectionDirective.args.find(arg => arg.name === 'if');
303
- stream = {
304
- if: ifArg,
305
- initialCount: initialCountArg,
306
- useCustomizedBatch: useCustomizedBatchArg,
307
- label: key,
308
- };
309
- }
310
-
311
- const dynamicKeyArg = connectionDirective.args.find(
312
- arg => arg.name === 'dynamicKey_UNSTABLE',
313
- );
314
- let dynamicKey: Variable | null = null;
315
- if (dynamicKeyArg != null) {
316
- if (
317
- RelayFeatureFlags.ENABLE_VARIABLE_CONNECTION_KEY &&
318
- dynamicKeyArg.value.kind === 'Variable'
319
- ) {
320
- dynamicKey = dynamicKeyArg.value;
321
- } else {
322
- throw createUserError(
323
- `Unsupported 'dynamicKey_UNSTABLE' argument to @${connectionDirective.name}. This argument is only valid when the feature flag is enabled and ` +
324
- 'the variable must be a variable',
325
- [connectionDirective.loc],
326
- );
327
- }
328
- }
329
-
330
- return {
331
- handler,
332
- key,
333
- dynamicKey,
334
- filters: (filters: $FlowFixMe),
335
- stream,
336
- };
337
- }
338
-
339
- function buildConnectionMetadata(
340
- field: LinkedField,
341
- path: Array<?string>,
342
- stream: boolean,
343
- ): ConnectionMetadata {
344
- const pathHasPlural = path.includes(null);
345
- const firstArg = findArg(field, FIRST);
346
- const lastArg = findArg(field, LAST);
347
- let direction = null;
348
- let countArg = null;
349
- let cursorArg = null;
350
- if (firstArg && !lastArg) {
351
- direction = 'forward';
352
- countArg = firstArg;
353
- cursorArg = findArg(field, AFTER);
354
- } else if (lastArg && !firstArg) {
355
- direction = 'backward';
356
- countArg = lastArg;
357
- cursorArg = findArg(field, BEFORE);
358
- } else if (lastArg && firstArg) {
359
- direction = 'bidirectional';
360
- // TODO(T26511885) Maybe add connection metadata to this case
361
- }
362
- const countVariable =
363
- countArg && countArg.value.kind === 'Variable'
364
- ? countArg.value.variableName
365
- : null;
366
- const cursorVariable =
367
- cursorArg && cursorArg.value.kind === 'Variable'
368
- ? cursorArg.value.variableName
369
- : null;
370
- if (stream) {
371
- return {
372
- count: countVariable,
373
- cursor: cursorVariable,
374
- direction,
375
- path: pathHasPlural ? null : (path: $FlowFixMe),
376
- stream: true,
377
- };
378
- }
379
- return {
380
- count: countVariable,
381
- cursor: cursorVariable,
382
- direction,
383
- path: pathHasPlural ? null : (path: $FlowFixMe),
384
- };
385
- }
386
-
387
- /**
388
- * @internal
389
- *
390
- * Transforms the selections on a connection field, generating fields necessary
391
- * for pagination (edges.cursor, pageInfo, etc) and adding/merging them with
392
- * existing selections.
393
- */
394
- function transformConnectionSelections(
395
- context: CompilerContext,
396
- field: LinkedField,
397
- nullableType: CompositeTypeID,
398
- direction: 'forward' | 'backward' | 'bidirectional',
399
- connectionArguments: ConnectionArguments,
400
- directiveLocation: Location,
401
- documentName: string,
402
- ): $ReadOnlyArray<Selection> {
403
- const schema = context.getSchema();
404
- const derivedFieldLocation = {kind: 'Derived', source: field.loc};
405
- const derivedDirectiveLocation = {
406
- kind: 'Derived',
407
- source: directiveLocation,
408
- };
409
- const {
410
- CURSOR,
411
- EDGES,
412
- END_CURSOR,
413
- HAS_NEXT_PAGE,
414
- HAS_PREV_PAGE,
415
- NODE,
416
- PAGE_INFO,
417
- START_CURSOR,
418
- } = ConnectionInterface.get();
419
-
420
- // Find existing edges/pageInfo selections
421
- let edgesSelection: ?LinkedField;
422
- let pageInfoSelection: ?LinkedField;
423
- field.selections.forEach(selection => {
424
- if (selection.kind === 'LinkedField') {
425
- if (selection.name === EDGES) {
426
- if (edgesSelection != null) {
427
- throw createCompilerError(
428
- `ConnectionTransform: Unexpected duplicate field '${EDGES}'.`,
429
- [edgesSelection.loc, selection.loc],
430
- );
431
- }
432
- edgesSelection = selection;
433
- return;
434
- } else if (selection.name === PAGE_INFO) {
435
- if (pageInfoSelection != null) {
436
- throw createCompilerError(
437
- `ConnectionTransform: Unexpected duplicate field '${PAGE_INFO}'.`,
438
- [pageInfoSelection.loc, selection.loc],
439
- );
440
- }
441
- pageInfoSelection = selection;
442
- return;
443
- }
444
- }
445
- });
446
- // If streaming is enabled, construct directives to apply to the edges/
447
- // pageInfo fields
448
- let streamDirective;
449
- const stream = connectionArguments.stream;
450
- if (stream != null) {
451
- streamDirective = {
452
- args: [
453
- stream.if,
454
- stream.initialCount,
455
- stream.useCustomizedBatch,
456
- {
457
- kind: 'Argument',
458
- loc: derivedDirectiveLocation,
459
- name: 'label',
460
- type: SchemaUtils.getNullableStringInput(schema),
461
- value: {
462
- kind: 'Literal',
463
- loc: derivedDirectiveLocation,
464
- value: stream.label,
465
- },
466
- },
467
- ].filter(Boolean),
468
- kind: 'Directive',
469
- loc: derivedDirectiveLocation,
470
- name: 'stream',
471
- };
472
- }
473
- // For backwards compatibility with earlier versions of this transform,
474
- // edges/pageInfo have to be generated as non-aliased fields (since product
475
- // code may be accessing the non-aliased response keys). But for streaming
476
- // mode we need to generate @stream/@defer directives on these fields *and*
477
- // we prefer to avoid generating extra selections (we want one payload per
478
- // item, not two as could happen with separate @stream directives on the
479
- // aliased and non-aliased edges fields). So we keep things simple by
480
- // disallowing aliases on edges/pageInfo in streaming mode.
481
- if (edgesSelection && edgesSelection.alias !== edgesSelection.name) {
482
- if (stream) {
483
- throw createUserError(
484
- `@stream_connection does not support aliasing the '${EDGES}' field.`,
485
- [edgesSelection.loc],
486
- );
487
- }
488
- edgesSelection = null;
489
- }
490
- if (pageInfoSelection && pageInfoSelection.alias !== pageInfoSelection.name) {
491
- if (stream) {
492
- throw createUserError(
493
- `@stream_connection does not support aliasing the '${PAGE_INFO}' field.`,
494
- [pageInfoSelection.loc],
495
- );
496
- }
497
- pageInfoSelection = null;
498
- }
499
-
500
- // Separately create transformed versions of edges/pageInfo so that we can
501
- // later replace the originals at the same point within the selection array
502
- let transformedEdgesSelection: ?LinkedField = edgesSelection;
503
- let transformedPageInfoSelection: ?(
504
- | Defer
505
- | InlineFragment
506
- | LinkedField
507
- ) = pageInfoSelection;
508
- const edgesType = schema.getFieldConfig(
509
- schema.expectField(nullableType, EDGES),
510
- ).type;
511
-
512
- const pageInfoType = schema.getFieldConfig(
513
- schema.expectField(nullableType, PAGE_INFO),
514
- ).type;
515
-
516
- if (transformedEdgesSelection == null) {
517
- transformedEdgesSelection = {
518
- alias: EDGES,
519
- args: [],
520
- connection: false,
521
- directives: [],
522
- handles: null,
523
- kind: 'LinkedField',
524
- loc: derivedFieldLocation,
525
- metadata: null,
526
- name: EDGES,
527
- selections: [],
528
- type: schema.assertLinkedFieldType(edgesType),
529
- };
530
- }
531
- if (transformedPageInfoSelection == null) {
532
- transformedPageInfoSelection = {
533
- alias: PAGE_INFO,
534
- args: [],
535
- connection: false,
536
- directives: [],
537
- handles: null,
538
- kind: 'LinkedField',
539
- loc: derivedFieldLocation,
540
- metadata: null,
541
- name: PAGE_INFO,
542
- selections: [],
543
- type: schema.assertLinkedFieldType(pageInfoType),
544
- };
545
- }
546
-
547
- // Generate (additional) fields on pageInfo and add to the transformed
548
- // pageInfo field
549
- const pageInfoRawType = schema.getRawType(pageInfoType);
550
- let pageInfoText;
551
- if (direction === 'forward') {
552
- pageInfoText = `fragment PageInfo on ${schema.getTypeString(
553
- pageInfoRawType,
554
- )} {
555
- ${END_CURSOR}
556
- ${HAS_NEXT_PAGE}
557
- }`;
558
- } else if (direction === 'backward') {
559
- pageInfoText = `fragment PageInfo on ${schema.getTypeString(
560
- pageInfoRawType,
561
- )} {
562
- ${HAS_PREV_PAGE}
563
- ${START_CURSOR}
564
- }`;
565
- } else {
566
- pageInfoText = `fragment PageInfo on ${schema.getTypeString(
567
- pageInfoRawType,
568
- )} {
569
- ${END_CURSOR}
570
- ${HAS_NEXT_PAGE}
571
- ${HAS_PREV_PAGE}
572
- ${START_CURSOR}
573
- }`;
574
- }
575
- const pageInfoAst = parse(pageInfoText);
576
- const pageInfoFragment = RelayParser.transform(schema, [
577
- pageInfoAst.definitions[0],
578
- ])[0];
579
- if (transformedPageInfoSelection.kind !== 'LinkedField') {
580
- throw createCompilerError(
581
- 'ConnectionTransform: Expected generated pageInfo selection to be ' +
582
- 'a LinkedField',
583
- [field.loc],
584
- );
585
- }
586
- transformedPageInfoSelection = {
587
- ...transformedPageInfoSelection,
588
- selections: [
589
- ...transformedPageInfoSelection.selections,
590
- {
591
- directives: [],
592
- kind: 'InlineFragment',
593
- loc: derivedFieldLocation,
594
- metadata: null,
595
- selections: pageInfoFragment.selections,
596
- typeCondition: pageInfoFragment.type,
597
- },
598
- ],
599
- };
600
- // When streaming the pageInfo field has to be deferred
601
- if (stream != null) {
602
- transformedPageInfoSelection = {
603
- if: stream.if?.value ?? null,
604
- label: `${documentName}$defer$${stream.label}$${PAGE_INFO}`,
605
- kind: 'Defer',
606
- loc: derivedFieldLocation,
607
- selections: [transformedPageInfoSelection],
608
- };
609
- }
610
-
611
- // Generate additional fields on edges and append to the transformed edges
612
- // selection
613
- const edgeText = `
614
- fragment Edges on ${schema.getTypeString(schema.getRawType(edgesType))} {
615
- ${CURSOR}
616
- ${NODE} {
617
- __typename # rely on GenerateRequisiteFieldTransform to add "id"
618
- }
619
- }
620
- `;
621
- const edgeAst = parse(edgeText);
622
- const edgeFragment = RelayParser.transform(schema, [
623
- edgeAst.definitions[0],
624
- ])[0];
625
- // When streaming the edges field needs @stream
626
- transformedEdgesSelection = {
627
- ...transformedEdgesSelection,
628
- directives:
629
- streamDirective != null
630
- ? [...transformedEdgesSelection.directives, streamDirective]
631
- : transformedEdgesSelection.directives,
632
- selections: [
633
- ...transformedEdgesSelection.selections,
634
- {
635
- directives: [],
636
- kind: 'InlineFragment',
637
- loc: derivedFieldLocation,
638
- metadata: null,
639
- selections: edgeFragment.selections,
640
- typeCondition: edgeFragment.type,
641
- },
642
- ],
643
- };
644
- // Copy the original selections, replacing edges/pageInfo (if present)
645
- // with the generated locations. This is to maintain the original field
646
- // ordering.
647
- const selections = field.selections.map(selection => {
648
- if (
649
- transformedEdgesSelection != null &&
650
- edgesSelection != null &&
651
- selection === edgesSelection
652
- ) {
653
- return transformedEdgesSelection;
654
- } else if (
655
- transformedPageInfoSelection != null &&
656
- pageInfoSelection != null &&
657
- selection === pageInfoSelection
658
- ) {
659
- return transformedPageInfoSelection;
660
- } else {
661
- return selection;
662
- }
663
- });
664
- // If edges/pageInfo were missing, append the generated versions instead.
665
- if (edgesSelection == null && transformedEdgesSelection != null) {
666
- selections.push(transformedEdgesSelection);
667
- }
668
- if (pageInfoSelection == null && transformedPageInfoSelection != null) {
669
- selections.push(transformedPageInfoSelection);
670
- }
671
- return selections;
672
- }
673
-
674
- function findArg(field: LinkedField, argName: string): ?Argument {
675
- return field.args && field.args.find(arg => arg.name === argName);
676
- }
677
-
678
- /**
679
- * @internal
680
- *
681
- * Validates that the selection is a valid connection:
682
- * - Specifies a first or last argument to prevent accidental, unconstrained
683
- * data access.
684
- * - Has an `edges` selection, otherwise there is nothing to paginate.
685
- *
686
- * TODO: This implementation requires the edges field to be a direct selection
687
- * and not contained within an inline fragment or fragment spread. It's
688
- * technically possible to remove this restriction if this pattern becomes
689
- * common/necessary.
690
- */
691
- function validateConnectionSelection(field: LinkedField): void {
692
- const {EDGES} = ConnectionInterface.get();
693
-
694
- if (!findArg(field, FIRST) && !findArg(field, LAST)) {
695
- throw createUserError(
696
- `Expected field '${field.name}' to have a '${FIRST}' or '${LAST}' ` +
697
- 'argument.',
698
- [field.loc],
699
- );
700
- }
701
- if (
702
- !field.selections.some(
703
- selection => selection.kind === 'LinkedField' && selection.name === EDGES,
704
- )
705
- ) {
706
- throw createUserError(
707
- `Expected field '${field.name}' to have an '${EDGES}' selection.`,
708
- [field.loc],
709
- );
710
- }
711
- }
712
-
713
- /**
714
- * @internal
715
- *
716
- * Validates that the type satisfies the Connection specification:
717
- * - The type has an edges field, and edges have scalar `cursor` and object
718
- * `node` fields.
719
- * - The type has a page info field which is an object with the correct
720
- * subfields.
721
- */
722
- function validateConnectionType(
723
- schema: Schema,
724
- field: LinkedField,
725
- nullableType: CompositeTypeID,
726
- connectionDirective: Directive,
727
- ): void {
728
- const directiveName = connectionDirective.name;
729
- const {
730
- CURSOR,
731
- EDGES,
732
- END_CURSOR,
733
- HAS_NEXT_PAGE,
734
- HAS_PREV_PAGE,
735
- NODE,
736
- PAGE_INFO,
737
- START_CURSOR,
738
- } = ConnectionInterface.get();
739
-
740
- const typeName = schema.getTypeString(nullableType);
741
- if (!schema.hasField(nullableType, EDGES)) {
742
- throw createUserError(
743
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
744
- `field type '${typeName}' to have an '${EDGES}' field`,
745
- [field.loc],
746
- );
747
- }
748
-
749
- const edges = schema.getFieldConfig(schema.expectField(nullableType, EDGES));
750
-
751
- const edgesType = schema.getNullableType(edges.type);
752
- if (!schema.isList(edgesType)) {
753
- throw createUserError(
754
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
755
- `field type '${typeName}' to have an '${EDGES}' field that returns ` +
756
- 'a list of objects.',
757
- [field.loc],
758
- );
759
- }
760
- let edgeType = schema.getNullableType(schema.getListItemType(edgesType));
761
- if (!schema.isObject(edgeType) && !schema.isInterface(edgeType)) {
762
- throw createUserError(
763
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
764
- `field type '${typeName}' to have an '${EDGES}' field that returns ` +
765
- 'a list of objects.',
766
- [field.loc],
767
- );
768
- }
769
- edgeType = schema.assertCompositeType(edgeType);
770
-
771
- if (!schema.hasField(edgeType, NODE)) {
772
- throw createUserError(
773
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
774
- `field type '${typeName}' to have an '${EDGES} { ${NODE} }' field ` +
775
- 'that returns an object, interface, or union.',
776
- [field.loc],
777
- );
778
- }
779
- const node = schema.getFieldConfig(schema.expectField(edgeType, NODE));
780
-
781
- const nodeType = schema.getNullableType(node.type);
782
- if (!(schema.isAbstractType(nodeType) || schema.isObject(nodeType))) {
783
- throw createUserError(
784
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
785
- `field type '${typeName}' to have an '${EDGES} { ${NODE} }' field ` +
786
- 'that returns an object, interface, or union.',
787
- [field.loc],
788
- );
789
- }
790
-
791
- if (!schema.hasField(edgeType, CURSOR)) {
792
- throw createUserError(
793
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
794
- `field type '${typeName}' to have an '${EDGES} { ${CURSOR} }' field ` +
795
- 'that returns a scalar value.',
796
- [field.loc],
797
- );
798
- }
799
- const cursor = schema.getFieldConfig(schema.expectField(edgeType, CURSOR));
800
-
801
- if (!schema.isScalar(schema.getNullableType(cursor.type))) {
802
- throw createUserError(
803
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
804
- `field type '${typeName}' to have an '${EDGES} { ${CURSOR} }' field ` +
805
- 'that returns a scalar value.',
806
- [field.loc],
807
- );
808
- }
809
-
810
- if (!schema.hasField(nullableType, PAGE_INFO)) {
811
- throw createUserError(
812
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
813
- `field type '${typeName}' to have a '${PAGE_INFO}' field that returns ` +
814
- 'an object.',
815
- [field.loc],
816
- );
817
- }
818
-
819
- const pageInfo = schema.getFieldConfig(
820
- schema.expectField(nullableType, PAGE_INFO),
821
- );
822
-
823
- const pageInfoType = schema.getNullableType(pageInfo.type);
824
- if (!schema.isObject(pageInfoType)) {
825
- throw createUserError(
826
- `@${directiveName} used on invalid field '${field.name}'. Expected the ` +
827
- `field type '${typeName}' to have a '${PAGE_INFO}' field that ` +
828
- 'returns an object.',
829
- [field.loc],
830
- );
831
- }
832
-
833
- [END_CURSOR, HAS_NEXT_PAGE, HAS_PREV_PAGE, START_CURSOR].forEach(
834
- fieldName => {
835
- const pageInfoField = schema.getFieldConfig(
836
- schema.expectField(schema.assertObjectType(pageInfoType), fieldName),
837
- );
838
- if (!schema.isScalar(schema.getNullableType(pageInfoField.type))) {
839
- throw createUserError(
840
- `@${directiveName} used on invalid field '${field.name}'. Expected ` +
841
- `the field type '${typeName}' to have a '${PAGE_INFO} { ${fieldName} }' ` +
842
- 'field returns a scalar.',
843
- [field.loc],
844
- );
845
- }
846
- },
847
- );
848
- }
849
-
850
- module.exports = {
851
- buildConnectionMetadata,
852
- CONNECTION,
853
- SCHEMA_EXTENSION,
854
- transform: connectionTransform,
855
- };