relay-compiler 9.0.0 → 9.1.0

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