relay-compiler 9.0.0 → 10.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (217) hide show
  1. package/bin/RelayCompilerBin.js.flow +169 -0
  2. package/bin/RelayCompilerMain.js.flow +515 -0
  3. package/bin/__fixtures__/plugin-module.js.flow +17 -0
  4. package/bin/relay-compiler +3862 -2505
  5. package/codegen/CodegenDirectory.js.flow +375 -0
  6. package/codegen/CodegenRunner.js.flow +432 -0
  7. package/codegen/CodegenTypes.js.flow +28 -0
  8. package/codegen/CodegenWatcher.js.flow +254 -0
  9. package/codegen/NormalizationCodeGenerator.js.flow +571 -0
  10. package/codegen/ReaderCodeGenerator.js.flow +512 -0
  11. package/codegen/RelayCodeGenerator.js.flow +85 -0
  12. package/codegen/RelayFileWriter.js.flow +367 -0
  13. package/codegen/SourceControl.js.flow +58 -0
  14. package/codegen/compileRelayArtifacts.js.flow +182 -0
  15. package/codegen/createPrintRequireModuleDependency.js.flow +21 -0
  16. package/codegen/sortObjectByKey.js.flow +25 -0
  17. package/codegen/writeRelayGeneratedFile.js.flow +223 -0
  18. package/core/ASTCache.js.flow +74 -0
  19. package/core/ASTConvert.js.flow +233 -0
  20. package/core/CompilerContext.js.flow +191 -0
  21. package/core/CompilerError.js.flow +250 -0
  22. package/core/DotGraphQLParser.js.flow +39 -0
  23. package/core/GraphQLCompilerProfiler.js.flow +341 -0
  24. package/core/GraphQLDerivedFromMetadata.js.flow +36 -0
  25. package/core/GraphQLWatchmanClient.js.flow +111 -0
  26. package/core/IR.js.flow +326 -0
  27. package/core/IRPrinter.js.flow +477 -0
  28. package/core/IRTransformer.js.flow +377 -0
  29. package/core/IRValidator.js.flow +260 -0
  30. package/core/IRVisitor.js.flow +150 -0
  31. package/core/JSModuleParser.js.flow +24 -0
  32. package/core/RelayCompilerScope.js.flow +199 -0
  33. package/core/RelayFindGraphQLTags.js.flow +119 -0
  34. package/core/RelayGraphQLEnumsGenerator.js.flow +55 -0
  35. package/core/RelayIRTransforms.js.flow +138 -0
  36. package/core/RelayParser.js.flow +1731 -0
  37. package/core/RelaySourceModuleParser.js.flow +135 -0
  38. package/core/Schema.js.flow +2037 -0
  39. package/core/SchemaUtils.js.flow +120 -0
  40. package/core/filterContextForNode.js.flow +50 -0
  41. package/core/getFieldDefinition.js.flow +156 -0
  42. package/core/getIdentifierForArgumentValue.js.flow +49 -0
  43. package/core/getIdentifierForSelection.js.flow +69 -0
  44. package/core/getLiteralArgumentValues.js.flow +32 -0
  45. package/core/getNormalizationOperationName.js.flow +19 -0
  46. package/core/inferRootArgumentDefinitions.js.flow +323 -0
  47. package/index.js +1 -1
  48. package/index.js.flow +200 -0
  49. package/language/RelayLanguagePluginInterface.js.flow +283 -0
  50. package/language/javascript/FindGraphQLTags.js.flow +137 -0
  51. package/language/javascript/RelayFlowBabelFactories.js.flow +176 -0
  52. package/language/javascript/RelayFlowGenerator.js.flow +1099 -0
  53. package/language/javascript/RelayFlowTypeTransformers.js.flow +184 -0
  54. package/language/javascript/RelayLanguagePluginJavaScript.js.flow +34 -0
  55. package/language/javascript/formatGeneratedModule.js.flow +65 -0
  56. package/lib/bin/RelayCompilerBin.js +10 -0
  57. package/lib/bin/RelayCompilerMain.js +127 -130
  58. package/lib/codegen/CodegenDirectory.js +2 -6
  59. package/lib/codegen/CodegenRunner.js +37 -76
  60. package/lib/codegen/CodegenWatcher.js +13 -21
  61. package/lib/codegen/NormalizationCodeGenerator.js +131 -50
  62. package/lib/codegen/ReaderCodeGenerator.js +116 -49
  63. package/lib/codegen/RelayCodeGenerator.js +17 -6
  64. package/lib/codegen/RelayFileWriter.js +15 -37
  65. package/lib/codegen/compileRelayArtifacts.js +16 -30
  66. package/lib/codegen/sortObjectByKey.js +43 -0
  67. package/lib/codegen/writeRelayGeneratedFile.js +86 -96
  68. package/lib/core/ASTCache.js +3 -4
  69. package/lib/core/CompilerContext.js +3 -4
  70. package/lib/core/CompilerError.js +27 -54
  71. package/lib/core/GraphQLCompilerProfiler.js +8 -12
  72. package/lib/core/GraphQLDerivedFromMetadata.js +1 -10
  73. package/lib/core/GraphQLWatchmanClient.js +4 -12
  74. package/lib/core/IRPrinter.js +16 -21
  75. package/lib/core/IRTransformer.js +8 -6
  76. package/lib/core/IRValidator.js +1 -3
  77. package/lib/core/RelayCompilerScope.js +4 -4
  78. package/lib/core/RelayGraphQLEnumsGenerator.js +12 -15
  79. package/lib/core/RelayIRTransforms.js +23 -13
  80. package/lib/core/RelayParser.js +53 -89
  81. package/lib/core/RelaySourceModuleParser.js +1 -3
  82. package/lib/core/Schema.js +106 -77
  83. package/lib/core/SchemaUtils.js +15 -1
  84. package/lib/core/getFieldDefinition.js +12 -15
  85. package/lib/core/getIdentifierForSelection.js +1 -1
  86. package/lib/core/inferRootArgumentDefinitions.js +27 -36
  87. package/lib/index.js +1 -3
  88. package/lib/language/javascript/FindGraphQLTags.js +7 -72
  89. package/lib/language/javascript/RelayFlowBabelFactories.js +5 -5
  90. package/lib/language/javascript/RelayFlowGenerator.js +131 -108
  91. package/lib/language/javascript/RelayFlowTypeTransformers.js +1 -3
  92. package/lib/reporters/ConsoleReporter.js +1 -3
  93. package/lib/reporters/MultiReporter.js +1 -3
  94. package/lib/runner/Artifacts.js +69 -170
  95. package/lib/runner/BufferedFilesystem.js +32 -66
  96. package/lib/runner/GraphQLASTNodeGroup.js +54 -120
  97. package/lib/runner/GraphQLNodeMap.js +14 -19
  98. package/lib/runner/Sources.js +70 -85
  99. package/lib/runner/StrictMap.js +21 -37
  100. package/lib/runner/getChangedNodeNames.js +30 -62
  101. package/lib/transforms/ApplyFragmentArgumentTransform.js +71 -31
  102. package/lib/transforms/ClientExtensionsTransform.js +15 -15
  103. package/lib/transforms/ConnectionTransform.js +26 -38
  104. package/lib/transforms/DeclarativeConnectionMutationTransform.js +225 -0
  105. package/lib/transforms/DeferStreamTransform.js +27 -17
  106. package/lib/transforms/DisallowTypenameOnRoot.js +55 -0
  107. package/lib/transforms/FieldHandleTransform.js +7 -3
  108. package/lib/transforms/FilterCompilerDirectivesTransform.js +29 -0
  109. package/lib/transforms/FlattenTransform.js +23 -19
  110. package/lib/transforms/GenerateIDFieldTransform.js +56 -35
  111. package/lib/transforms/GenerateTypeNameTransform.js +84 -10
  112. package/lib/transforms/InlineDataFragmentTransform.js +9 -4
  113. package/lib/transforms/MaskTransform.js +17 -17
  114. package/lib/transforms/MatchTransform.js +114 -32
  115. package/lib/transforms/ReactFlightComponentTransform.js +162 -0
  116. package/lib/transforms/RefetchableFragmentTransform.js +21 -17
  117. package/lib/transforms/RelayDirectiveTransform.js +8 -3
  118. package/lib/transforms/RequiredFieldTransform.js +380 -0
  119. package/lib/transforms/SkipClientExtensionsTransform.js +8 -0
  120. package/lib/transforms/SkipHandleFieldTransform.js +6 -2
  121. package/lib/transforms/SkipRedundantNodesTransform.js +9 -2
  122. package/lib/transforms/SkipSplitOperationTransform.js +32 -0
  123. package/lib/transforms/SkipUnreachableNodeTransform.js +9 -2
  124. package/lib/transforms/SkipUnusedVariablesTransform.js +18 -17
  125. package/lib/transforms/SplitModuleImportTransform.js +2 -2
  126. package/lib/transforms/TestOperationTransform.js +26 -20
  127. package/lib/transforms/ValidateGlobalVariablesTransform.js +18 -30
  128. package/lib/transforms/ValidateRequiredArgumentsTransform.js +12 -15
  129. package/lib/transforms/ValidateServerOnlyDirectivesTransform.js +16 -30
  130. package/lib/transforms/ValidateUnusedVariablesTransform.js +18 -30
  131. package/lib/transforms/query-generators/FetchableQueryGenerator.js +161 -0
  132. package/lib/transforms/query-generators/NodeQueryGenerator.js +22 -3
  133. package/lib/transforms/query-generators/QueryQueryGenerator.js +2 -1
  134. package/lib/transforms/query-generators/ViewerQueryGenerator.js +1 -0
  135. package/lib/transforms/query-generators/index.js +23 -6
  136. package/lib/transforms/query-generators/utils.js +17 -16
  137. package/lib/util/RelayCompilerCache.js +2 -4
  138. package/lib/util/argumentContainsVariables.js +37 -0
  139. package/lib/util/dedupeJSONStringify.js +15 -12
  140. package/lib/util/generateAbstractTypeRefinementKey.js +24 -0
  141. package/lib/util/getModuleName.js +1 -1
  142. package/lib/util/joinArgumentDefinitions.js +3 -1
  143. package/package.json +7 -7
  144. package/relay-compiler.js +4 -4
  145. package/relay-compiler.min.js +4 -4
  146. package/reporters/ConsoleReporter.js.flow +81 -0
  147. package/reporters/MultiReporter.js.flow +43 -0
  148. package/reporters/Reporter.js.flow +19 -0
  149. package/runner/Artifacts.js.flow +219 -0
  150. package/runner/BufferedFilesystem.js.flow +194 -0
  151. package/runner/GraphQLASTNodeGroup.js.flow +176 -0
  152. package/runner/GraphQLASTUtils.js.flow +26 -0
  153. package/runner/GraphQLNodeMap.js.flow +55 -0
  154. package/runner/Sources.js.flow +228 -0
  155. package/runner/StrictMap.js.flow +96 -0
  156. package/runner/compileArtifacts.js.flow +76 -0
  157. package/runner/extractAST.js.flow +100 -0
  158. package/runner/getChangedNodeNames.js.flow +48 -0
  159. package/runner/getSchemaInstance.js.flow +36 -0
  160. package/runner/types.js.flow +37 -0
  161. package/transforms/ApplyFragmentArgumentTransform.js.flow +526 -0
  162. package/transforms/ClientExtensionsTransform.js.flow +224 -0
  163. package/transforms/ConnectionTransform.js.flow +855 -0
  164. package/transforms/DeclarativeConnectionMutationTransform.js.flow +246 -0
  165. package/transforms/DeferStreamTransform.js.flow +265 -0
  166. package/transforms/DisallowIdAsAlias.js.flow +47 -0
  167. package/transforms/DisallowTypenameOnRoot.js.flow +45 -0
  168. package/transforms/FieldHandleTransform.js.flow +79 -0
  169. package/transforms/FilterCompilerDirectivesTransform.js.flow +33 -0
  170. package/transforms/FilterDirectivesTransform.js.flow +45 -0
  171. package/transforms/FlattenTransform.js.flow +454 -0
  172. package/transforms/GenerateIDFieldTransform.js.flow +152 -0
  173. package/transforms/GenerateTypeNameTransform.js.flow +161 -0
  174. package/transforms/InlineDataFragmentTransform.js.flow +125 -0
  175. package/transforms/InlineFragmentsTransform.js.flow +71 -0
  176. package/transforms/MaskTransform.js.flow +126 -0
  177. package/transforms/MatchTransform.js.flow +589 -0
  178. package/transforms/ReactFlightComponentTransform.js.flow +195 -0
  179. package/transforms/RefetchableFragmentTransform.js.flow +272 -0
  180. package/transforms/RelayDirectiveTransform.js.flow +97 -0
  181. package/transforms/RequiredFieldTransform.js.flow +415 -0
  182. package/transforms/SkipClientExtensionsTransform.js.flow +54 -0
  183. package/transforms/SkipHandleFieldTransform.js.flow +44 -0
  184. package/transforms/SkipRedundantNodesTransform.js.flow +257 -0
  185. package/transforms/SkipSplitOperationTransform.js.flow +37 -0
  186. package/transforms/SkipUnreachableNodeTransform.js.flow +149 -0
  187. package/transforms/SkipUnusedVariablesTransform.js.flow +59 -0
  188. package/transforms/SplitModuleImportTransform.js.flow +98 -0
  189. package/transforms/TestOperationTransform.js.flow +142 -0
  190. package/transforms/TransformUtils.js.flow +26 -0
  191. package/transforms/ValidateGlobalVariablesTransform.js.flow +81 -0
  192. package/transforms/ValidateRequiredArgumentsTransform.js.flow +127 -0
  193. package/transforms/ValidateServerOnlyDirectivesTransform.js.flow +112 -0
  194. package/transforms/ValidateUnusedVariablesTransform.js.flow +89 -0
  195. package/transforms/query-generators/FetchableQueryGenerator.js.flow +189 -0
  196. package/transforms/query-generators/NodeQueryGenerator.js.flow +219 -0
  197. package/transforms/query-generators/QueryQueryGenerator.js.flow +57 -0
  198. package/transforms/query-generators/ViewerQueryGenerator.js.flow +97 -0
  199. package/transforms/query-generators/index.js.flow +90 -0
  200. package/transforms/query-generators/utils.js.flow +76 -0
  201. package/util/CodeMarker.js.flow +79 -0
  202. package/util/DefaultHandleKey.js.flow +17 -0
  203. package/util/RelayCompilerCache.js.flow +88 -0
  204. package/util/Rollout.js.flow +39 -0
  205. package/util/TimeReporter.js.flow +79 -0
  206. package/util/areEqualOSS.js.flow +123 -0
  207. package/util/argumentContainsVariables.js.flow +38 -0
  208. package/util/dedupeJSONStringify.js.flow +152 -0
  209. package/util/generateAbstractTypeRefinementKey.js.flow +29 -0
  210. package/util/getDefinitionNodeHash.js.flow +25 -0
  211. package/util/getModuleName.js.flow +39 -0
  212. package/util/joinArgumentDefinitions.js.flow +105 -0
  213. package/util/md5.js.flow +22 -0
  214. package/util/murmurHash.js.flow +94 -0
  215. package/util/nullthrowsOSS.js.flow +25 -0
  216. package/util/orList.js.flow +37 -0
  217. package/util/partitionArray.js.flow +37 -0
@@ -0,0 +1,477 @@
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
8
+ * @format
9
+ */
10
+
11
+ // flowlint ambiguous-object-type:error
12
+
13
+ 'use strict';
14
+
15
+ const invariant = require('invariant');
16
+
17
+ const {DEFAULT_HANDLE_KEY} = require('../util/DefaultHandleKey');
18
+
19
+ import type {CompilerContextDocument} from './CompilerContext';
20
+ import type {
21
+ Argument,
22
+ ArgumentDefinition,
23
+ ArgumentValue,
24
+ Directive,
25
+ Field,
26
+ LocalArgumentDefinition,
27
+ Node,
28
+ Selection,
29
+ } from './IR';
30
+ import type {Schema, TypeID} from './Schema';
31
+
32
+ const INDENT = ' ';
33
+
34
+ /**
35
+ * Converts an IR node into a GraphQL string. Custom Relay
36
+ * extensions (directives) are not supported; to print fragments with
37
+ * variables or fragment spreads with arguments, transform the node
38
+ * prior to printing.
39
+ */
40
+ function print(schema: Schema, node: CompilerContextDocument): string {
41
+ switch (node.kind) {
42
+ case 'Fragment':
43
+ return (
44
+ `fragment ${node.name} on ${schema.getTypeString(node.type)}` +
45
+ printFragmentArgumentDefinitions(schema, node.argumentDefinitions) +
46
+ printDirectives(schema, node.directives) +
47
+ printSelections(schema, node, '', {}) +
48
+ '\n'
49
+ );
50
+ case 'Root':
51
+ return (
52
+ `${node.operation} ${node.name}` +
53
+ printArgumentDefinitions(schema, node.argumentDefinitions) +
54
+ printDirectives(schema, node.directives) +
55
+ printSelections(schema, node, '', {}) +
56
+ '\n'
57
+ );
58
+ case 'SplitOperation':
59
+ return (
60
+ `SplitOperation ${node.name} on ${schema.getTypeString(node.type)}` +
61
+ printSelections(schema, node, '', {}) +
62
+ '\n'
63
+ );
64
+ default:
65
+ (node: empty);
66
+ invariant(false, 'IRPrinter: Unsupported IR node `%s`.', node.kind);
67
+ }
68
+ }
69
+
70
+ function printSelections(
71
+ schema: Schema,
72
+ node: Node,
73
+ indent: string,
74
+ options?: {
75
+ parentDirectives?: string,
76
+ isClientExtension?: boolean,
77
+ ...
78
+ },
79
+ ): string {
80
+ const selections = node.selections;
81
+ if (selections == null) {
82
+ return '';
83
+ }
84
+ const printed = selections.map(selection =>
85
+ printSelection(schema, selection, indent, options),
86
+ );
87
+ return printed.length
88
+ ? ` {\n${indent + INDENT}${printed.join(
89
+ '\n' + indent + INDENT,
90
+ )}\n${indent}${options?.isClientExtension === true ? '# ' : ''}}`
91
+ : '';
92
+ }
93
+
94
+ /**
95
+ * Prints a field without subselections.
96
+ */
97
+ function printField(
98
+ schema: Schema,
99
+ field: Field,
100
+ options?: {
101
+ parentDirectives?: string,
102
+ isClientExtension?: boolean,
103
+ ...
104
+ },
105
+ ): string {
106
+ const parentDirectives = options?.parentDirectives ?? '';
107
+ const isClientExtension = options?.isClientExtension === true;
108
+ return (
109
+ (isClientExtension ? '# ' : '') +
110
+ (field.alias === field.name
111
+ ? field.name
112
+ : field.alias + ': ' + field.name) +
113
+ printArguments(schema, field.args) +
114
+ parentDirectives +
115
+ printDirectives(schema, field.directives) +
116
+ printHandles(schema, field)
117
+ );
118
+ }
119
+
120
+ function printSelection(
121
+ schema: Schema,
122
+ selection: Selection,
123
+ indent: string,
124
+ options?: {
125
+ parentDirectives?: string,
126
+ isClientExtension?: boolean,
127
+ ...
128
+ },
129
+ ): string {
130
+ let str;
131
+ const parentDirectives = options?.parentDirectives ?? '';
132
+ const isClientExtension = options?.isClientExtension === true;
133
+ if (selection.kind === 'LinkedField') {
134
+ str = printField(schema, selection, {parentDirectives, isClientExtension});
135
+ str += printSelections(schema, selection, indent + INDENT, {
136
+ isClientExtension,
137
+ });
138
+ } else if (selection.kind === 'ModuleImport') {
139
+ str = selection.selections
140
+ .map(matchSelection =>
141
+ printSelection(schema, matchSelection, indent, {
142
+ parentDirectives,
143
+ isClientExtension,
144
+ }),
145
+ )
146
+ .join('\n' + indent + INDENT);
147
+ } else if (selection.kind === 'ScalarField') {
148
+ str = printField(schema, selection, {parentDirectives, isClientExtension});
149
+ } else if (selection.kind === 'InlineFragment') {
150
+ str = '';
151
+ if (isClientExtension) {
152
+ str += '# ';
153
+ }
154
+ str += '... on ' + schema.getTypeString(selection.typeCondition);
155
+ str += parentDirectives;
156
+ str += printDirectives(schema, selection.directives);
157
+ str += printSelections(schema, selection, indent + INDENT, {
158
+ isClientExtension,
159
+ });
160
+ } else if (selection.kind === 'FragmentSpread') {
161
+ str = '';
162
+ if (isClientExtension) {
163
+ str += '# ';
164
+ }
165
+ str += '...' + selection.name;
166
+ str += parentDirectives;
167
+ str += printFragmentArguments(schema, selection.args);
168
+ str += printDirectives(schema, selection.directives);
169
+ } else if (selection.kind === 'InlineDataFragmentSpread') {
170
+ str =
171
+ `# ${selection.name} @inline` +
172
+ `\n${indent}${INDENT}...` +
173
+ parentDirectives +
174
+ printSelections(schema, selection, indent + INDENT, {});
175
+ } else if (selection.kind === 'Condition') {
176
+ const value = printValue(schema, selection.condition, null);
177
+ // For Flow
178
+ invariant(
179
+ value != null,
180
+ 'IRPrinter: Expected a variable for condition, got a literal `null`.',
181
+ );
182
+ let condStr = selection.passingValue ? ' @include' : ' @skip';
183
+ condStr += '(if: ' + value + ')';
184
+ condStr += parentDirectives;
185
+ // For multi-selection conditions, pushes the condition down to each
186
+ const subSelections = selection.selections.map(sel =>
187
+ printSelection(schema, sel, indent, {
188
+ parentDirectives: condStr,
189
+ isClientExtension,
190
+ }),
191
+ );
192
+ str = subSelections.join('\n' + indent + INDENT);
193
+ } else if (selection.kind === 'Stream') {
194
+ let streamStr = parentDirectives;
195
+ streamStr += ` @stream(label: "${selection.label}"`;
196
+ if (selection.if !== null) {
197
+ streamStr += `, if: ${printValue(schema, selection.if, null) ?? ''}`;
198
+ }
199
+ if (selection.initialCount !== null) {
200
+ streamStr += `, initial_count: ${printValue(
201
+ schema,
202
+ selection.initialCount,
203
+ null,
204
+ ) ?? ''}`;
205
+ }
206
+ if (selection.useCustomizedBatch !== null) {
207
+ streamStr += `, use_customized_batch: ${printValue(
208
+ schema,
209
+ selection.useCustomizedBatch,
210
+ null,
211
+ ) ?? 'false'}`;
212
+ }
213
+ streamStr += ')';
214
+ const subSelections = selection.selections.map(sel =>
215
+ printSelection(schema, sel, indent, {
216
+ parentDirectives: streamStr,
217
+ isClientExtension,
218
+ }),
219
+ );
220
+ str = subSelections.join('\n' + INDENT);
221
+ } else if (selection.kind === 'Defer') {
222
+ let deferStr = parentDirectives;
223
+ deferStr += ` @defer(label: "${selection.label}"`;
224
+ if (selection.if !== null) {
225
+ deferStr += `, if: ${printValue(schema, selection.if, null) ?? ''}`;
226
+ }
227
+ deferStr += ')';
228
+ if (
229
+ selection.selections.every(
230
+ subSelection =>
231
+ subSelection.kind === 'InlineFragment' ||
232
+ subSelection.kind === 'FragmentSpread',
233
+ )
234
+ ) {
235
+ const subSelections = selection.selections.map(sel =>
236
+ printSelection(schema, sel, indent, {
237
+ parentDirectives: deferStr,
238
+ isClientExtension,
239
+ }),
240
+ );
241
+ str = subSelections.join('\n' + INDENT);
242
+ } else {
243
+ str = '...' + deferStr;
244
+ str += printSelections(schema, selection, indent + INDENT, {
245
+ isClientExtension,
246
+ });
247
+ }
248
+ } else if (selection.kind === 'ClientExtension') {
249
+ invariant(
250
+ isClientExtension === false,
251
+ 'IRPrinter: Did not expect to encounter a ClientExtension node ' +
252
+ 'as a descendant of another ClientExtension node.',
253
+ );
254
+ str =
255
+ '# Client-only selections:\n' +
256
+ indent +
257
+ INDENT +
258
+ selection.selections
259
+ .map(sel =>
260
+ printSelection(schema, sel, indent, {
261
+ parentDirectives,
262
+ isClientExtension: true,
263
+ }),
264
+ )
265
+ .join('\n' + indent + INDENT);
266
+ } else {
267
+ (selection: empty);
268
+ invariant(false, 'IRPrinter: Unknown selection kind `%s`.', selection.kind);
269
+ }
270
+ return str;
271
+ }
272
+
273
+ function printArgumentDefinitions(
274
+ schema: Schema,
275
+ argumentDefinitions: $ReadOnlyArray<LocalArgumentDefinition>,
276
+ ): string {
277
+ const printed = argumentDefinitions.map(def => {
278
+ let str = `$${def.name}: ${schema.getTypeString(def.type)}`;
279
+ if (def.defaultValue != null) {
280
+ str += ' = ' + printLiteral(schema, def.defaultValue, def.type);
281
+ }
282
+ return str;
283
+ });
284
+ return printed.length ? `(\n${INDENT}${printed.join('\n' + INDENT)}\n)` : '';
285
+ }
286
+
287
+ function printFragmentArgumentDefinitions(
288
+ schema: Schema,
289
+ argumentDefinitions: $ReadOnlyArray<ArgumentDefinition>,
290
+ ): string {
291
+ let printed;
292
+ argumentDefinitions.forEach(def => {
293
+ if (def.kind !== 'LocalArgumentDefinition') {
294
+ return;
295
+ }
296
+ printed = printed || [];
297
+ let str = `${def.name}: {type: "${schema.getTypeString(def.type)}"`;
298
+ if (def.defaultValue != null) {
299
+ str += `, defaultValue: ${printLiteral(
300
+ schema,
301
+ def.defaultValue,
302
+ def.type,
303
+ )}`;
304
+ }
305
+ str += '}';
306
+ printed.push(str);
307
+ });
308
+ return printed && printed.length
309
+ ? ` @argumentDefinitions(\n${INDENT}${printed.join('\n' + INDENT)}\n)`
310
+ : '';
311
+ }
312
+
313
+ function printHandles(schema: Schema, field: Field): string {
314
+ if (!field.handles) {
315
+ return '';
316
+ }
317
+ const printed = field.handles.map(handle => {
318
+ // For backward compatibility.
319
+ const key =
320
+ handle.key === DEFAULT_HANDLE_KEY ? '' : `, key: "${handle.key}"`;
321
+ const filters =
322
+ handle.filters == null
323
+ ? ''
324
+ : `, filters: ${JSON.stringify(Array.from(handle.filters).sort())}`;
325
+ const handleArgs =
326
+ handle.handleArgs == null
327
+ ? ''
328
+ : `, handleArgs: ${printArguments(schema, handle.handleArgs)}`;
329
+ return `@__clientField(handle: "${handle.name}"${key}${filters}${handleArgs})`;
330
+ });
331
+ return printed.length ? ' ' + printed.join(' ') : '';
332
+ }
333
+
334
+ function printDirectives(
335
+ schema: Schema,
336
+ directives: $ReadOnlyArray<Directive>,
337
+ ): string {
338
+ const printed = directives.map(directive => {
339
+ return '@' + directive.name + printArguments(schema, directive.args);
340
+ });
341
+ return printed.length ? ' ' + printed.join(' ') : '';
342
+ }
343
+
344
+ function printFragmentArguments(
345
+ schema: Schema,
346
+ args: $ReadOnlyArray<Argument>,
347
+ ) {
348
+ const printedArgs = printArguments(schema, args);
349
+ if (!printedArgs.length) {
350
+ return '';
351
+ }
352
+ return ` @arguments${printedArgs}`;
353
+ }
354
+
355
+ function printArguments(
356
+ schema: Schema,
357
+ args: $ReadOnlyArray<Argument>,
358
+ ): string {
359
+ const printed = [];
360
+ args.forEach(arg => {
361
+ const printedValue = printValue(schema, arg.value, arg.type);
362
+ if (printedValue != null) {
363
+ printed.push(arg.name + ': ' + printedValue);
364
+ }
365
+ });
366
+ return printed.length ? '(' + printed.join(', ') + ')' : '';
367
+ }
368
+
369
+ function printValue(
370
+ schema: Schema,
371
+ value: ArgumentValue,
372
+ type: ?TypeID,
373
+ ): ?string {
374
+ if (type != null && schema.isNonNull(type)) {
375
+ type = schema.getNullableType(type);
376
+ }
377
+ if (value.kind === 'Variable') {
378
+ return '$' + value.variableName;
379
+ } else if (value.kind === 'ObjectValue') {
380
+ const inputType = type != null ? schema.asInputObjectType(type) : null;
381
+ const pairs = value.fields
382
+ .map(field => {
383
+ const fieldConfig =
384
+ inputType != null
385
+ ? schema.hasField(inputType, field.name)
386
+ ? schema.getFieldConfig(schema.expectField(inputType, field.name))
387
+ : null
388
+ : null;
389
+ const innerValue = printValue(schema, field.value, fieldConfig?.type);
390
+ return innerValue == null ? null : field.name + ': ' + innerValue;
391
+ })
392
+ .filter(Boolean);
393
+
394
+ return '{' + pairs.join(', ') + '}';
395
+ } else if (value.kind === 'ListValue') {
396
+ invariant(
397
+ type && schema.isList(type),
398
+ 'GraphQLIRPrinter: Need a type in order to print arrays.',
399
+ );
400
+ const innerType = schema.getListItemType(type);
401
+ return `[${value.items
402
+ .map(i => printValue(schema, i, innerType))
403
+ .join(', ')}]`;
404
+ } else if (value.value != null) {
405
+ return printLiteral(schema, value.value, type);
406
+ } else {
407
+ return null;
408
+ }
409
+ }
410
+
411
+ function printLiteral(schema: Schema, value: mixed, type: ?TypeID): string {
412
+ if (value == null) {
413
+ return JSON.stringify(value) ?? 'null';
414
+ }
415
+ if (type != null && schema.isNonNull(type)) {
416
+ type = schema.getNullableType(type);
417
+ }
418
+
419
+ if (type && schema.isEnum(type)) {
420
+ let result = schema.serialize(schema.assertEnumType(type), value);
421
+ if (result == null && typeof value === 'string') {
422
+ // For backwards compatibility, print invalid input values as-is. This
423
+ // can occur with literals defined as an @argumentDefinitions
424
+ // defaultValue.
425
+ result = value;
426
+ }
427
+ invariant(
428
+ typeof result === 'string',
429
+ 'IRPrinter: Expected value of type %s to be a valid enum value, got `%s`.',
430
+ schema.getTypeString(type),
431
+ JSON.stringify(value) ?? 'null',
432
+ );
433
+ return result;
434
+ } else if (type && (schema.isId(type) || schema.isInt(type))) {
435
+ return JSON.stringify(value) ?? '';
436
+ } else if (type && schema.isScalar(type)) {
437
+ const result = schema.serialize(schema.assertScalarType(type), value);
438
+ return JSON.stringify(result) ?? '';
439
+ } else if (Array.isArray(value)) {
440
+ invariant(
441
+ type && schema.isList(type),
442
+ 'IRPrinter: Need a type in order to print arrays.',
443
+ );
444
+ const itemType = schema.getListItemType(type);
445
+ return (
446
+ '[' +
447
+ value.map(item => printLiteral(schema, item, itemType)).join(', ') +
448
+ ']'
449
+ );
450
+ } else if (type && schema.isList(type) && value != null) {
451
+ // Not an array, but still a list. Treat as list-of-one as per spec 3.1.7:
452
+ // http://facebook.github.io/graphql/October2016/#sec-Lists
453
+ return printLiteral(schema, value, schema.getListItemType(type));
454
+ } else if (typeof value === 'object' && value != null) {
455
+ const fields = [];
456
+ invariant(
457
+ type && schema.isInputObject(type),
458
+ 'IRPrinter: Need an InputObject type to print objects.',
459
+ );
460
+ const inputType = schema.assertInputObjectType(type);
461
+ for (const key in value) {
462
+ if (value.hasOwnProperty(key)) {
463
+ const fieldConfig = schema.getFieldConfig(
464
+ schema.expectField(inputType, key),
465
+ );
466
+ fields.push(
467
+ key + ': ' + printLiteral(schema, value[key], fieldConfig.type),
468
+ );
469
+ }
470
+ }
471
+ return '{' + fields.join(', ') + '}';
472
+ } else {
473
+ return JSON.stringify(value) ?? 'null';
474
+ }
475
+ }
476
+
477
+ module.exports = {print, printField, printArguments, printDirectives};