relay-compiler 8.0.0 → 10.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (220) 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 +8930 -8967
  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 +563 -0
  10. package/codegen/ReaderCodeGenerator.js.flow +477 -0
  11. package/codegen/RelayCodeGenerator.js.flow +85 -0
  12. package/codegen/RelayFileWriter.js.flow +365 -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 +73 -0
  19. package/core/ASTConvert.js.flow +233 -0
  20. package/core/CompilerContext.js.flow +190 -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 +327 -0
  27. package/core/IRPrinter.js.flow +482 -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 +131 -0
  36. package/core/RelayParser.js.flow +1731 -0
  37. package/core/RelaySourceModuleParser.js.flow +135 -0
  38. package/core/Schema.js.flow +1983 -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 +232 -0
  51. package/language/javascript/RelayFlowBabelFactories.js.flow +180 -0
  52. package/language/javascript/RelayFlowGenerator.js.flow +1042 -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 +24 -7
  57. package/lib/bin/RelayCompilerMain.js +141 -136
  58. package/lib/codegen/CodegenDirectory.js +13 -8
  59. package/lib/codegen/CodegenRunner.js +37 -76
  60. package/lib/codegen/CodegenWatcher.js +13 -21
  61. package/lib/codegen/NormalizationCodeGenerator.js +117 -140
  62. package/lib/codegen/ReaderCodeGenerator.js +76 -117
  63. package/lib/codegen/RelayCodeGenerator.js +17 -6
  64. package/lib/codegen/RelayFileWriter.js +19 -40
  65. package/lib/codegen/compileRelayArtifacts.js +16 -30
  66. package/lib/codegen/sortObjectByKey.js +43 -0
  67. package/lib/codegen/writeRelayGeneratedFile.js +86 -95
  68. package/lib/core/ASTCache.js +2 -4
  69. package/lib/core/CompilerContext.js +2 -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 +23 -21
  75. package/lib/core/IRTransformer.js +8 -16
  76. package/lib/core/IRValidator.js +1 -9
  77. package/lib/core/IRVisitor.js +0 -2
  78. package/lib/core/RelayCompilerScope.js +4 -4
  79. package/lib/core/RelayGraphQLEnumsGenerator.js +12 -15
  80. package/lib/core/RelayIRTransforms.js +16 -14
  81. package/lib/core/RelayParser.js +53 -89
  82. package/lib/core/RelaySourceModuleParser.js +3 -3
  83. package/lib/core/Schema.js +61 -73
  84. package/lib/core/SchemaUtils.js +15 -1
  85. package/lib/core/getFieldDefinition.js +12 -15
  86. package/lib/core/getIdentifierForSelection.js +2 -4
  87. package/lib/core/inferRootArgumentDefinitions.js +33 -73
  88. package/lib/index.js +4 -5
  89. package/lib/language/javascript/FindGraphQLTags.js +4 -3
  90. package/lib/language/javascript/RelayFlowGenerator.js +82 -171
  91. package/lib/language/javascript/RelayFlowTypeTransformers.js +1 -3
  92. package/lib/language/javascript/RelayLanguagePluginJavaScript.js +6 -4
  93. package/lib/language/javascript/formatGeneratedModule.js +11 -2
  94. package/lib/reporters/ConsoleReporter.js +1 -3
  95. package/lib/reporters/MultiReporter.js +1 -3
  96. package/lib/runner/Artifacts.js +69 -170
  97. package/lib/runner/BufferedFilesystem.js +32 -66
  98. package/lib/runner/GraphQLASTNodeGroup.js +54 -120
  99. package/lib/runner/GraphQLNodeMap.js +14 -19
  100. package/lib/runner/Sources.js +51 -85
  101. package/lib/runner/StrictMap.js +21 -37
  102. package/lib/runner/getChangedNodeNames.js +30 -62
  103. package/lib/transforms/ApplyFragmentArgumentTransform.js +73 -59
  104. package/lib/transforms/ClientExtensionsTransform.js +12 -16
  105. package/lib/transforms/ConnectionTransform.js +30 -37
  106. package/lib/transforms/DeclarativeConnectionMutationTransform.js +167 -0
  107. package/lib/transforms/DeferStreamTransform.js +30 -73
  108. package/lib/transforms/DisallowTypenameOnRoot.js +55 -0
  109. package/lib/transforms/FieldHandleTransform.js +6 -2
  110. package/lib/transforms/FlattenTransform.js +18 -45
  111. package/lib/transforms/GenerateIDFieldTransform.js +56 -35
  112. package/lib/transforms/GenerateTypeNameTransform.js +84 -10
  113. package/lib/transforms/InlineDataFragmentTransform.js +9 -4
  114. package/lib/transforms/MaskTransform.js +17 -17
  115. package/lib/transforms/MatchTransform.js +110 -32
  116. package/lib/transforms/RefetchableFragmentTransform.js +21 -38
  117. package/lib/transforms/RelayDirectiveTransform.js +8 -3
  118. package/lib/transforms/SkipClientExtensionsTransform.js +8 -0
  119. package/lib/transforms/SkipHandleFieldTransform.js +6 -2
  120. package/lib/transforms/SkipRedundantNodesTransform.js +7 -4
  121. package/lib/transforms/SkipSplitOperationTransform.js +32 -0
  122. package/lib/transforms/SkipUnreachableNodeTransform.js +9 -10
  123. package/lib/transforms/SkipUnusedVariablesTransform.js +18 -17
  124. package/lib/transforms/SplitModuleImportTransform.js +2 -2
  125. package/lib/transforms/TestOperationTransform.js +26 -22
  126. package/lib/transforms/ValidateGlobalVariablesTransform.js +18 -30
  127. package/lib/transforms/ValidateRequiredArgumentsTransform.js +12 -16
  128. package/lib/transforms/ValidateServerOnlyDirectivesTransform.js +16 -30
  129. package/lib/transforms/ValidateUnusedVariablesTransform.js +18 -30
  130. package/lib/transforms/query-generators/FetchableQueryGenerator.js +161 -0
  131. package/lib/transforms/query-generators/NodeQueryGenerator.js +22 -3
  132. package/lib/transforms/query-generators/QueryQueryGenerator.js +2 -1
  133. package/lib/transforms/query-generators/ViewerQueryGenerator.js +1 -0
  134. package/lib/transforms/query-generators/index.js +23 -6
  135. package/lib/transforms/query-generators/utils.js +17 -16
  136. package/lib/util/RelayCompilerCache.js +2 -4
  137. package/lib/util/argumentContainsVariables.js +37 -0
  138. package/lib/util/dedupeJSONStringify.js +15 -12
  139. package/lib/util/generateAbstractTypeRefinementKey.js +24 -0
  140. package/lib/util/getModuleName.js +3 -5
  141. package/lib/util/joinArgumentDefinitions.js +3 -1
  142. package/package.json +6 -6
  143. package/relay-compiler.js +4 -4
  144. package/relay-compiler.min.js +4 -4
  145. package/reporters/ConsoleReporter.js.flow +81 -0
  146. package/reporters/MultiReporter.js.flow +43 -0
  147. package/reporters/Reporter.js.flow +19 -0
  148. package/runner/Artifacts.js.flow +219 -0
  149. package/runner/BufferedFilesystem.js.flow +194 -0
  150. package/runner/GraphQLASTNodeGroup.js.flow +176 -0
  151. package/runner/GraphQLASTUtils.js.flow +26 -0
  152. package/runner/GraphQLNodeMap.js.flow +55 -0
  153. package/runner/Sources.js.flow +214 -0
  154. package/runner/StrictMap.js.flow +96 -0
  155. package/runner/compileArtifacts.js.flow +76 -0
  156. package/runner/extractAST.js.flow +100 -0
  157. package/runner/getChangedNodeNames.js.flow +48 -0
  158. package/runner/getSchemaInstance.js.flow +36 -0
  159. package/runner/types.js.flow +37 -0
  160. package/transforms/ApplyFragmentArgumentTransform.js.flow +526 -0
  161. package/transforms/ClientExtensionsTransform.js.flow +222 -0
  162. package/transforms/ConnectionTransform.js.flow +856 -0
  163. package/transforms/DeclarativeConnectionMutationTransform.js.flow +157 -0
  164. package/transforms/DeferStreamTransform.js.flow +265 -0
  165. package/transforms/DisallowIdAsAlias.js.flow +47 -0
  166. package/transforms/DisallowTypenameOnRoot.js.flow +45 -0
  167. package/transforms/FieldHandleTransform.js.flow +80 -0
  168. package/transforms/FilterDirectivesTransform.js.flow +45 -0
  169. package/transforms/FlattenTransform.js.flow +453 -0
  170. package/transforms/GenerateIDFieldTransform.js.flow +152 -0
  171. package/transforms/GenerateTypeNameTransform.js.flow +161 -0
  172. package/transforms/InlineDataFragmentTransform.js.flow +125 -0
  173. package/transforms/InlineFragmentsTransform.js.flow +71 -0
  174. package/transforms/MaskTransform.js.flow +126 -0
  175. package/transforms/MatchTransform.js.flow +583 -0
  176. package/transforms/RefetchableFragmentTransform.js.flow +272 -0
  177. package/transforms/RelayDirectiveTransform.js.flow +97 -0
  178. package/transforms/SkipClientExtensionsTransform.js.flow +54 -0
  179. package/transforms/SkipHandleFieldTransform.js.flow +44 -0
  180. package/transforms/SkipRedundantNodesTransform.js.flow +254 -0
  181. package/transforms/SkipSplitOperationTransform.js.flow +37 -0
  182. package/transforms/SkipUnreachableNodeTransform.js.flow +149 -0
  183. package/transforms/SkipUnusedVariablesTransform.js.flow +59 -0
  184. package/transforms/SplitModuleImportTransform.js.flow +98 -0
  185. package/transforms/TestOperationTransform.js.flow +142 -0
  186. package/transforms/TransformUtils.js.flow +26 -0
  187. package/transforms/ValidateGlobalVariablesTransform.js.flow +81 -0
  188. package/transforms/ValidateRequiredArgumentsTransform.js.flow +127 -0
  189. package/transforms/ValidateServerOnlyDirectivesTransform.js.flow +112 -0
  190. package/transforms/ValidateUnusedVariablesTransform.js.flow +89 -0
  191. package/transforms/query-generators/FetchableQueryGenerator.js.flow +189 -0
  192. package/transforms/query-generators/NodeQueryGenerator.js.flow +219 -0
  193. package/transforms/query-generators/QueryQueryGenerator.js.flow +57 -0
  194. package/transforms/query-generators/ViewerQueryGenerator.js.flow +97 -0
  195. package/transforms/query-generators/index.js.flow +90 -0
  196. package/transforms/query-generators/utils.js.flow +76 -0
  197. package/util/CodeMarker.js.flow +79 -0
  198. package/{lib/core/GraphQLIR.js → util/DefaultHandleKey.js.flow} +9 -2
  199. package/util/RelayCompilerCache.js.flow +88 -0
  200. package/util/Rollout.js.flow +39 -0
  201. package/util/TimeReporter.js.flow +79 -0
  202. package/util/areEqualOSS.js.flow +123 -0
  203. package/util/argumentContainsVariables.js.flow +38 -0
  204. package/util/dedupeJSONStringify.js.flow +152 -0
  205. package/util/generateAbstractTypeRefinementKey.js.flow +29 -0
  206. package/util/getDefinitionNodeHash.js.flow +25 -0
  207. package/util/getModuleName.js.flow +39 -0
  208. package/util/joinArgumentDefinitions.js.flow +105 -0
  209. package/util/md5.js.flow +22 -0
  210. package/util/murmurHash.js.flow +94 -0
  211. package/util/nullthrowsOSS.js.flow +25 -0
  212. package/util/orList.js.flow +37 -0
  213. package/util/partitionArray.js.flow +37 -0
  214. package/lib/core/GraphQLCompilerContext.js +0 -165
  215. package/lib/core/GraphQLIRPrinter.js +0 -371
  216. package/lib/core/GraphQLIRTransformer.js +0 -344
  217. package/lib/core/GraphQLIRValidator.js +0 -218
  218. package/lib/core/GraphQLIRVisitor.js +0 -46
  219. package/lib/core/RelayCompilerError.js +0 -277
  220. package/lib/transforms/ConnectionFieldTransform.js +0 -276
@@ -0,0 +1,482 @@
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
+ invariant(
381
+ type && schema.isInputObject(type),
382
+ 'GraphQLIRPrinter: Need an InputObject type to print objects.',
383
+ );
384
+ const inputType = schema.assertInputObjectType(type);
385
+ const pairs = value.fields
386
+ .map(field => {
387
+ const fieldConfig =
388
+ type != null
389
+ ? schema.hasField(inputType, field.name)
390
+ ? schema.getFieldConfig(schema.expectField(inputType, field.name))
391
+ : null
392
+ : null;
393
+ const innerValue =
394
+ fieldConfig && printValue(schema, field.value, fieldConfig.type);
395
+ return innerValue == null ? null : field.name + ': ' + innerValue;
396
+ })
397
+ .filter(Boolean);
398
+
399
+ return '{' + pairs.join(', ') + '}';
400
+ } else if (value.kind === 'ListValue') {
401
+ invariant(
402
+ type && schema.isList(type),
403
+ 'GraphQLIRPrinter: Need a type in order to print arrays.',
404
+ );
405
+ const innerType = schema.getListItemType(type);
406
+ return `[${value.items
407
+ .map(i => printValue(schema, i, innerType))
408
+ .join(', ')}]`;
409
+ } else if (value.value != null) {
410
+ return printLiteral(schema, value.value, type);
411
+ } else {
412
+ return null;
413
+ }
414
+ }
415
+
416
+ function printLiteral(schema: Schema, value: mixed, type: ?TypeID): string {
417
+ if (value == null) {
418
+ return JSON.stringify(value) ?? 'null';
419
+ }
420
+ if (type != null && schema.isNonNull(type)) {
421
+ type = schema.getNullableType(type);
422
+ }
423
+
424
+ if (type && schema.isEnum(type)) {
425
+ let result = schema.serialize(schema.assertEnumType(type), value);
426
+ if (result == null && typeof value === 'string') {
427
+ // For backwards compatibility, print invalid input values as-is. This
428
+ // can occur with literals defined as an @argumentDefinitions
429
+ // defaultValue.
430
+ result = value;
431
+ }
432
+ invariant(
433
+ typeof result === 'string',
434
+ 'IRPrinter: Expected value of type %s to be a valid enum value, got `%s`.',
435
+ schema.getTypeString(type),
436
+ JSON.stringify(value) ?? 'null',
437
+ );
438
+ return result;
439
+ } else if (type && (schema.isId(type) || schema.isInt(type))) {
440
+ return JSON.stringify(value) ?? '';
441
+ } else if (type && schema.isScalar(type)) {
442
+ const result = schema.serialize(schema.assertScalarType(type), value);
443
+ return JSON.stringify(result) ?? '';
444
+ } else if (Array.isArray(value)) {
445
+ invariant(
446
+ type && schema.isList(type),
447
+ 'IRPrinter: Need a type in order to print arrays.',
448
+ );
449
+ const itemType = schema.getListItemType(type);
450
+ return (
451
+ '[' +
452
+ value.map(item => printLiteral(schema, item, itemType)).join(', ') +
453
+ ']'
454
+ );
455
+ } else if (type && schema.isList(type) && value != null) {
456
+ // Not an array, but still a list. Treat as list-of-one as per spec 3.1.7:
457
+ // http://facebook.github.io/graphql/October2016/#sec-Lists
458
+ return printLiteral(schema, value, schema.getListItemType(type));
459
+ } else if (typeof value === 'object' && value != null) {
460
+ const fields = [];
461
+ invariant(
462
+ type && schema.isInputObject(type),
463
+ 'IRPrinter: Need an InputObject type to print objects.',
464
+ );
465
+ const inputType = schema.assertInputObjectType(type);
466
+ for (const key in value) {
467
+ if (value.hasOwnProperty(key)) {
468
+ const fieldConfig = schema.getFieldConfig(
469
+ schema.expectField(inputType, key),
470
+ );
471
+ fields.push(
472
+ key + ': ' + printLiteral(schema, value[key], fieldConfig.type),
473
+ );
474
+ }
475
+ }
476
+ return '{' + fields.join(', ') + '}';
477
+ } else {
478
+ return JSON.stringify(value) ?? 'null';
479
+ }
480
+ }
481
+
482
+ module.exports = {print, printField, printArguments, printDirectives};