relay-compiler 1.3.0 → 1.5.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (137) hide show
  1. package/LICENSE +16 -26
  2. package/bin/relay-compiler +7348 -5939
  3. package/index.js +3 -6
  4. package/lib/{FileParser.js → ASTCache.js} +17 -14
  5. package/lib/ASTConvert.js +84 -70
  6. package/lib/CodegenDirectory.js +122 -28
  7. package/lib/{RelayCodegenRunner.js → CodegenRunner.js} +110 -186
  8. package/lib/CodegenTypes.js +12 -0
  9. package/lib/{RelayCodegenWatcher.js → CodegenWatcher.js} +53 -43
  10. package/lib/DefaultHandleKey.js +2 -4
  11. package/lib/DotGraphQLParser.js +27 -0
  12. package/lib/FilterDirectivesTransform.js +11 -11
  13. package/lib/FindGraphQLTags.js +33 -52
  14. package/lib/FlattenTransform.js +197 -0
  15. package/lib/GraphQLCompilerContext.js +158 -0
  16. package/lib/GraphQLCompilerProfiler.js +271 -0
  17. package/lib/GraphQLCompilerPublic.js +27 -22
  18. package/lib/GraphQLCompilerUserError.js +26 -0
  19. package/lib/GraphQLConsoleReporter.js +58 -0
  20. package/lib/GraphQLIR.js +12 -0
  21. package/lib/{RelayPrinter.js → GraphQLIRPrinter.js} +42 -38
  22. package/lib/{RelayIRTransformer.js → GraphQLIRTransformer.js} +47 -38
  23. package/lib/GraphQLIRTransforms.js +6 -15
  24. package/lib/{RelayIRVisitor.js → GraphQLIRVisitor.js} +7 -6
  25. package/lib/GraphQLMultiReporter.js +50 -0
  26. package/lib/GraphQLParser.js +743 -0
  27. package/lib/GraphQLReporter.js +12 -0
  28. package/lib/GraphQLSchemaUtils.js +10 -36
  29. package/lib/GraphQLValidator.js +13 -15
  30. package/lib/{RelayWatchmanClient.js → GraphQLWatchmanClient.js} +15 -17
  31. package/lib/InlineFragmentsTransform.js +48 -0
  32. package/lib/PatchedBabelGenerator.js +58 -0
  33. package/lib/RelayApplyFragmentArgumentTransform.js +37 -18
  34. package/lib/RelayCodeGenerator.js +130 -60
  35. package/lib/RelayCompilerBin.js +80 -35
  36. package/lib/RelayCompilerCache.js +18 -11
  37. package/lib/RelayCompilerPublic.js +24 -10
  38. package/lib/RelayCompilerScope.js +2 -4
  39. package/lib/RelayConcreteNode.js +31 -14
  40. package/lib/RelayConnectionConstants.js +2 -4
  41. package/lib/RelayConnectionTransform.js +34 -38
  42. package/lib/RelayDefaultHandleKey.js +2 -4
  43. package/lib/RelayDeferrableFragmentTransform.js +464 -0
  44. package/lib/RelayError.js +2 -6
  45. package/lib/RelayFieldHandleTransform.js +15 -11
  46. package/lib/RelayFileWriter.js +119 -98
  47. package/lib/RelayFlowBabelFactories.js +113 -0
  48. package/lib/RelayFlowGenerator.js +180 -200
  49. package/lib/RelayFlowTypeTransformers.js +109 -0
  50. package/lib/RelayGenerateIDFieldTransform.js +131 -0
  51. package/lib/RelayGenerateTypeNameTransform.js +75 -0
  52. package/lib/RelayGraphQLEnumsGenerator.js +65 -0
  53. package/lib/RelayIRTransforms.js +19 -23
  54. package/lib/RelayInternalTypes.js +2 -5
  55. package/lib/RelayInternals.js +2 -5
  56. package/lib/RelayJSModuleParser.js +64 -0
  57. package/lib/RelayMaskTransform.js +129 -0
  58. package/lib/RelayMetricsRecorder.js +9 -9
  59. package/lib/RelayMockRenderer.js +3 -8
  60. package/lib/RelayNetworkDebug.js +4 -7
  61. package/lib/RelayParser.js +28 -645
  62. package/lib/RelayProfiler.js +7 -7
  63. package/lib/RelayQueryCaching.js +2 -5
  64. package/lib/RelayRelayDirectiveTransform.js +47 -33
  65. package/lib/RelayRuntimeTypes.js +22 -0
  66. package/lib/RelayShallowMock.js +4 -7
  67. package/lib/RelaySkipHandleFieldTransform.js +13 -11
  68. package/lib/RelayTaskQueue.js +2 -5
  69. package/lib/RelayTransformUtils.js +20 -0
  70. package/lib/RelayTypes.js +2 -5
  71. package/lib/RelayValidator.js +9 -8
  72. package/lib/RelayViewerHandleTransform.js +22 -18
  73. package/lib/SkipClientFieldTransform.js +36 -53
  74. package/lib/SkipRedundantNodesTransform.js +22 -29
  75. package/lib/SkipUnreachableNodeTransform.js +57 -36
  76. package/lib/SourceControl.js +61 -0
  77. package/lib/StripUnusedVariablesTransform.js +86 -41
  78. package/lib/areEqualOSS.js +2 -4
  79. package/lib/compileRelayArtifacts.js +72 -0
  80. package/lib/dedent.js +2 -5
  81. package/lib/dedupeJSONStringify.js +132 -0
  82. package/lib/deepFreeze.js +3 -5
  83. package/lib/deepMergeAssignments.js +68 -0
  84. package/lib/filterContextForNode.js +5 -7
  85. package/lib/formatGeneratedModule.js +5 -9
  86. package/lib/{getIdentifierForRelayArgumentValue.js → getIdentifierForArgumentValue.js} +8 -10
  87. package/lib/getIdentifierForSelection.js +37 -0
  88. package/lib/getLiteralArgumentValues.js +26 -0
  89. package/lib/getModuleName.js +2 -4
  90. package/lib/getRelayHandleKey.js +2 -4
  91. package/lib/isCompatibleRelayFragmentType.js +2 -5
  92. package/lib/isEquivalentType.js +55 -0
  93. package/lib/isPromise.js +2 -5
  94. package/lib/isScalarAndEqual.js +3 -5
  95. package/lib/murmurHash.js +2 -4
  96. package/lib/nullthrowsOSS.js +7 -5
  97. package/lib/recycleNodesInto.js +2 -4
  98. package/lib/relayUnstableBatchedUpdates.js +2 -5
  99. package/lib/relayUnstableBatchedUpdates.native.js +2 -5
  100. package/lib/requestsForOperation.js +75 -0
  101. package/lib/simpleClone.js +2 -4
  102. package/lib/stableCopy.js +35 -0
  103. package/lib/testEditDistance.js +2 -5
  104. package/lib/throwFailedPromise.js +2 -5
  105. package/lib/writeRelayGeneratedFile.js +84 -50
  106. package/package.json +16 -15
  107. package/relay-compiler.js +7208 -5872
  108. package/relay-compiler.min.js +7200 -5867
  109. package/ARCHITECTURE.md +0 -94
  110. package/PATENTS +0 -33
  111. package/lib/AutoAliasTransform.js +0 -80
  112. package/lib/GraphQLFileParser.js +0 -27
  113. package/lib/GraphQLTextParser.js +0 -46
  114. package/lib/RelayCodegenTypes.js +0 -14
  115. package/lib/RelayCompiledTypes.js +0 -13
  116. package/lib/RelayCompiler.js +0 -144
  117. package/lib/RelayCompilerContext.js +0 -133
  118. package/lib/RelayCompilerUserError.js +0 -30
  119. package/lib/RelayConsoleReporter.js +0 -40
  120. package/lib/RelayFileIRParser.js +0 -66
  121. package/lib/RelayFlattenTransform.js +0 -278
  122. package/lib/RelayFlowParser.js +0 -188
  123. package/lib/RelayGenerateRequisiteFieldsTransform.js +0 -189
  124. package/lib/RelayIR.js +0 -14
  125. package/lib/RelayMultiReporter.js +0 -40
  126. package/lib/RelayReporter.js +0 -14
  127. package/lib/RelayTestSchema.js +0 -21
  128. package/lib/formatStorageKey.js +0 -37
  129. package/lib/getIdentifierForRelaySelection.js +0 -54
  130. package/lib/getRelayLiteralArgumentValues.js +0 -28
  131. package/lib/parseGraphQLText.js +0 -33
  132. package/lib/prettyStringify.js +0 -35
  133. package/lib/printFlowTypes.js +0 -282
  134. package/lib/stableJSONStringify.js +0 -45
  135. package/lib/stableJSONStringifyOSS.js +0 -44
  136. package/lib/transformInputObjectToIR.js +0 -85
  137. package/lib/writeLegacyFlowFile.js +0 -24
@@ -1,66 +0,0 @@
1
- /**
2
- * Copyright (c) 2013-present, Facebook, Inc.
3
- * All rights reserved.
4
- *
5
- * This source code is licensed under the BSD-style license found in the
6
- * LICENSE file in the root directory of this source tree. An additional grant
7
- * of patent rights can be found in the PATENTS file in the same directory.
8
- *
9
- * @providesModule RelayFileIRParser
10
- *
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _toConsumableArray3 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray'));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
19
-
20
- // Throws an error if parsing the file fails
21
- function parseFile(baseDir, file) {
22
- var text = require('fs').readFileSync(require('path').join(baseDir, file.relPath), 'utf8');
23
-
24
- require('fbjs/lib/invariant')(text.indexOf('graphql') >= 0, 'RelayFileIRParser: Files should be filtered before passed to the ' + 'parser, got unfiltered file `%s`.', file);
25
-
26
- var astDefinitions = [];
27
- require('./FindGraphQLTags').memoizedFind(text, baseDir, file).forEach(function (_ref) {
28
- var tag = _ref.tag,
29
- template = _ref.template;
30
-
31
- if (!(tag === 'graphql' || tag === 'graphql.experimental')) {
32
- throw new Error('Invalid tag ' + tag + ' in ' + file.relPath + '. ' + 'Expected graphql`` (common case) or ' + 'graphql.experimental`` (if using experimental directives).');
33
- }
34
- if (tag !== 'graphql.experimental' && /@argument(Definition)?s\b/.test(template)) {
35
- throw new Error('Unexpected use of fragment variables: @arguments and ' + '@argumentDefinitions are only supported in ' + 'graphql.experimental literals. Source: ' + template);
36
- }
37
- var ast = require('graphql').parse(new (require('graphql').Source)(template, file.relPath));
38
- require('fbjs/lib/invariant')(ast.definitions.length, 'RelayFileIRParser: Expected GraphQL text to contain at least one ' + 'definition (fragment, mutation, query, subscription), got `%s`.', template);
39
-
40
- astDefinitions.push.apply(astDefinitions, (0, _toConsumableArray3['default'])(ast.definitions));
41
- });
42
-
43
- return {
44
- kind: 'Document',
45
- definitions: astDefinitions
46
- };
47
- }
48
-
49
- function getParser(baseDir) {
50
- return new (require('./FileParser'))({
51
- baseDir: baseDir,
52
- parse: parseFile
53
- });
54
- }
55
-
56
- function getFileFilter(baseDir) {
57
- return function (file) {
58
- var text = require('fs').readFileSync(require('path').join(baseDir, file.relPath), 'utf8');
59
- return text.indexOf('graphql') >= 0;
60
- };
61
- }
62
-
63
- module.exports = {
64
- getParser: getParser,
65
- getFileFilter: getFileFilter
66
- };
@@ -1,278 +0,0 @@
1
- /**
2
- * Copyright (c) 2013-present, Facebook, Inc.
3
- * All rights reserved.
4
- *
5
- * This source code is licensed under the BSD-style license found in the
6
- * LICENSE file in the root directory of this source tree. An additional grant
7
- * of patent rights can be found in the PATENTS file in the same directory.
8
- *
9
- * @providesModule RelayFlattenTransform
10
- * @format
11
- */
12
-
13
- 'use strict';
14
-
15
- var _extends3 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
16
-
17
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
18
-
19
- var _require = require('graphql'),
20
- GraphQLNonNull = _require.GraphQLNonNull,
21
- GraphQLList = _require.GraphQLList;
22
-
23
- var RELAY = 'relay';
24
-
25
- var getRawType = require('./GraphQLSchemaUtils').getRawType,
26
- isAbstractType = require('./GraphQLSchemaUtils').isAbstractType;
27
-
28
- /**
29
- * Transform that flattens inline fragments, fragment spreads, and conditionals.
30
- *
31
- * Inline fragments are inlined (replaced with their selections) when:
32
- * - The fragment type matches the type of its parent.
33
- * - The fragment has an abstract type and the `flattenAbstractTypes` option has
34
- * been set.
35
- * - The 'flattenInlineFragments' option has been set.
36
- *
37
- * Fragment spreads are inlined when the `flattenFragmentSpreads` option is set.
38
- * In this case the fragment is converted to an inline fragment, which is
39
- * then inlined according to the rules above.
40
- *
41
- * Conditions are inlined when the `flattenConditions` option is set.
42
- * In this case the condition is converted to an inline fragment, which is then
43
- * inlined according to the rules above.
44
- */
45
- function transform(context, options) {
46
- var flattenOptions = {
47
- flattenAbstractTypes: !!(options && options.flattenAbstractTypes),
48
- flattenFragmentSpreads: !!(options && options.flattenFragmentSpreads),
49
- flattenInlineFragments: !!(options && options.flattenInlineFragments),
50
- flattenConditions: !!(options && options.flattenConditions)
51
- };
52
- return context.documents().reduce(function (ctx, node) {
53
- if (flattenOptions.flattenFragmentSpreads && node.kind === 'Fragment') {
54
- return ctx;
55
- }
56
- var state = {
57
- kind: 'FlattenState',
58
- node: node,
59
- selections: {},
60
- type: node.type
61
- };
62
- visitNode(context, flattenOptions, state, node);
63
- var flattenedNode = buildNode(state);
64
- require('fbjs/lib/invariant')(flattenedNode.kind === 'Root' || flattenedNode.kind === 'Fragment', 'RelayFlattenTransform: Expected Root `%s` to flatten back to a Root ' + ' or Fragment.', node.name);
65
- return ctx.add(flattenedNode);
66
- }, new (require('./RelayCompilerContext'))(context.schema));
67
- }
68
-
69
- function buildNode(state) {
70
- return (0, _extends3['default'])({}, state.node, {
71
- selections: Object.keys(state.selections).map(function (key) {
72
- var selectionState = state.selections[key];
73
- if (selectionState.kind === 'FragmentSpread' || selectionState.kind === 'ScalarField') {
74
- return selectionState;
75
- } else if (selectionState.kind === 'FlattenState') {
76
- var _node = buildNode(selectionState);
77
- require('fbjs/lib/invariant')(_node.kind !== 'Root' && _node.kind !== 'Fragment', 'RelayFlattenTransform: got a `%s`, expected a selection.', _node.kind);
78
- return _node;
79
- } else {
80
- // $FlowIssue: this is provably unreachable
81
- require('fbjs/lib/invariant')(false, 'RelayFlattenTransform: Unexpected kind `%s`.', selectionState.kind);
82
- }
83
- })
84
- });
85
- }
86
-
87
- /**
88
- * @internal
89
- */
90
- function visitNode(context, options, state, node) {
91
- node.selections.forEach(function (selection) {
92
- if (selection.kind === 'FragmentSpread' && shouldFlattenFragmentSpread(selection, options)) {
93
- require('fbjs/lib/invariant')(!selection.args.length, 'RelayFlattenTransform: Cannot flatten fragment spread `%s` with ' + 'arguments. Use the `ApplyFragmentArgumentTransform` before flattening', selection.name);
94
- var fragment = context.get(selection.name);
95
- require('fbjs/lib/invariant')(fragment && fragment.kind === 'Fragment', 'RelayFlattenTransform: Unknown fragment `%s`.', selection.name);
96
- // Replace the spread with an inline fragment containing the fragment's
97
- // contents
98
- selection = {
99
- directives: selection.directives,
100
- kind: 'InlineFragment',
101
- selections: fragment.selections,
102
- typeCondition: fragment.type
103
- };
104
- }
105
- if (selection.kind === 'Condition' && options.flattenConditions) {
106
- selection = {
107
- directives: [],
108
- kind: 'InlineFragment',
109
- selections: selection.selections,
110
- typeCondition: state.type
111
- };
112
- }
113
- if (selection.kind === 'InlineFragment' && shouldFlattenInlineFragment(selection, options, state)) {
114
- visitNode(context, options, state, selection);
115
- return;
116
- }
117
- var nodeIdentifier = require('./getIdentifierForRelaySelection')(selection);
118
- if (selection.kind === 'Condition' || selection.kind === 'InlineFragment') {
119
- var selectionState = state.selections[nodeIdentifier];
120
- if (!selectionState) {
121
- selectionState = state.selections[nodeIdentifier] = {
122
- kind: 'FlattenState',
123
- node: selection,
124
- selections: {},
125
- type: selection.kind === 'InlineFragment' ? selection.typeCondition : selection.type
126
- };
127
- }
128
- visitNode(context, options, selectionState, selection);
129
- } else if (selection.kind === 'FragmentSpread') {
130
- state.selections[nodeIdentifier] = selection;
131
- } else if (selection.kind === 'LinkedField') {
132
- var _selectionState = state.selections[nodeIdentifier];
133
- if (!_selectionState) {
134
- _selectionState = state.selections[nodeIdentifier] = {
135
- kind: 'FlattenState',
136
- node: selection,
137
- selections: {},
138
- type: selection.type
139
- };
140
- } else {
141
- var prevSelection = _selectionState.node;
142
- // Validate unique args for a given alias
143
- require('fbjs/lib/invariant')(areEqualFields(selection, prevSelection), 'RelayFlattenTransform: Expected all fields with the alias `%s` ' + 'to have the same name/arguments. Got `%s` and `%s`.', nodeIdentifier, showField(selection), showField(prevSelection));
144
- // merge fields
145
- var handles = dedupe(prevSelection.handles, selection.handles);
146
- _selectionState.node = (0, _extends3['default'])({}, selection, {
147
- handles: handles
148
- });
149
- }
150
- visitNode(context, options, _selectionState, selection);
151
- } else if (selection.kind === 'ScalarField') {
152
- var _prevSelection = state.selections[nodeIdentifier];
153
- if (_prevSelection) {
154
- require('fbjs/lib/invariant')(areEqualFields(selection, _prevSelection), 'RelayFlattenTransform: Expected all fields with the alias `%s` ' + 'to have the same name/arguments. Got `%s` and `%s`.', nodeIdentifier, showField(selection), showField(_prevSelection));
155
- if (selection.handles || _prevSelection.handles) {
156
- var _handles = dedupe(selection.handles, _prevSelection.handles);
157
- selection = (0, _extends3['default'])({}, selection, {
158
- handles: _handles
159
- });
160
- }
161
- }
162
- state.selections[nodeIdentifier] = selection;
163
- } else {
164
- require('fbjs/lib/invariant')(false, 'RelayFlattenTransform: Unknown kind `%s`.', selection.kind);
165
- }
166
- });
167
- }
168
-
169
- /**
170
- * @internal
171
- */
172
- function shouldFlattenFragmentSpread(fragment, options) {
173
- if (options.flattenFragmentSpreads) {
174
- return true;
175
- }
176
- var relayDirective = fragment.directives.find(function (_ref) {
177
- var name = _ref.name;
178
- return name === RELAY;
179
- });
180
- if (!relayDirective) {
181
- return false;
182
- }
183
-
184
- var _getRelayLiteralArgum = require('./getRelayLiteralArgumentValues')(relayDirective.args),
185
- mask = _getRelayLiteralArgum.mask;
186
-
187
- return mask === false;
188
- }
189
-
190
- /**
191
- * @internal
192
- */
193
- function shouldFlattenInlineFragment(fragment, options, state) {
194
- // Right now, both the fragment's and state's types could be undefined.
195
- if (!fragment.typeCondition) {
196
- return !state.type;
197
- } else if (!state.type) {
198
- return false;
199
- }
200
- return isEquivalentType(fragment.typeCondition, state.type) || options.flattenInlineFragments || options.flattenAbstractTypes && isAbstractType(getRawType(fragment.typeCondition));
201
- }
202
-
203
- /**
204
- * @internal
205
- */
206
- function showField(field) {
207
- var alias = field.alias ? field.alias + ' ' : '';
208
- return '' + alias + field.name + '(' + JSON.stringify(field.args) + ')';
209
- }
210
-
211
- /**
212
- * @internal
213
- *
214
- * Verify that two fields are equal in all properties other than their
215
- * selections.
216
- */
217
- function areEqualFields(thisField, thatField) {
218
- return thisField.kind === thatField.kind && thisField.name === thatField.name && thisField.alias === thatField.alias && require('./areEqualOSS')(thisField.args, thatField.args);
219
- }
220
-
221
- /**
222
- * @internal
223
- */
224
- function dedupe() {
225
- var uniqueItems = new Map();
226
-
227
- for (var _len = arguments.length, arrays = Array(_len), _key = 0; _key < _len; _key++) {
228
- arrays[_key] = arguments[_key];
229
- }
230
-
231
- arrays.forEach(function (items) {
232
- items && items.forEach(function (item) {
233
- uniqueItems.set(require('./stableJSONStringifyOSS')(item), item);
234
- });
235
- });
236
- return Array.from(uniqueItems.values());
237
- }
238
-
239
- /**
240
- *
241
- * @internal
242
- * Determine if a type is the same type (same name and class) as another type.
243
- * Needed if we're comparing IRs created at different times: we don't yet have
244
- * an IR schema, so the type we assign to an IR field could be !== than
245
- * what we assign to it after adding some schema definitions or extensions.
246
- */
247
- function isEquivalentType(typeA, typeB) {
248
- // Easy short-circuit: equal types are equal.
249
- if (typeA === typeB) {
250
- return true;
251
- }
252
-
253
- // If either type is non-null, the other must also be non-null.
254
- if (typeA instanceof GraphQLNonNull && typeB instanceof GraphQLNonNull) {
255
- return isEquivalentType(typeA.ofType, typeB.ofType);
256
- }
257
-
258
- // If either type is a list, the other must also be a list.
259
- if (typeA instanceof GraphQLList && typeB instanceof GraphQLList) {
260
- return isEquivalentType(typeA.ofType, typeB.ofType);
261
- }
262
-
263
- // Make sure the two types are of the same class
264
- if (typeA.constructor.name === typeB.constructor.name) {
265
- var rawA = getRawType(typeA);
266
- var rawB = getRawType(typeB);
267
-
268
- // And they must have the exact same name
269
- return rawA.name === rawB.name;
270
- }
271
-
272
- // Otherwise the types are not equal.
273
- return false;
274
- }
275
-
276
- module.exports = {
277
- transform: transform
278
- };
@@ -1,188 +0,0 @@
1
- /**
2
- * Copyright (c) 2013-present, Facebook, Inc.
3
- * All rights reserved.
4
- *
5
- * This source code is licensed under the BSD-style license found in the
6
- * LICENSE file in the root directory of this source tree. An additional grant
7
- * of patent rights can be found in the PATENTS file in the same directory.
8
- *
9
- *
10
- * @providesModule RelayFlowParser
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _toConsumableArray3 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray'));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
19
-
20
- var _require = require('./GraphQLSchemaUtils'),
21
- isOperationDefinitionAST = _require.isOperationDefinitionAST;
22
-
23
- var _require2 = require('graphql'),
24
- ArgumentsOfCorrectTypeRule = _require2.ArgumentsOfCorrectTypeRule,
25
- DefaultValuesOfCorrectTypeRule = _require2.DefaultValuesOfCorrectTypeRule,
26
- FieldsOnCorrectTypeRule = _require2.FieldsOnCorrectTypeRule,
27
- formatError = _require2.formatError,
28
- FragmentsOnCompositeTypesRule = _require2.FragmentsOnCompositeTypesRule,
29
- KnownArgumentNamesRule = _require2.KnownArgumentNamesRule,
30
- KnownTypeNamesRule = _require2.KnownTypeNamesRule,
31
- parse = _require2.parse,
32
- PossibleFragmentSpreadsRule = _require2.PossibleFragmentSpreadsRule,
33
- ProvidedNonNullArgumentsRule = _require2.ProvidedNonNullArgumentsRule,
34
- Source = _require2.Source,
35
- validate = _require2.validate,
36
- VariablesInAllowedPositionRule = _require2.VariablesInAllowedPositionRule;
37
-
38
- var RELAY_CLASSIC_MUTATION = '__RelayClassicMutation__';
39
-
40
- /**
41
- * Validates that a given DocumentNode is properly formed. Returns an Array
42
- * of ValidationErrors if there are errors.
43
- */
44
- function validateDocument(document, documentName, schema) {
45
- require('fbjs/lib/invariant')(document.definitions.length === 1, 'You supplied a GraphQL document named `%s` with %d definitions, but ' + 'it must have exactly one definition.', documentName, document.definitions.length);
46
- var definition = document.definitions[0];
47
- var isMutation = definition.kind === 'OperationDefinition' && definition.operation === 'mutation';
48
-
49
- var rules = [ArgumentsOfCorrectTypeRule, DefaultValuesOfCorrectTypeRule, FieldsOnCorrectTypeRule, FragmentsOnCompositeTypesRule, KnownArgumentNamesRule, KnownTypeNamesRule, PossibleFragmentSpreadsRule, VariablesInAllowedPositionRule];
50
- if (!isMutation) {
51
- rules.push(ProvidedNonNullArgumentsRule);
52
- }
53
- var validationErrors = validate(schema, document, rules);
54
-
55
- if (validationErrors && validationErrors.length > 0) {
56
- return validationErrors.map(formatError);
57
- }
58
- return null;
59
- }
60
-
61
- /**
62
- * Parses a given string containing one or more GraphQL operations into an array
63
- * of GraphQL documents.
64
- */
65
- function parseRelayGraphQL(source, schema) {
66
- var sourceName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default';
67
-
68
- // We need to ignore these directives. The RelayParser cannot handle these
69
- // directives, so this needs to happen here.
70
- var PATTERN_LIST = ['@relay(pattern:true)', '@fixme_fat_interface'];
71
- var strippedSource = source.replace(/ /g, '');
72
- var patternFound = PATTERN_LIST.some(function (pattern) {
73
- var isSubstring = strippedSource.indexOf(pattern) !== -1;
74
- if (isSubstring) {
75
- console.warn('Skipping Relay.QL template string because it contains ' + pattern + ': ' + sourceName);
76
- }
77
- return isSubstring;
78
- });
79
- if (patternFound) {
80
- return [];
81
- }
82
-
83
- var ast = null;
84
- try {
85
- ast = parse(new Source(source, sourceName));
86
- } catch (e) {
87
- console.error('\n-- GraphQL Parsing Error --\n');
88
- console.error(['File: ' + sourceName, 'Error: ' + e.message].join('\n'));
89
- return [];
90
- }
91
-
92
- var validationErrors = validateDocument(ast, sourceName, schema);
93
- if (validationErrors) {
94
- var errorMessages = [];
95
- var sourceLines = source.split('\n');
96
- validationErrors.forEach(function (_ref) {
97
- var message = _ref.message,
98
- locations = _ref.locations;
99
-
100
- errorMessages.push(message);
101
- console.error('\n-- GraphQL Validation Error --\n');
102
- console.error(['File: ' + sourceName, 'Error: ' + message, 'Source:'].join('\n'));
103
- locations.forEach(function (location) {
104
- var preview = sourceLines[location.line - 1];
105
- if (preview) {
106
- console.error(['> ', '> ' + preview, '> ' + ' '.repeat(location.column - 1) + '^^^'].join('\n'));
107
- }
108
- });
109
- });
110
- return [];
111
- }
112
-
113
- var _ast = ast,
114
- definitions = _ast.definitions;
115
-
116
- definitions.forEach(function (definition) {
117
- if (definition.kind !== 'OperationDefinition' || definition.operation !== 'mutation') {
118
- return;
119
- }
120
-
121
- var selections = definition.selectionSet.selections;
122
- // As of now, FB mutations should only have one input.
123
- require('fbjs/lib/invariant')(selections.length <= 1, 'Mutations should only have one argument, ' + selections.length + ' found.');
124
-
125
- var mutationField = selections[0];
126
- require('fbjs/lib/invariant')(mutationField.kind === 'Field', 'RelayFlowParser: Expected the first selection of a mutation to be a ' + 'field, got `%s`.', mutationField.kind);
127
- if (definition.name == null) {
128
- // We need to manually add a `name` and a selection to each `selectionSet`
129
- // in order for this to be a valid GraphQL document. The RelayParser will
130
- // throw an error if we give it a "classic" mutation. `__typename` is a
131
- // valid field in *all* mutation payloads.
132
- definition.name = {
133
- kind: 'Name',
134
- value: RELAY_CLASSIC_MUTATION
135
- };
136
- mutationField.selectionSet = {
137
- kind: 'SelectionSet',
138
- selections: [{
139
- kind: 'Field',
140
- name: {
141
- kind: 'Name',
142
- value: '__typename'
143
- }
144
- }]
145
- };
146
- }
147
- });
148
-
149
- var nodes = [];
150
- definitions.forEach(function (definition) {
151
- if (isOperationDefinitionAST(definition)) {
152
- nodes.push(require('./RelayParser').transform(schema, definition));
153
- }
154
- });
155
- return nodes;
156
- }
157
-
158
- /**
159
- * Parses each extracted template literal from an array of ExtractedRelayTags
160
- * into a GraphQL Document type. Each element in the returned array is a
161
- * ExtractedGQLDocuments type which includes the filename.
162
- */
163
- function transformFiles(extractedTags, schema) {
164
- var gqlMapping = [];
165
- extractedTags.forEach(function (file) {
166
- var documents = [];
167
- file.tags.forEach(function (tag) {
168
- var transformed = parseRelayGraphQL(tag, schema, file.filename);
169
- if (transformed.length) {
170
- documents.push.apply(documents, (0, _toConsumableArray3['default'])(transformed));
171
- }
172
- });
173
-
174
- if (documents.length) {
175
- gqlMapping.push({
176
- filename: file.filename,
177
- documents: documents
178
- });
179
- }
180
- });
181
- return gqlMapping;
182
- }
183
-
184
- module.exports = {
185
- transformFiles: transformFiles,
186
- parse: parseRelayGraphQL,
187
- RELAY_CLASSIC_MUTATION: RELAY_CLASSIC_MUTATION
188
- };