UNPKG

20.5 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 return new (P || (P = Promise))(function (resolve, reject) {
15 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
18 step((generator = generator.apply(thisArg, _arguments || [])).next());
19 });
20};
21var __generator = (this && this.__generator) || function (thisArg, body) {
22 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
23 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24 function verb(n) { return function (v) { return step([n, v]); }; }
25 function step(op) {
26 if (f) throw new TypeError("Generator is already executing.");
27 while (_) try {
28 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
29 if (y = 0, t) op = [op[0] & 2, t.value];
30 switch (op[0]) {
31 case 0: case 1: t = op; break;
32 case 4: _.label++; return { value: op[1], done: false };
33 case 5: _.label++; y = op[1]; op = [0]; continue;
34 case 7: op = _.ops.pop(); _.trys.pop(); continue;
35 default:
36 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40 if (t[2]) _.ops.pop();
41 _.trys.pop(); continue;
42 }
43 op = body.call(thisArg, _);
44 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46 }
47};
48Object.defineProperty(exports, "__esModule", { value: true });
49var graphql_codegen_core_1 = require("graphql-codegen-core");
50var Listr = require("listr");
51var helpers_1 = require("./helpers");
52var prettier_1 = require("./utils/prettier");
53var listr_renderer_1 = require("./utils/listr-renderer");
54var errors_1 = require("./errors");
55var load_1 = require("./load");
56var merge_schemas_1 = require("./merge-schemas");
57var graphql_1 = require("graphql");
58var execute_plugin_1 = require("./execute-plugin");
59function executeCodegen(config) {
60 return __awaiter(this, void 0, void 0, function () {
61 function wrapTask(task, source) {
62 var _this = this;
63 return function () { return __awaiter(_this, void 0, void 0, function () {
64 var error_1;
65 return __generator(this, function (_a) {
66 switch (_a.label) {
67 case 0:
68 _a.trys.push([0, 2, , 3]);
69 return [4 /*yield*/, task()];
70 case 1:
71 _a.sent();
72 return [3 /*break*/, 3];
73 case 2:
74 error_1 = _a.sent();
75 if (source && !(error_1 instanceof graphql_1.GraphQLError)) {
76 error_1.source = source;
77 }
78 throw error_1;
79 case 3: return [2 /*return*/];
80 }
81 });
82 }); };
83 }
84 function normalize() {
85 /* Load Require extensions */
86 var requireExtensions = helpers_1.normalizeInstanceOrArray(config.require);
87 requireExtensions.forEach(function (mod) { return require(mod); });
88 /* Root templates-config */
89 rootConfig = config.config || {};
90 /* Normalize root "schema" field */
91 rootSchemas = helpers_1.normalizeInstanceOrArray(config.schema);
92 /* Normalize root "documents" field */
93 rootDocuments = helpers_1.normalizeInstanceOrArray(config.documents);
94 /* Normalize "generators" field */
95 var generateKeys = Object.keys(config.generates);
96 if (generateKeys.length === 0) {
97 throw new errors_1.DetailedError('Invalid Codegen Configuration!', "\n Please make sure that your codegen config file contains the \"generates\" field, with a specification for the plugins you need.\n \n It should looks like that:\n\n schema:\n - my-schema.graphql\n generates:\n my-file.ts:\n - plugin1\n - plugin2\n - plugin3\n ");
98 }
99 for (var _i = 0, generateKeys_1 = generateKeys; _i < generateKeys_1.length; _i++) {
100 var filename = generateKeys_1[_i];
101 generates[filename] = helpers_1.normalizeOutputParam(config.generates[filename]);
102 if (generates[filename].plugins.length === 0) {
103 throw new errors_1.DetailedError('Invalid Codegen Configuration!', "\n Please make sure that your codegen config file has defined plugins list for output \"" + filename + "\".\n \n It should looks like that:\n \n schema:\n - my-schema.graphql\n generates:\n my-file.ts:\n - plugin1\n - plugin2\n - plugin3\n ");
104 }
105 }
106 if (rootSchemas.length === 0 && Object.keys(generates).some(function (filename) { return generates[filename].schema.length === 0; })) {
107 throw new errors_1.DetailedError('Invalid Codegen Configuration!', "\n Please make sure that your codegen config file contains either the \"schema\" field \n or every generated file has its own \"schema\" field.\n \n It should looks like that:\n schema:\n - my-schema.graphql\n\n or:\n generates:\n path/to/output:\n schema: my-schema.graphql\n ");
108 }
109 }
110 var result, commonListrOptions, listr, rootConfig, rootSchemas, rootDocuments, generates;
111 var _this = this;
112 return __generator(this, function (_a) {
113 switch (_a.label) {
114 case 0:
115 result = [];
116 commonListrOptions = {
117 exitOnError: true
118 };
119 if (process.env.VERBOSE) {
120 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'verbose', nonTTYRenderer: 'verbose' }));
121 }
122 else if (process.env.NODE_ENV === 'test') {
123 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'silent', nonTTYRenderer: 'silent' }));
124 }
125 else {
126 listr = new Listr(__assign({}, commonListrOptions, { renderer: config.silent ? 'silent' : listr_renderer_1.Renderer, nonTTYRenderer: config.silent ? 'silent' : 'default', collapse: true, clearOutput: false }));
127 }
128 rootConfig = {};
129 generates = {};
130 listr.add({
131 title: 'Parse configuration',
132 task: function () { return normalize(); }
133 });
134 listr.add({
135 title: 'Generate outputs',
136 task: function () {
137 return new Listr(Object.keys(generates).map(function (filename, i) { return ({
138 title: "Generate " + filename,
139 task: function () {
140 var outputConfig = generates[filename];
141 var outputFileTemplateConfig = outputConfig.config || {};
142 var outputDocuments = [];
143 var outputSchema;
144 var outputSpecificSchemas = helpers_1.normalizeInstanceOrArray(outputConfig.schema);
145 var outputSpecificDocuments = helpers_1.normalizeInstanceOrArray(outputConfig.documents);
146 return new Listr([
147 {
148 title: 'Load GraphQL schemas',
149 task: wrapTask(function () { return __awaiter(_this, void 0, void 0, function () {
150 var allSchemas, _a;
151 return __generator(this, function (_b) {
152 switch (_b.label) {
153 case 0:
154 graphql_codegen_core_1.debugLog("[CLI] Loading Schemas");
155 allSchemas = rootSchemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }).concat(outputSpecificSchemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }));
156 if (!(allSchemas.length > 0)) return [3 /*break*/, 3];
157 _a = merge_schemas_1.mergeSchemas;
158 return [4 /*yield*/, Promise.all(allSchemas)];
159 case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])];
160 case 2:
161 outputSchema = _b.sent();
162 _b.label = 3;
163 case 3: return [2 /*return*/];
164 }
165 });
166 }); }, filename)
167 },
168 {
169 title: 'Load GraphQL documents',
170 task: wrapTask(function () { return __awaiter(_this, void 0, void 0, function () {
171 var allDocuments, _i, allDocuments_1, docDef, documents;
172 return __generator(this, function (_a) {
173 switch (_a.label) {
174 case 0:
175 graphql_codegen_core_1.debugLog("[CLI] Loading Documents");
176 allDocuments = rootDocuments.concat(outputSpecificDocuments);
177 _i = 0, allDocuments_1 = allDocuments;
178 _a.label = 1;
179 case 1:
180 if (!(_i < allDocuments_1.length)) return [3 /*break*/, 4];
181 docDef = allDocuments_1[_i];
182 return [4 /*yield*/, load_1.loadDocuments(docDef, config)];
183 case 2:
184 documents = _a.sent();
185 if (documents.length > 0) {
186 outputDocuments.push.apply(outputDocuments, documents);
187 }
188 _a.label = 3;
189 case 3:
190 _i++;
191 return [3 /*break*/, 1];
192 case 4: return [2 /*return*/];
193 }
194 });
195 }); }, filename)
196 },
197 {
198 title: 'Generate',
199 task: wrapTask(function () { return __awaiter(_this, void 0, void 0, function () {
200 var normalizedPluginsArray, output;
201 return __generator(this, function (_a) {
202 switch (_a.label) {
203 case 0:
204 graphql_codegen_core_1.debugLog("[CLI] Generating output");
205 normalizedPluginsArray = helpers_1.normalizeConfig(outputConfig.plugins);
206 return [4 /*yield*/, generateOutput({
207 filename: filename,
208 plugins: normalizedPluginsArray,
209 schema: outputSchema,
210 documents: outputDocuments,
211 inheritedConfig: __assign({}, rootConfig, outputFileTemplateConfig),
212 pluginLoader: config.pluginLoader || require
213 })];
214 case 1:
215 output = _a.sent();
216 result.push(output);
217 return [2 /*return*/];
218 }
219 });
220 }); }, filename)
221 }
222 ], {
223 // it stops when one of tasks failed
224 exitOnError: true
225 });
226 }
227 }); }), {
228 // it doesn't stop when one of tasks failed, to finish at least some of outputs
229 exitOnError: false,
230 // run 4 at once
231 concurrent: 4
232 });
233 }
234 });
235 return [4 /*yield*/, listr.run()];
236 case 1:
237 _a.sent();
238 return [2 /*return*/, result];
239 }
240 });
241 });
242}
243exports.executeCodegen = executeCodegen;
244function validateDocuments(schema, files) {
245 // duplicated names
246 var operationMap = {};
247 files.forEach(function (file) {
248 graphql_1.visit(file.content, {
249 OperationDefinition: function (node) {
250 if (typeof node.name !== 'undefined') {
251 if (!operationMap[node.name.value]) {
252 operationMap[node.name.value] = [];
253 }
254 operationMap[node.name.value].push(file.filePath);
255 }
256 }
257 });
258 });
259 var names = Object.keys(operationMap);
260 if (names.length) {
261 var duplicated = names.filter(function (name) { return operationMap[name].length > 1; });
262 if (!duplicated.length) {
263 return;
264 }
265 var list = duplicated
266 .map(function (name) {
267 return ("\n * " + name + " found in:\n " + operationMap[name]
268 .map(function (filepath) {
269 return ("\n - " + filepath + "\n ").trimRight();
270 })
271 .join('') + "\n ").trimRight();
272 })
273 .join('');
274 throw new errors_1.DetailedError("Not all operations have an unique name: " + duplicated.join(', '), "\n Not all operations have an unique name\n\n " + list + "\n ");
275 }
276}
277function generateOutput(options) {
278 return __awaiter(this, void 0, void 0, function () {
279 var output, pluginsPackages, schema, i, plugin, pluginPackage, name_1, pluginConfig, result, _a;
280 return __generator(this, function (_b) {
281 switch (_b.label) {
282 case 0:
283 output = '';
284 validateDocuments(options.schema, options.documents);
285 return [4 /*yield*/, Promise.all(options.plugins.map(function (plugin) { return execute_plugin_1.getPluginByName(Object.keys(plugin)[0], options.pluginLoader); }))];
286 case 1:
287 pluginsPackages = _b.sent();
288 schema = pluginsPackages.reduce(function (schema, plugin) {
289 return !plugin.addToSchema ? schema : merge_schemas_1.mergeSchemas([schema, plugin.addToSchema]);
290 }, options.schema);
291 i = 0;
292 _b.label = 2;
293 case 2:
294 if (!(i < options.plugins.length)) return [3 /*break*/, 5];
295 plugin = options.plugins[i];
296 pluginPackage = pluginsPackages[i];
297 name_1 = Object.keys(plugin)[0];
298 pluginConfig = plugin[name_1];
299 graphql_codegen_core_1.debugLog("[CLI] Running plugin: " + name_1);
300 return [4 /*yield*/, execute_plugin_1.executePlugin({
301 name: name_1,
302 config: typeof pluginConfig !== 'object'
303 ? pluginConfig
304 : __assign({}, options.inheritedConfig, pluginConfig),
305 schema: schema,
306 documents: options.documents,
307 outputFilename: options.filename,
308 allPlugins: options.plugins
309 }, pluginPackage)];
310 case 3:
311 result = _b.sent();
312 graphql_codegen_core_1.debugLog("[CLI] Completed executing plugin: " + name_1);
313 output += result;
314 _b.label = 4;
315 case 4:
316 i++;
317 return [3 /*break*/, 2];
318 case 5:
319 _a = { filename: options.filename };
320 return [4 /*yield*/, prettier_1.prettify(options.filename, output)];
321 case 6: return [2 /*return*/, (_a.content = _b.sent(), _a)];
322 }
323 });
324 });
325}
326exports.generateOutput = generateOutput;
327//# sourceMappingURL=codegen.js.map
\No newline at end of file