UNPKG

8.79 kBJavaScriptView Raw
1// @generated
2/**
3 * Copyright (c) 2013-present, Facebook, Inc.
4 * All rights reserved.
5 *
6 * This source code is licensed under the BSD-style license found in the
7 * LICENSE file in the root directory of this source tree. An additional grant
8 * of patent rights can be found in the PATENTS file in the same directory.
9 *
10 *
11 * @fullSyntaxTransform
12 */
13
14'use strict';
15
16Object.defineProperty(exports, '__esModule', {
17 value: true
18});
19
20var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21
22function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
23
24var GraphQL = require('./GraphQL');
25var formatError = GraphQL.error.formatError;
26var parser = GraphQL.language_parser;
27var Source = GraphQL.language_source.Source;
28var validate = GraphQL.validation.validate;
29
30var _require = require('./RelayQLAST');
31
32var RelayQLDefinition = _require.RelayQLDefinition;
33var RelayQLFragment = _require.RelayQLFragment;
34var RelayQLMutation = _require.RelayQLMutation;
35var RelayQLQuery = _require.RelayQLQuery;
36var RelayQLSubscription = _require.RelayQLSubscription;
37
38var RelayQLPrinter = require('./RelayQLPrinter');
39
40var invariant = require('./invariant');
41var util = require('util');
42
43/**
44 * Transforms a TemplateLiteral node into a RelayQLDefinition, which is then
45 * transformed into a Babel AST via RelayQLPrinter.
46 */
47
48var RelayQLTransformer = (function () {
49 function RelayQLTransformer(schema, options) {
50 _classCallCheck(this, RelayQLTransformer);
51
52 this.schema = schema;
53 this.options = options;
54 }
55
56 _createClass(RelayQLTransformer, [{
57 key: 'transform',
58 value: function transform(t, // Babel
59 node, options) {
60 var _processTemplateLiteral = this.processTemplateLiteral(node, options.documentName);
61
62 var substitutions = _processTemplateLiteral.substitutions;
63 var templateText = _processTemplateLiteral.templateText;
64 var variableNames = _processTemplateLiteral.variableNames;
65
66 var documentText = this.processTemplateText(templateText, options);
67 var definition = this.processDocumentText(documentText, options);
68
69 var Printer = RelayQLPrinter(t, this.options);
70 return new Printer(options.tagName, variableNames).print(definition, substitutions);
71 }
72
73 /**
74 * Convert TemplateLiteral into a single template string with substitution
75 * names, a matching array of substituted values, and a set of substituted
76 * variable names.
77 */
78 }, {
79 key: 'processTemplateLiteral',
80 value: function processTemplateLiteral(node, documentName) {
81 var _this = this;
82
83 var chunks = [];
84 var variableNames = {};
85 var substitutions = [];
86 node.quasis.forEach(function (element, ii) {
87 var chunk = element.value.cooked;
88 chunks.push(chunk);
89 if (!element.tail) {
90 var _name = 'RQL_' + ii;
91 var _value = node.expressions[ii];
92 substitutions.push({ name: _name, value: _value });
93 if (/:\s*$/.test(chunk)) {
94 invariant(_this.options.substituteVariables, 'You supplied a GraphQL document named `%s` that uses template ' + 'substitution for an argument value, but variable substitution ' + 'has not been enabled.', documentName);
95 chunks.push('$' + _name);
96 variableNames[_name] = undefined;
97 } else {
98 chunks.push('...' + _name);
99 }
100 }
101 });
102 return { substitutions: substitutions, templateText: chunks.join('').trim(), variableNames: variableNames };
103 }
104
105 /**
106 * Converts the template string into a valid GraphQL document string.
107 */
108 }, {
109 key: 'processTemplateText',
110 value: function processTemplateText(templateText, _ref) {
111 var documentName = _ref.documentName;
112 var propName = _ref.propName;
113
114 var pattern = /^(fragment|mutation|query|subscription)\s*(\w*)?([\s\S]*)/;
115 var matches = pattern.exec(templateText);
116 invariant(matches, 'You supplied a GraphQL document named `%s` with invalid syntax. It ' + 'must start with `fragment`, `mutation`, `query`, or `subscription`.', documentName);
117 var type = matches[1];
118 var name = matches[2] || documentName;
119 var rest = matches[3];
120 // Allow `fragment on Type {...}`.
121 if (type === 'fragment' && name === 'on') {
122 name = documentName + (propName ? '_' + capitalize(propName) : '') + 'RelayQL';
123 rest = 'on' + rest;
124 }
125 var definitionName = capitalize(name);
126 return type + ' ' + definitionName + ' ' + rest;
127 }
128
129 /**
130 * Parses the GraphQL document string into a RelayQLDocument.
131 */
132 }, {
133 key: 'processDocumentText',
134 value: function processDocumentText(documentText, _ref2) {
135 var documentName = _ref2.documentName;
136 var fragmentLocationID = _ref2.fragmentLocationID;
137
138 var document = parser.parse(new Source(documentText, documentName));
139 var validationErrors = this.validateDocument(document);
140 if (validationErrors) {
141 var error = new Error(util.format('You supplied a GraphQL document named `%s` with validation errors.', documentName));
142 error.validationErrors = validationErrors;
143 error.sourceText = documentText;
144 throw error;
145 }
146 var definition = document.definitions[0];
147
148 var context = {
149 definitionName: capitalize(documentName),
150 isPattern: false,
151 nodeIndex: 0,
152 schema: this.schema,
153 fragmentLocationID: fragmentLocationID
154 };
155 if (definition.kind === 'FragmentDefinition') {
156 return new RelayQLFragment(context, definition);
157 } else if (definition.kind === 'OperationDefinition') {
158 if (definition.operation === 'mutation') {
159 return new RelayQLMutation(context, definition);
160 } else if (definition.operation === 'query') {
161 return new RelayQLQuery(context, definition);
162 } else if (definition.operation === 'subscription') {
163 return new RelayQLSubscription(context, definition);
164 } else {
165 invariant(false, 'Unsupported operation: %s', definition.operation);
166 }
167 } else {
168 invariant(false, 'Unsupported definition kind: %s', definition.kind);
169 }
170 }
171 }, {
172 key: 'validateDocument',
173 value: function validateDocument(document) {
174 invariant(document.definitions.length === 1, 'You supplied a GraphQL document named `%s` with %d definitions, but ' + 'it must have exactly one definition.', document.definitions.length);
175 var definition = document.definitions[0];
176 var isMutation = definition.kind === 'OperationDefinition' && definition.operation === 'mutation';
177
178 var validator = this.options.validator;
179 var validationErrors = undefined;
180 if (validator) {
181 var _validator = validator(GraphQL);
182
183 var _validate = _validator.validate;
184
185 validationErrors = _validate(this.schema, document);
186 } else {
187 var rules = [require('graphql/validation/rules/ArgumentsOfCorrectType').ArgumentsOfCorrectType, require('graphql/validation/rules/DefaultValuesOfCorrectType').DefaultValuesOfCorrectType, require('graphql/validation/rules/FieldsOnCorrectType').FieldsOnCorrectType, require('graphql/validation/rules/FragmentsOnCompositeTypes').FragmentsOnCompositeTypes, require('graphql/validation/rules/KnownArgumentNames').KnownArgumentNames, require('graphql/validation/rules/KnownTypeNames').KnownTypeNames, require('graphql/validation/rules/PossibleFragmentSpreads').PossibleFragmentSpreads, require('graphql/validation/rules/PossibleFragmentSpreads').PossibleFragmentSpreads, require('graphql/validation/rules/VariablesInAllowedPosition').VariablesInAllowedPosition];
188 if (!isMutation) {
189 rules.push(require('graphql/validation/rules/ProvidedNonNullArguments').ProvidedNonNullArguments);
190 }
191 validationErrors = validate(this.schema, document, rules);
192 }
193
194 if (validationErrors && validationErrors.length > 0) {
195 return validationErrors.map(formatError);
196 }
197 return null;
198 }
199 }]);
200
201 return RelayQLTransformer;
202})();
203
204function capitalize(string) {
205 return string[0].toUpperCase() + string.slice(1);
206}
207
208module.exports = RelayQLTransformer;
\No newline at end of file