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
package/ARCHITECTURE.md DELETED
@@ -1,94 +0,0 @@
1
- # Relay Compiler
2
-
3
- The compiler is a set of modules designed to extract GraphQL documents from across a codebase, transform/optimize them, and generate build artifacts. Examples of common types of artifacts include optimized GraphQL to persist to your server, runtime representations of the queries for use with GraphQL clients such as the Relay runtime, or generated source code for use with GraphQL frameworks for compiled languages (Java/Swift/etc).
4
-
5
- ## Data Flow
6
-
7
- The high-level flow of data through the compiler is represented in the following diagram:
8
-
9
- ```
10
- ┌─────────────┐┌─────────────┐
11
- │ GraphQL ││ Schema │
12
- └─────────────┘└─────────────┘
13
- │ │ parse
14
- └───────┬──────┘
15
-
16
- ┌────────────────────────────┐
17
- │ CompilerContext │
18
- │ │
19
- │ ┌─────┐ ┌─────┐ ┌─────┐ │──┐
20
- │ │ IR │ │ IR │ │ ... │ │ │
21
- │ └─────┘ └─────┘ └─────┘ │ │
22
- └────────────────────────────┘ │ transform/
23
- │ │ ▲ │ optimize
24
- │ │ └────────────┘
25
- │ │
26
- │ └──────────┐
27
- │ print │ codegen
28
- ▼ ▼
29
- ┌─────────────┐ ┌─────────────┐
30
- │ GraphQL │ │ Artifacts │
31
- └─────────────┘ └─────────────┘
32
- ```
33
-
34
- 1. GraphQL text is extracted from source files and "parsed" into an intermediate representation (IR) using information from the schema.
35
- 2. The set of IR documents forms a CompilerContext, which is then transformed and optimized.
36
- 3. Finally, GraphQL is printed (e.g. to files, saved to a database, etc) and any artifacts are generated.
37
-
38
- ## Data Types & Modules
39
-
40
- The compiler module is composed of a set of core building blocks as well as a helper that packages them together in an easy to use API. Some of the main data types and modules in the compiler are as follows:
41
-
42
- - `IR` (Intermediate Representation): an (effectively immutable) representation of a GraphQL document (query, fragment, field, etc) as a tree structure, including type information from a schema. Compared to the standard GraphQL AST (produced by e.g. `graphql-js`) the main difference is that it encodes more of the semantics of GraphQL. For example, conditional branches (`@include` and `@skip`) are represented directly, making it easier to target optimizations for these directives (One such optimization is to merge sibling fields with the same condition, potentially reducing the number of conditionals that must be evaluated at runtime).
43
- - `CompilerContext`: an immutable representation of a corpus of GraphQL documents. It contains the schema and a mapping of document names to document representations (as IR, see above).
44
- - `Transform`: a "map"-like function that accepts a `CompilerContext` as input and returns a new, modified context as output. Examples below.
45
- - `Parser`: Converts a GraphQL schema and raw GraphQL text into typed IR objects.
46
- - `Printer`: a function that accepts IR and converts it to a GraphQL string.
47
-
48
- The `RelayCompiler` module is a helper class that demonstrates one way of combining these primitives. It takes IR transforms, and given IR definitions, constructs a CompilerContext from them, transforming them, and generating output artifacts intended for use with Relay runtime.
49
-
50
- ## Transforms
51
-
52
- One of the main goals of the compiler is to provide a consistent platform for writing tools that transform or optimize GraphQL. This includes the ability to experiment with new directives by transforming them away at compile time. Transform functions should typically perform a single type of modification - it's expected that an app will have multiple transforms configured in the compiler instance.
53
-
54
- Here are a few examples of some of the included transforms:
55
-
56
- - `FlattenTransform`: Reduces extraneous levels of indirection in a query, inlining fields from anonymous fragments wherever they match the parent type. This can be beneficial when generating code to read the results of a query or process query results, as it reduces duplicate field processing. For example:
57
-
58
- ```
59
- # before: `id` is processed twice
60
- foo { # type FooType
61
- id
62
- ... on FooType { # matches the parent type, so this is extraneous
63
- id
64
- }
65
- }
66
-
67
- # after: `id` is processed once
68
- foo {
69
- id
70
- }
71
- ```
72
-
73
- - `SkipRedundantNodeTransform`: A more advanced version of flattening, this eliminates more complex cases of field duplication such as when a field is fetched both unconditionally and conditionally, or is fetched by two different sub-fragments. For example:
74
-
75
- ```
76
- # before: `id` processed up to 2x
77
- foo {
78
- bar {
79
- id
80
- }
81
- ... on FooType @include(if: $cond) { # can't be flattened due to conditional
82
- id # but this field is guaranteed to be fetched regardless
83
- }
84
- }
85
-
86
- # after: `id` processed at most once
87
- foo {
88
- bar {
89
- id
90
- }
91
- }
92
- ```
93
-
94
- - `GenerateRequisiteFieldTransform`: This optional, Relay-specific transform inserts `id` fields for globally identifiable objects and `__typename` fields wherever the type cannot be statically determined (e.g. for unions).
package/PATENTS DELETED
@@ -1,33 +0,0 @@
1
- Additional Grant of Patent Rights Version 2
2
-
3
- "Software" means the Relay software distributed by Facebook, Inc.
4
-
5
- Facebook, Inc. ("Facebook") hereby grants to each recipient of the Software
6
- ("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable
7
- (subject to the termination provision below) license under any Necessary
8
- Claims, to make, have made, use, sell, offer to sell, import, and otherwise
9
- transfer the Software. For avoidance of doubt, no license is granted under
10
- Facebook's rights in any patent claims that are infringed by (i) modifications
11
- to the Software made by you or any third party or (ii) the Software in
12
- combination with any software or other technology.
13
-
14
- The license granted hereunder will terminate, automatically and without notice,
15
- if you (or any of your subsidiaries, corporate affiliates or agents) initiate
16
- directly or indirectly, or take a direct financial interest in, any Patent
17
- Assertion: (i) against Facebook or any of its subsidiaries or corporate
18
- affiliates, (ii) against any party if such Patent Assertion arises in whole or
19
- in part from any software, technology, product or service of Facebook or any of
20
- its subsidiaries or corporate affiliates, or (iii) against any party relating
21
- to the Software. Notwithstanding the foregoing, if Facebook or any of its
22
- subsidiaries or corporate affiliates files a lawsuit alleging patent
23
- infringement against you in the first instance, and you respond by filing a
24
- patent infringement counterclaim in that lawsuit against that party that is
25
- unrelated to the Software, the license granted hereunder will not terminate
26
- under section (i) of this paragraph due to such counterclaim.
27
-
28
- A "Necessary Claim" is a claim of a patent owned by Facebook that is
29
- necessarily infringed by the Software standing alone.
30
-
31
- A "Patent Assertion" is any lawsuit or other action alleging direct, indirect,
32
- or contributory infringement or inducement to infringe any patent, including a
33
- cross-claim or counterclaim.
@@ -1,80 +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 AutoAliasTransform
10
- *
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _extends3 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
17
-
18
- var _toConsumableArray3 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray'));
19
-
20
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
21
-
22
- /**
23
- * A transform to generate a unique alias for every combination of field name
24
- * and static calls. This transform requires that fragment spreads with
25
- * arguments have been inlined.
26
- */
27
- function transform(context) {
28
- var documents = context.documents();
29
- return documents.reduce(function (ctx, node) {
30
- var selections = transformSelections(node.selections);
31
- return ctx.add((0, _extends3['default'])({}, node, {
32
- selections: selections
33
- }));
34
- }, new (require('./RelayCompilerContext'))(context.schema));
35
- }
36
-
37
- function transformSelections(nodeSelections) {
38
- return nodeSelections.map(function (selection) {
39
- if (selection.kind === 'LinkedField') {
40
- var alias = generateAlias(selection);
41
- var selections = transformSelections(selection.selections);
42
- return (0, _extends3['default'])({}, selection, {
43
- alias: alias,
44
- selections: selections
45
- });
46
- } else if (selection.kind === 'ScalarField') {
47
- var _alias = generateAlias(selection);
48
- return (0, _extends3['default'])({}, selection, {
49
- alias: _alias
50
- });
51
- } else if (selection.kind === 'InlineFragment' || selection.kind === 'Condition') {
52
- var _selections = transformSelections(selection.selections);
53
- return (0, _extends3['default'])({}, selection, {
54
- selections: _selections
55
- });
56
- } else if (selection.kind === 'FragmentSpread') {
57
- require('fbjs/lib/invariant')(!selection.args.length, 'AutoAliasTransform: Expected arguments to fragment spread ' + '`%s` to be inlined.', selection.name);
58
- return selection;
59
- } else {
60
- require('fbjs/lib/invariant')(false, 'AutoAliasTransform: Unexpected node kind `%s`.', selection.kind);
61
- }
62
- });
63
- }
64
-
65
- function generateAlias(field) {
66
- if (!field.args.length) {
67
- return null;
68
- }
69
- var args = [].concat((0, _toConsumableArray3['default'])(field.args)).sort(sortByName).map(function (arg) {
70
- return require('./getIdentifierForRelayArgumentValue')(arg.value);
71
- });
72
- var hash = require('./murmurHash')(require('./stableJSONStringifyOSS')(args));
73
- return (field.alias || field.name) + '_' + hash;
74
- }
75
-
76
- function sortByName(a, b) {
77
- return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
78
- }
79
-
80
- module.exports = { transform: transform };
@@ -1,27 +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 GraphQLFileParser
10
- *
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _require = require('graphql'),
17
- parse = _require.parse,
18
- Source = _require.Source;
19
-
20
- function parseFile(baseDir, file) {
21
- var text = require('fs').readFileSync(require('path').join(baseDir, file.relPath), 'utf8');
22
- return parse(new Source(text, file.relPath));
23
- }
24
-
25
- exports.getParser = function getParser(baseDir) {
26
- return new (require('./FileParser'))({ baseDir: baseDir, parse: parseFile });
27
- };
@@ -1,46 +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 GraphQLTextParser
10
- * TODO: enable flow
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, openTag, closeTag) {
22
- var text = require('fs').readFileSync(require('path').join(baseDir, file.relPath), 'utf8');
23
- var regex = new RegExp(openTag + '([\\s\\S]*?)' + closeTag, 'g');
24
- var graphqlText = void 0;
25
- var astDefinitions = [];
26
- while ((graphqlText = regex.exec(text)) !== null) {
27
- var ast = require('graphql').parse(new (require('graphql').Source)(graphqlText[1], file.relPath));
28
- require('fbjs/lib/invariant')(ast.definitions.length, 'GraphQLTextParser: Expected GraphQL text to contain at least one ' + 'definition (fragment, mutation, query, subscription), got `%s`.', graphqlText[1]);
29
- astDefinitions.push.apply(astDefinitions, (0, _toConsumableArray3['default'])(ast.definitions));
30
- }
31
- return {
32
- kind: 'Document',
33
- definitions: astDefinitions
34
- };
35
- }
36
-
37
- function getParser(baseDir) {
38
- return new (require('./FileParser'))({
39
- baseDir: baseDir,
40
- parse: parseFile
41
- });
42
- }
43
-
44
- module.exports = {
45
- getParser: getParser
46
- };
@@ -1,14 +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 RelayCodegenTypes
10
- *
11
- * @format
12
- */
13
-
14
- 'use strict';
@@ -1,13 +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 RelayCompiledTypes
10
- *
11
- * @format
12
- */
13
- 'use strict';
@@ -1,144 +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 RelayCompiler
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _classCallCheck3 = _interopRequireDefault(require('babel-runtime/helpers/classCallCheck'));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
19
-
20
- /**
21
- * A utility class for parsing a corpus of GraphQL documents, transforming them
22
- * with a standardized set of transforms, and generating runtime representations
23
- * of each definition.
24
- */
25
-
26
-
27
- // <CodegenNode> is a generic type here,
28
- // which represents the node type we get from the CodeGenerator's generation function.
29
- var RelayCompiler = function () {
30
-
31
- // The context passed in must already have any Relay-specific schema extensions
32
- function RelayCompiler(schema, context, transforms, codeGenerator) {
33
- (0, _classCallCheck3['default'])(this, RelayCompiler);
34
-
35
- this._context = context;
36
- // some transforms depend on this being the original schema,
37
- // not the transformed schema/context's schema
38
- this._schema = schema;
39
- this._transforms = transforms;
40
- this._codeGenerator = codeGenerator;
41
- }
42
-
43
- RelayCompiler.prototype.clone = function clone() {
44
- return new RelayCompiler(this._schema, this._context, this._transforms, this._codeGenerator);
45
- };
46
-
47
- RelayCompiler.prototype.context = function context() {
48
- return this._context;
49
- };
50
-
51
- RelayCompiler.prototype.addDefinitions = function addDefinitions(definitions) {
52
- this._context = this._context.addAll(definitions);
53
- return this._context.documents();
54
- };
55
-
56
- // Can only be called once per compiler. Once run, will use cached context
57
- // To re-run, clone the compiler.
58
-
59
-
60
- RelayCompiler.prototype.transformedQueryContext = function transformedQueryContext() {
61
- var _this = this;
62
-
63
- if (this._transformedQueryContext) {
64
- return this._transformedQueryContext;
65
- }
66
- this._transformedQueryContext = this._transforms.queryTransforms.reduce(function (ctx, transform) {
67
- return transform(ctx, _this._schema);
68
- }, this._context);
69
- return this._transformedQueryContext;
70
- };
71
-
72
- RelayCompiler.prototype.compile = function compile() {
73
- var _this2 = this;
74
-
75
- var transformContext = function transformContext(ctx, transform) {
76
- return transform(ctx, _this2._schema);
77
- };
78
- var fragmentContext = this._transforms.fragmentTransforms.reduce(transformContext, this._context);
79
- var queryContext = this.transformedQueryContext();
80
- var printContext = this._transforms.printTransforms.reduce(transformContext, queryContext);
81
- var codeGenContext = this._transforms.codegenTransforms.reduce(transformContext, queryContext);
82
-
83
- var compiledDocuments = new Map();
84
- fragmentContext.documents().forEach(function (node) {
85
- if (node.kind !== 'Fragment') {
86
- return;
87
- }
88
- var generatedFragment = _this2._codeGenerator(node);
89
- compiledDocuments.set(node.name, generatedFragment);
90
- });
91
- queryContext.documents().forEach(function (node) {
92
- if (node.kind !== 'Root') {
93
- return;
94
- }
95
- var name = node.name;
96
- // The unflattened query is used for printing, since flattening creates an
97
- // invalid query.
98
-
99
- var text = require('./filterContextForNode')(printContext.getRoot(name), printContext).documents().map(require('./RelayPrinter').print).join('\n');
100
- // The original query (with fragment spreads) is converted to a fragment
101
- // for reading out the root data.
102
- var sourceNode = fragmentContext.getRoot(name);
103
- var rootFragment = buildFragmentForRoot(sourceNode);
104
- var generatedFragment = _this2._codeGenerator(rootFragment);
105
- // The flattened query is used for codegen in order to reduce the number of
106
- // duplicate fields that must be processed during response normalization.
107
- var codeGenNode = codeGenContext.getRoot(name);
108
- var generatedQuery = _this2._codeGenerator(codeGenNode);
109
-
110
- var batchQuery = {
111
- fragment: generatedFragment,
112
- id: null,
113
- kind: 'Batch',
114
- metadata: node.metadata || {},
115
- name: name,
116
- query: generatedQuery,
117
- text: text
118
- };
119
- compiledDocuments.set(name, batchQuery);
120
- });
121
- return compiledDocuments;
122
- };
123
-
124
- return RelayCompiler;
125
- }();
126
-
127
- /**
128
- * Construct the fragment equivalent of a root node.
129
- */
130
-
131
-
132
- function buildFragmentForRoot(root) {
133
- return {
134
- argumentDefinitions: root.argumentDefinitions,
135
- directives: root.directives,
136
- kind: 'Fragment',
137
- metadata: null,
138
- name: root.name,
139
- selections: root.selections,
140
- type: root.type
141
- };
142
- }
143
-
144
- module.exports = RelayCompiler;
@@ -1,133 +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 RelayCompilerContext
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _classCallCheck3 = _interopRequireDefault(require('babel-runtime/helpers/classCallCheck'));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
19
-
20
- var _require = require('./RelayCompilerUserError'),
21
- createUserError = _require.createUserError;
22
-
23
- var ImmutableList = require('immutable').List,
24
- ImmutableOrderedMap = require('immutable').OrderedMap,
25
- Record = require('immutable').Record;
26
-
27
- var Document = Record({
28
- errors: null,
29
- name: null,
30
- node: null
31
- });
32
-
33
- /**
34
- * An immutable representation of a corpus of documents being compiled together.
35
- * For each document, the context stores the IR and any validation errors.
36
- */
37
-
38
- var RelayCompilerContext = function () {
39
- function RelayCompilerContext(schema) {
40
- (0, _classCallCheck3['default'])(this, RelayCompilerContext);
41
-
42
- this._documents = new ImmutableOrderedMap();
43
- this.schema = schema;
44
- }
45
-
46
- /**
47
- * Returns the documents for the context in the order they were added.
48
- */
49
-
50
-
51
- RelayCompilerContext.prototype.documents = function documents() {
52
- return this._documents.valueSeq().map(function (doc) {
53
- return doc.get('node');
54
- }).toJS();
55
- };
56
-
57
- RelayCompilerContext.prototype.updateSchema = function updateSchema(schema) {
58
- var context = new RelayCompilerContext(schema);
59
- context._documents = this._documents;
60
- return context;
61
- };
62
-
63
- RelayCompilerContext.prototype.add = function add(node) {
64
- require('fbjs/lib/invariant')(!this._documents.has(node.name), 'RelayCompilerContext: Duplicate document named `%s`. GraphQL ' + 'fragments and roots must have unique names.', node.name);
65
- return this._update(this._documents.set(node.name, new Document({
66
- name: node.name,
67
- node: node
68
- })));
69
- };
70
-
71
- RelayCompilerContext.prototype.addAll = function addAll(nodes) {
72
- return nodes.reduce(function (ctx, definition) {
73
- return ctx.add(definition);
74
- }, this);
75
- };
76
-
77
- RelayCompilerContext.prototype.addError = function addError(name, error) {
78
- var record = this._get(name);
79
- var errors = record.get('errors');
80
- if (errors) {
81
- errors = errors.push(error);
82
- } else {
83
- errors = ImmutableList([error]);
84
- }
85
- return this._update(this._documents.set(name, record.set('errors', errors)));
86
- };
87
-
88
- RelayCompilerContext.prototype.get = function get(name) {
89
- var record = this._documents.get(name);
90
- return record && record.get('node');
91
- };
92
-
93
- RelayCompilerContext.prototype.getFragment = function getFragment(name) {
94
- var record = this._documents.get(name);
95
- var node = record && record.get('node');
96
- if (!(node && node.kind === 'Fragment')) {
97
- var childModule = name.substring(0, name.lastIndexOf('_'));
98
- throw createUserError('Relay cannot find fragment `%s`.' + ' Please make sure the fragment exists in `%s`', name, childModule);
99
- }
100
- return node;
101
- };
102
-
103
- RelayCompilerContext.prototype.getRoot = function getRoot(name) {
104
- var record = this._documents.get(name);
105
- var node = record && record.get('node');
106
- require('fbjs/lib/invariant')(node && node.kind === 'Root', 'RelayCompilerContext: Expected `%s` to be a root, got `%s`.', name, node && node.kind);
107
- return node;
108
- };
109
-
110
- RelayCompilerContext.prototype.getErrors = function getErrors(name) {
111
- return this._get(name).get('errors');
112
- };
113
-
114
- RelayCompilerContext.prototype.remove = function remove(name) {
115
- return this._update(this._documents['delete'](name));
116
- };
117
-
118
- RelayCompilerContext.prototype._get = function _get(name) {
119
- var record = this._documents.get(name);
120
- require('fbjs/lib/invariant')(record, 'RelayCompilerContext: Unknown document `%s`.', name);
121
- return record;
122
- };
123
-
124
- RelayCompilerContext.prototype._update = function _update(documents) {
125
- var context = new RelayCompilerContext(this.schema);
126
- context._documents = documents;
127
- return context;
128
- };
129
-
130
- return RelayCompilerContext;
131
- }();
132
-
133
- module.exports = RelayCompilerContext;
@@ -1,30 +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 RelayCompilerUserError
10
- *
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var createUserError = function createUserError(format) {
17
- for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
18
- args[_key - 1] = arguments[_key];
19
- }
20
-
21
- var index = 0;
22
- var formatted = format.replace(/%s/g, function (match) {
23
- return args[index++];
24
- });
25
- var err = new Error(formatted);
26
- err.isRelayUserError = true;
27
- return err;
28
- };
29
-
30
- module.exports = { createUserError: createUserError };
@@ -1,40 +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 RelayConsoleReporter
10
- *
11
- * @format
12
- */
13
-
14
- 'use strict';
15
-
16
- var _classCallCheck3 = _interopRequireDefault(require('babel-runtime/helpers/classCallCheck'));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
19
-
20
- var RelayConsoleReporter = function () {
21
- function RelayConsoleReporter(options) {
22
- (0, _classCallCheck3['default'])(this, RelayConsoleReporter);
23
-
24
- this._verbose = options.verbose;
25
- }
26
-
27
- RelayConsoleReporter.prototype.reportError = function reportError(caughtLocation, error) {
28
- process.stdout.write(require('chalk').red('ERROR:\n' + error.message + '\n'));
29
- if (this._verbose) {
30
- var frames = error.stack.match(/^ {4}at .*$/gm);
31
- if (frames) {
32
- process.stdout.write(require('chalk').gray('From: ' + caughtLocation + '\n' + frames.join('\n') + '\n'));
33
- }
34
- }
35
- };
36
-
37
- return RelayConsoleReporter;
38
- }();
39
-
40
- module.exports = RelayConsoleReporter;