UNPKG

26.2 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_tools_1 = require("graphql-tools");
50var Listr = require("listr");
51var helpers_1 = require("./helpers");
52var validate_documents_1 = require("./loaders/documents/validate-documents");
53var prettier_1 = require("./utils/prettier");
54var listr_renderer_1 = require("./utils/listr-renderer");
55var errors_1 = require("./errors");
56var load_1 = require("./load");
57var merge_schemas_1 = require("./merge-schemas");
58function executeCodegen(config) {
59 return __awaiter(this, void 0, void 0, function () {
60 function wrapTask(task, source) {
61 var _this = this;
62 return function () { return __awaiter(_this, void 0, void 0, function () {
63 var error_1;
64 return __generator(this, function (_a) {
65 switch (_a.label) {
66 case 0:
67 _a.trys.push([0, 2, , 3]);
68 return [4 /*yield*/, task()];
69 case 1:
70 _a.sent();
71 return [3 /*break*/, 3];
72 case 2:
73 error_1 = _a.sent();
74 if (source) {
75 error_1.source = source;
76 }
77 throw error_1;
78 case 3: return [2 /*return*/];
79 }
80 });
81 }); };
82 }
83 function normalize() {
84 /* Load Require extensions */
85 var requireExtensions = helpers_1.normalizeInstanceOrArray(config.require);
86 requireExtensions.forEach(function (mod) { return require(mod); });
87 /* Root templates-config */
88 rootConfig = config.config || {};
89 /* Normalize root "schema" field */
90 schemas = helpers_1.normalizeInstanceOrArray(config.schema);
91 /* Normalize root "documents" field */
92 documents = helpers_1.normalizeInstanceOrArray(config.documents);
93 /* Normalize "generators" field */
94 var generateKeys = Object.keys(config.generates);
95 if (generateKeys.length === 0) {
96 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 ");
97 }
98 for (var _i = 0, generateKeys_1 = generateKeys; _i < generateKeys_1.length; _i++) {
99 var filename = generateKeys_1[_i];
100 generates[filename] = helpers_1.normalizeOutputParam(config.generates[filename]);
101 if (generates[filename].plugins.length === 0) {
102 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 ");
103 }
104 }
105 if (schemas.length === 0 && Object.keys(generates).some(function (filename) { return generates[filename].schema.length === 0; })) {
106 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 ");
107 }
108 }
109 function loadRootSchema() {
110 return __awaiter(this, void 0, void 0, function () {
111 var _a;
112 return __generator(this, function (_b) {
113 switch (_b.label) {
114 case 0:
115 if (!schemas.length) return [3 /*break*/, 3];
116 _a = merge_schemas_1.mergeSchemas;
117 return [4 /*yield*/, Promise.all(schemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }))];
118 case 1: return [4 /*yield*/, _a.apply(void 0, [_b.sent()])];
119 case 2:
120 rootSchema = _b.sent();
121 _b.label = 3;
122 case 3: return [2 /*return*/];
123 }
124 });
125 });
126 }
127 function loadRootDocuments() {
128 return __awaiter(this, void 0, void 0, function () {
129 var _i, documents_1, docDef, documents_2, errors;
130 return __generator(this, function (_a) {
131 switch (_a.label) {
132 case 0:
133 if (!(documents.length > 0)) return [3 /*break*/, 5];
134 _i = 0, documents_1 = documents;
135 _a.label = 1;
136 case 1:
137 if (!(_i < documents_1.length)) return [3 /*break*/, 4];
138 docDef = documents_1[_i];
139 return [4 /*yield*/, load_1.loadDocuments(docDef, config)];
140 case 2:
141 documents_2 = _a.sent();
142 if (documents_2.length > 0) {
143 rootDocuments.push.apply(rootDocuments, documents_2);
144 }
145 _a.label = 3;
146 case 3:
147 _i++;
148 return [3 /*break*/, 1];
149 case 4:
150 if (rootSchema) {
151 errors = validate_documents_1.validateGraphQlDocuments(rootSchema, rootDocuments);
152 validate_documents_1.checkValidationErrors(errors);
153 }
154 _a.label = 5;
155 case 5: return [2 /*return*/];
156 }
157 });
158 });
159 }
160 var result, commonListrOptions, listr, rootConfig, schemas, documents, generates, rootSchema, rootDocuments;
161 return __generator(this, function (_a) {
162 switch (_a.label) {
163 case 0:
164 result = [];
165 commonListrOptions = {
166 exitOnError: true
167 };
168 if (process.env.VERBOSE) {
169 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'verbose', nonTTYRenderer: 'verbose' }));
170 }
171 else if (process.env.NODE_ENV === 'test') {
172 listr = new Listr(__assign({}, commonListrOptions, { renderer: 'silent', nonTTYRenderer: 'silent' }));
173 }
174 else {
175 listr = new Listr(__assign({}, commonListrOptions, { renderer: config.silent ? 'silent' : listr_renderer_1.Renderer, nonTTYRenderer: config.silent ? 'silent' : 'default', collapse: true, clearOutput: false }));
176 }
177 rootConfig = {};
178 generates = {};
179 rootDocuments = [];
180 listr.add({
181 title: 'Parse configuration',
182 task: function (ctx) {
183 normalize();
184 ctx.hasSchemas = schemas.length > 0;
185 ctx.hasDocuments = documents.length > 0;
186 }
187 });
188 listr.add({
189 title: 'Load schema',
190 enabled: function (ctx) { return ctx.hasSchemas; },
191 task: wrapTask(loadRootSchema)
192 });
193 listr.add({
194 title: 'Load documents',
195 enabled: function (ctx) { return ctx.hasDocuments; },
196 task: wrapTask(loadRootDocuments)
197 });
198 listr.add({
199 title: 'Generate outputs',
200 task: function () {
201 return new Listr(Object.keys(generates).map(function (filename, i) { return ({
202 title: "Generate " + filename,
203 task: function () {
204 var outputConfig = generates[filename];
205 var outputFileTemplateConfig = outputConfig.config || {};
206 var outputSchema = rootSchema;
207 var outputDocuments = rootDocuments;
208 var outputSpecificSchemas = helpers_1.normalizeInstanceOrArray(outputConfig.schema);
209 var outputSpecificDocuments = helpers_1.normalizeInstanceOrArray(outputConfig.documents);
210 function addSchema() {
211 return __awaiter(this, void 0, void 0, function () {
212 var _a, _b, _c;
213 return __generator(this, function (_d) {
214 switch (_d.label) {
215 case 0:
216 _a = merge_schemas_1.mergeSchemas;
217 _c = (_b = [
218 rootSchema
219 ]).concat;
220 return [4 /*yield*/, Promise.all(outputSpecificSchemas.map(function (pointToScehma) { return load_1.loadSchema(pointToScehma, config); }))];
221 case 1: return [4 /*yield*/, _a.apply(void 0, [_c.apply(_b, [(_d.sent())])])];
222 case 2:
223 outputSchema = _d.sent();
224 return [2 /*return*/];
225 }
226 });
227 });
228 }
229 function addDocuments() {
230 return __awaiter(this, void 0, void 0, function () {
231 var additionalDocs, _i, outputSpecificDocuments_1, docDef, documents_3, errors;
232 return __generator(this, function (_a) {
233 switch (_a.label) {
234 case 0:
235 additionalDocs = [];
236 _i = 0, outputSpecificDocuments_1 = outputSpecificDocuments;
237 _a.label = 1;
238 case 1:
239 if (!(_i < outputSpecificDocuments_1.length)) return [3 /*break*/, 4];
240 docDef = outputSpecificDocuments_1[_i];
241 return [4 /*yield*/, load_1.loadDocuments(docDef, config)];
242 case 2:
243 documents_3 = _a.sent();
244 if (documents_3.length > 0) {
245 additionalDocs.push.apply(additionalDocs, documents_3);
246 }
247 _a.label = 3;
248 case 3:
249 _i++;
250 return [3 /*break*/, 1];
251 case 4:
252 if (outputSchema) {
253 errors = validate_documents_1.validateGraphQlDocuments(outputSchema, additionalDocs);
254 validate_documents_1.checkValidationErrors(errors);
255 }
256 outputDocuments = rootDocuments.concat(additionalDocs);
257 return [2 /*return*/];
258 }
259 });
260 });
261 }
262 function doGenerateOutput() {
263 return __awaiter(this, void 0, void 0, function () {
264 var normalizedPluginsArray, output;
265 return __generator(this, function (_a) {
266 switch (_a.label) {
267 case 0:
268 normalizedPluginsArray = helpers_1.normalizeConfig(outputConfig.plugins);
269 return [4 /*yield*/, generateOutput({
270 filename: filename,
271 plugins: normalizedPluginsArray,
272 schema: outputSchema,
273 documents: outputDocuments,
274 inheritedConfig: __assign({}, rootConfig, outputFileTemplateConfig)
275 })];
276 case 1:
277 output = _a.sent();
278 result.push(output);
279 return [2 /*return*/];
280 }
281 });
282 });
283 }
284 return new Listr([
285 {
286 title: 'Add related schemas',
287 enabled: function () { return outputSpecificSchemas.length > 0; },
288 task: wrapTask(addSchema, filename)
289 },
290 {
291 title: 'Add related documents',
292 enabled: function () { return outputSpecificDocuments.length > 0; },
293 task: wrapTask(addDocuments, filename)
294 },
295 {
296 title: 'Generate',
297 task: wrapTask(doGenerateOutput, filename)
298 }
299 ], {
300 // it stops when one of tasks failed
301 exitOnError: true
302 });
303 }
304 }); }), {
305 // it doesn't stop when one of tasks failed, to finish at least some of outputs
306 exitOnError: false,
307 // run 4 at once
308 concurrent: 4
309 });
310 }
311 });
312 return [4 /*yield*/, listr.run()];
313 case 1:
314 _a.sent();
315 return [2 /*return*/, result];
316 }
317 });
318 });
319}
320exports.executeCodegen = executeCodegen;
321function generateOutput(options) {
322 return __awaiter(this, void 0, void 0, function () {
323 var output, _i, _a, plugin, name_1, pluginConfig, result, _b;
324 return __generator(this, function (_c) {
325 switch (_c.label) {
326 case 0:
327 output = '';
328 _i = 0, _a = options.plugins;
329 _c.label = 1;
330 case 1:
331 if (!(_i < _a.length)) return [3 /*break*/, 4];
332 plugin = _a[_i];
333 name_1 = Object.keys(plugin)[0];
334 pluginConfig = plugin[name_1];
335 return [4 /*yield*/, executePlugin({
336 name: name_1,
337 config: typeof pluginConfig !== 'object'
338 ? pluginConfig
339 : __assign({}, options.inheritedConfig, pluginConfig),
340 schema: options.schema,
341 documents: options.documents,
342 outputFilename: options.filename,
343 allPlugins: options.plugins
344 })];
345 case 2:
346 result = _c.sent();
347 output += result;
348 _c.label = 3;
349 case 3:
350 _i++;
351 return [3 /*break*/, 1];
352 case 4:
353 _b = { filename: options.filename };
354 return [4 /*yield*/, prettier_1.prettify(options.filename, output)];
355 case 5: return [2 /*return*/, (_b.content = _c.sent(), _b)];
356 }
357 });
358 });
359}
360exports.generateOutput = generateOutput;
361function getPluginByName(name) {
362 return __awaiter(this, void 0, void 0, function () {
363 var possibleNames, _i, possibleNames_1, packageName, possibleNamesMsg;
364 return __generator(this, function (_a) {
365 possibleNames = [
366 "graphql-codegen-" + name,
367 "graphql-codegen-" + name + "-template",
368 "codegen-" + name,
369 "codegen-" + name + "-template",
370 name
371 ];
372 for (_i = 0, possibleNames_1 = possibleNames; _i < possibleNames_1.length; _i++) {
373 packageName = possibleNames_1[_i];
374 try {
375 return [2 /*return*/, require(packageName)];
376 }
377 catch (err) {
378 if (err.message.indexOf("Cannot find module '" + packageName + "'") === -1) {
379 throw new errors_1.DetailedError("Unable to load template plugin matching " + name, "\n Unable to load template plugin matching '" + name + "'.\n Reason: \n " + err.message + "\n ");
380 }
381 }
382 }
383 possibleNamesMsg = possibleNames
384 .map(function (name) {
385 return ("\n - " + name + "\n ").trimRight();
386 })
387 .join('');
388 throw new errors_1.DetailedError("Unable to find template plugin matching " + name, "\n Unable to find template plugin matching '" + name + "'\n Install one of the following packages:\n \n " + possibleNamesMsg + "\n ");
389 });
390 });
391}
392exports.getPluginByName = getPluginByName;
393function executePlugin(options) {
394 return __awaiter(this, void 0, void 0, function () {
395 var pluginPackage, schema, _a, e_1;
396 return __generator(this, function (_b) {
397 switch (_b.label) {
398 case 0: return [4 /*yield*/, getPluginByName(options.name)];
399 case 1:
400 pluginPackage = _b.sent();
401 if (!pluginPackage.plugin || typeof pluginPackage.plugin !== 'function') {
402 throw new errors_1.DetailedError("Invalid Custom Plugin \"" + options.name + "\"", "\n Plugin " + options.name + " does not export a valid JS object with \"plugin\" function.\n\n Make sure your custom plugin is written in the following form:\n\n module.exports = {\n plugin: (schema, documents, config) => {\n return 'my-custom-plugin-content';\n },\n };\n ");
403 }
404 if (!!pluginPackage.addToSchema) return [3 /*break*/, 2];
405 _a = options.schema;
406 return [3 /*break*/, 4];
407 case 2: return [4 /*yield*/, merge_schemas_1.mergeSchemas([
408 options.schema,
409 graphql_tools_1.makeExecutableSchema({
410 typeDefs: pluginPackage.addToSchema,
411 allowUndefinedInResolve: true,
412 resolverValidationOptions: {
413 requireResolversForResolveType: false,
414 requireResolversForAllFields: false,
415 requireResolversForNonScalar: false,
416 requireResolversForArgs: false
417 }
418 })
419 ])];
420 case 3:
421 _a = _b.sent();
422 _b.label = 4;
423 case 4:
424 schema = _a;
425 if (!(pluginPackage.validate && typeof pluginPackage.validate === 'function')) return [3 /*break*/, 8];
426 _b.label = 5;
427 case 5:
428 _b.trys.push([5, 7, , 8]);
429 return [4 /*yield*/, pluginPackage.validate(schema, options.documents, options.config, options.outputFilename, options.allPlugins)];
430 case 6:
431 _b.sent();
432 return [3 /*break*/, 8];
433 case 7:
434 e_1 = _b.sent();
435 throw new errors_1.DetailedError("Plugin \"" + options.name + "\" validation failed:", "\n " + e_1.message + "\n ");
436 case 8: return [2 /*return*/, pluginPackage.plugin(schema, options.documents, options.config)];
437 }
438 });
439 });
440}
441exports.executePlugin = executePlugin;
442//# sourceMappingURL=codegen.js.map
\No newline at end of file