UNPKG

26.9 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};
48var _this = this;
49Object.defineProperty(exports, "__esModule", { value: true });
50var validate_documents_1 = require("./loaders/documents/validate-documents");
51var commander = require("commander");
52var path = require("path");
53var fs = require("fs");
54var mkdirp = require("mkdirp");
55var chalk_1 = require("chalk");
56var graphql_1 = require("graphql");
57var graphql_config_1 = require("graphql-config");
58var templates_scanner_1 = require("./loaders/template/templates-scanner");
59var graphql_codegen_compiler_1 = require("graphql-codegen-compiler");
60var graphql_codegen_core_1 = require("graphql-codegen-core");
61var epoxy_1 = require("@graphql-modules/epoxy");
62var graphql_tools_1 = require("graphql-tools");
63var load_1 = require("./load");
64var errors_1 = require("./errors");
65var spinner_1 = require("./spinner");
66process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
67function collect(val, memo) {
68 memo.push(val);
69 return memo;
70}
71exports.initCLI = function (args) {
72 commander
73 .usage('gql-gen [options]')
74 .option('-s, --schema <path>', 'Path to GraphQL schema: local JSON file, GraphQL endpoint, local file that exports GraphQLSchema/AST/JSON')
75 .option('-cs, --clientSchema <path>', 'Path to GraphQL client schema: local JSON file, local file that exports GraphQLSchema/AST/JSON')
76 .option('-h, --header [header]', 'Header to add to the introspection HTTP request when using --url/--schema with url', collect, [])
77 .option('-t, --template <template-name>', 'Language/platform name templates, or a name of NPM modules that `export default` GqlGenConfig object')
78 .option('-p, --project <project-path>', 'Project path(s) to scan for custom template files')
79 .option('--config <json-file>', 'Codegen configuration file, defaults to: ./gql-gen.json')
80 .option('-m, --skip-schema', 'Generates only client side documents, without server side schema types')
81 .option('-c, --skip-documents', 'Generates only server side schema types, without client side documents')
82 .option('-o, --out <path>', 'Output file(s) path', String, './')
83 .option('-r, --require [require]', 'module to preload (option can be repeated)', collect, [])
84 .option('-ow, --no-overwrite', 'Skip file writing if the output file(s) already exists in path')
85 .option('-w, --watch', 'Watch for changes and execute generation automatically')
86 .option('--silent', 'Does not print anything to the console')
87 .option('-ms, --merge-schema <merge-logic>', 'Merge schemas with custom logic')
88 .arguments('<options> [documents...]')
89 .parse(args);
90 return commander;
91};
92exports.cliError = function (err, exitOnError) {
93 if (exitOnError === void 0) { exitOnError = true; }
94 spinner_1.default.fail();
95 var msg;
96 if (err instanceof Error) {
97 msg = err.message || err.toString();
98 }
99 else if (typeof err === 'string') {
100 msg = err;
101 }
102 else {
103 msg = JSON.stringify(err);
104 }
105 graphql_codegen_core_1.getLogger().error(msg);
106 if (exitOnError) {
107 process.exit(1);
108 }
109 return;
110};
111exports.validateCliOptions = function (options) {
112 if (options.silent) {
113 graphql_codegen_core_1.setSilentLogger();
114 }
115 else {
116 graphql_codegen_core_1.useWinstonLogger();
117 }
118 var schema = options.schema;
119 var template = options.template;
120 var project = options.project;
121 if (!schema) {
122 try {
123 var graphqlProjectConfig = graphql_config_1.getGraphQLProjectConfig(project);
124 options.schema = graphqlProjectConfig.schemaPath;
125 }
126 catch (e) {
127 if (e instanceof graphql_config_1.ConfigNotFoundError) {
128 exports.cliError("\n \n Flag " + chalk_1.default.bold('--schema') + " is missing.\n \n Schema points to one of following:\n - url of a GraphQL server\n - path to a .graphql file with GraphQL Schema\n - path to a introspection file\n \n\n CLI example:\n \n $ gql-gen --schema ./schema.json ...\n \n API example:\n \n generate({\n schema: './schema.json',\n ...\n });\n\n ");
129 }
130 }
131 }
132 if (!template && !project) {
133 exports.cliError("\n \n Please specify the template.\n \n A template matches an npm package's name.\n\n CLI example:\n \n $ gql-gen --template graphql-codegen-typescript-template ...\n \n API example:\n \n generate({\n template: 'graphql-codegen-typescript-template',\n ...\n });\n\n ");
134 }
135};
136exports.executeWithOptions = function (options) { return __awaiter(_this, void 0, void 0, function () {
137 var schema, clientSchema, documents, template, project, gqlGenConfigFilePath, out, generateSchema, generateDocuments, modulesToRequire, exitOnError, templateConfig, localFilePath, localFileExists, templateFromExport, configPath, config, templates, resolvedHelpers_1, relevantEnvVars, addToSchema, asArray, executeGeneration, normalizeOutput, output, error_1;
138 var _this = this;
139 return __generator(this, function (_a) {
140 switch (_a.label) {
141 case 0:
142 spinner_1.default.start('Validating options');
143 exports.validateCliOptions(options);
144 schema = options.schema;
145 clientSchema = options.clientSchema;
146 documents = options.args || [];
147 template = options.template;
148 project = options.project;
149 gqlGenConfigFilePath = options.config || './gql-gen.json';
150 out = options.out || './';
151 generateSchema = !options.skipSchema;
152 generateDocuments = !options.skipDocuments;
153 modulesToRequire = options.require || [];
154 exitOnError = typeof options.exitOnError === 'undefined' ? true : options.exitOnError;
155 modulesToRequire.forEach(function (mod) { return require(mod); });
156 templateConfig = null;
157 if (template && template !== '') {
158 spinner_1.default.log("Loading template: " + template);
159 graphql_codegen_core_1.debugLog("[executeWithOptions] using template: " + template);
160 // Backward compatibility for older versions
161 if (template === 'ts' ||
162 template === 'ts-single' ||
163 template === 'typescript' ||
164 template === 'typescript-single') {
165 spinner_1.default.warn("You are using the old template name, please install it from NPM and use it by it's new name: \"graphql-codegen-typescript-template\"");
166 template = 'graphql-codegen-typescript-template';
167 }
168 else if (template === 'ts-multiple' || template === 'typescript-multiple') {
169 spinner_1.default.warn("You are using the old template name, please install it from NPM and use it by it's new name: \"graphql-codegen-typescript-template-multiple\"");
170 template = 'graphql-codegen-typescript-template-multiple';
171 }
172 localFilePath = path.resolve(process.cwd(), template);
173 localFileExists = fs.existsSync(localFilePath);
174 try {
175 templateFromExport = require(localFileExists ? localFilePath : template);
176 if (!templateFromExport) {
177 throw new Error();
178 }
179 templateConfig = templateFromExport.default || templateFromExport.config || templateFromExport;
180 spinner_1.default.succeed();
181 }
182 catch (e) {
183 throw new errors_1.DetailedError("\n\n Unknown codegen template: \"" + template + "\"\n\n Please make sure it's installed using npm or yarn.\n\n $ yarn add " + template + " -D\n\n OR\n\n $ npm install " + template + " -D\n\n Template should match package's name.\n\n ");
184 }
185 }
186 graphql_codegen_core_1.debugLog("[executeWithOptions] using project: " + project);
187 configPath = path.resolve(process.cwd(), gqlGenConfigFilePath);
188 config = null;
189 if (fs.existsSync(configPath)) {
190 graphql_codegen_core_1.getLogger().info("Loading config file from: " + configPath);
191 config = JSON.parse(fs.readFileSync(configPath).toString());
192 graphql_codegen_core_1.debugLog("[executeWithOptions] Got project config JSON: " + JSON.stringify(config));
193 }
194 if (project && project !== '') {
195 spinner_1.default.log("Using project: " + project);
196 if (config === null) {
197 throw new errors_1.DetailedError("\n To use project feature, please specify " + chalk_1.default.bold('path to the config file') + " or create " + chalk_1.default.bold('gql-gen.json') + " in your project root\n\n If config file is different then gql-gen.json do the following.\n\n CLI example:\n\n $ gql-gen --config ./my-gql-gen.json\n\n API example:\n\n generate({\n config: './my-gql-gen.json'\n });\n ");
198 }
199 templates = templates_scanner_1.scanForTemplatesInPath(project, graphql_codegen_compiler_1.ALLOWED_CUSTOM_TEMPLATE_EXT);
200 resolvedHelpers_1 = {};
201 Object.keys(config.customHelpers || {}).map(function (helperName) {
202 var filePath = config.customHelpers[helperName];
203 var resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
204 if (fs.existsSync(resolvedPath)) {
205 var requiredFile = require(resolvedPath);
206 if (requiredFile && typeof requiredFile === 'function') {
207 resolvedHelpers_1[helperName] = requiredFile;
208 }
209 else {
210 throw new errors_1.DetailedError("Custom template file " + resolvedPath + " does not have a default export function.");
211 }
212 }
213 else {
214 throw new errors_1.DetailedError("Custom template file " + helperName + " does not exists in path: " + resolvedPath);
215 }
216 });
217 templateConfig = {
218 inputType: graphql_codegen_core_1.EInputType.PROJECT,
219 templates: templates,
220 flattenTypes: config.flattenTypes,
221 primitives: config.primitives,
222 customHelpers: resolvedHelpers_1
223 };
224 }
225 spinner_1.default.succeed();
226 relevantEnvVars = Object.keys(process.env)
227 .filter(function (name) { return name.startsWith('CODEGEN_'); })
228 .reduce(function (prev, name) {
229 var cleanName = name
230 .replace('CODEGEN_', '')
231 .toLowerCase()
232 .replace(/[-_]+/g, ' ')
233 .replace(/[^\w\s]/g, '')
234 .replace(/ (.)/g, function (res) { return res.toUpperCase(); })
235 .replace(/ /g, '');
236 var value = process.env[name];
237 if (value === 'true') {
238 value = true;
239 }
240 else if (value === 'false') {
241 value = false;
242 }
243 prev[cleanName] = value;
244 return prev;
245 }, {});
246 addToSchema = [];
247 if (graphql_codegen_core_1.isGeneratorConfig(templateConfig)) {
248 templateConfig.config = __assign({}, (config && config.generatorConfig ? config.generatorConfig || {} : {}), (options && options['templateConfig'] ? options['templateConfig'] : {}), (relevantEnvVars || {}));
249 if (templateConfig.deprecationNote) {
250 spinner_1.default.warn("Template " + template + " is deprecated: " + templateConfig.deprecationNote);
251 }
252 if (templateConfig.addToSchema) {
253 asArray = Array.isArray(templateConfig.addToSchema)
254 ? templateConfig.addToSchema
255 : [templateConfig.addToSchema];
256 addToSchema = asArray.map(function (extension) { return (typeof extension === 'string' ? graphql_1.parse(extension) : extension); });
257 }
258 if (config) {
259 if ('flattenTypes' in config) {
260 templateConfig.flattenTypes = config.flattenTypes;
261 }
262 if ('primitives' in config) {
263 templateConfig.primitives = __assign({}, templateConfig.primitives, config.primitives);
264 }
265 }
266 }
267 executeGeneration = function () { return __awaiter(_this, void 0, void 0, function () {
268 var schemas, allSchemas, graphQlSchema, _i, addToSchema_1, extension, context, hasDocuments, documentsFiles, loadDocumentErrors, errors, errorCount, _a, loadDocumentErrors_1, loadDocumentError, _b, _c, graphQLError, transformedDocuments;
269 return __generator(this, function (_d) {
270 switch (_d.label) {
271 case 0:
272 schemas = [];
273 try {
274 spinner_1.default.log('Loading remote schema');
275 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema is being loaded ");
276 schemas.push(load_1.loadSchema(schema, options));
277 spinner_1.default.succeed();
278 }
279 catch (e) {
280 graphql_codegen_core_1.debugLog("[executeWithOptions] Failed to load schema", e);
281 exports.cliError("\n \n " + chalk_1.default.bold('Invalid schema provided.') + "\n Please use a path to local file, HTTP endpoint or a glob expression.\n\n Local file should export a string, GraphQLSchema object or should be a .graphql file.\n GraphQL Code Generator accepts: ES6 modules and CommonJS modules.\n It should either export schema with the " + chalk_1.default.italic('schema') + " variable or with default export.\n\n CLI example:\n\n $ gql-gen --schema ./path/to/schema.json ...\n\n API example:\n\n generate({\n schema: './path/to/schema.json',\n ...\n });\n\n ");
282 }
283 if (clientSchema) {
284 spinner_1.default.log('Loading client schema');
285 try {
286 graphql_codegen_core_1.debugLog("[executeWithOptions] Client Schema is being loaded ");
287 schemas.push(load_1.loadSchema(clientSchema, options));
288 spinner_1.default.succeed();
289 }
290 catch (e) {
291 graphql_codegen_core_1.debugLog("[executeWithOptions] Failed to load client schema", e);
292 exports.cliError("\n \n " + chalk_1.default.bold('Invalid client schema.') + "\n Please use a path to local file or a glob expression.\n\n Local file should export a string, GraphQLSchema object or should be a .graphql file.\n GraphQL Code Generator accepts: ES6 modules and CommonJS modules.\n It should either export schema with the " + chalk_1.default.italic('schema') + " variable or with default export.\n\n CLI example:\n\n $ gql-gen --clientSchema ./path/to/schema.json\n\n API example:\n\n generate({\n clientSchema: './path/to/schema.json',\n ...\n });\n\n ");
293 }
294 }
295 return [4 /*yield*/, Promise.all(schemas)];
296 case 1:
297 allSchemas = _d.sent();
298 graphQlSchema = allSchemas.length === 1
299 ? allSchemas[0]
300 : graphql_tools_1.makeExecutableSchema({ typeDefs: epoxy_1.mergeGraphQLSchemas(allSchemas), allowUndefinedInResolve: true });
301 if (addToSchema && addToSchema.length > 0) {
302 for (_i = 0, addToSchema_1 = addToSchema; _i < addToSchema_1.length; _i++) {
303 extension = addToSchema_1[_i];
304 graphql_codegen_core_1.debugLog("Extending GraphQL Schema with: ", extension);
305 graphQlSchema = graphql_1.extendSchema(graphQlSchema, extension);
306 }
307 }
308 if (process.env.VERBOSE !== undefined) {
309 graphql_codegen_core_1.getLogger().info("GraphQL Schema is: ", graphQlSchema);
310 }
311 context = graphql_codegen_core_1.schemaToTemplateContext(graphQlSchema);
312 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema template context build, the result is: ");
313 Object.keys(context).forEach(function (key) {
314 if (Array.isArray(context[key])) {
315 graphql_codegen_core_1.debugLog("Total of " + key + ": " + context[key].length);
316 }
317 });
318 hasDocuments = documents.length;
319 if (hasDocuments) {
320 spinner_1.default.log('Loading documents');
321 }
322 return [4 /*yield*/, load_1.loadDocuments(documents)];
323 case 2:
324 documentsFiles = _d.sent();
325 loadDocumentErrors = validate_documents_1.validateGraphQlDocuments(graphQlSchema, documentsFiles);
326 if (loadDocumentErrors.length > 0) {
327 errors = [];
328 errorCount = 0;
329 for (_a = 0, loadDocumentErrors_1 = loadDocumentErrors; _a < loadDocumentErrors_1.length; _a++) {
330 loadDocumentError = loadDocumentErrors_1[_a];
331 for (_b = 0, _c = loadDocumentError.errors; _b < _c.length; _b++) {
332 graphQLError = _c[_b];
333 errors.push("\n\n " + loadDocumentError.filePath + ": \n " + graphQLError.message + "\n\n ");
334 errorCount++;
335 }
336 }
337 exports.cliError("\n\n Found " + errorCount + " errors.\n\n GraphQL Code Generator validated your GraphQL documents against the schema.\n Please fix following errors and run codegen again:\n\n\n " + errors.join('') + "\n \n ", options.watch ? false : exitOnError);
338 }
339 transformedDocuments = graphql_codegen_core_1.transformDocumentsFiles(graphQlSchema, documentsFiles);
340 if (hasDocuments) {
341 spinner_1.default.succeed();
342 }
343 spinner_1.default.log("Compiling template: " + template);
344 try {
345 return [2 /*return*/, graphql_codegen_compiler_1.compileTemplate(templateConfig, context, [transformedDocuments], {
346 generateSchema: generateSchema,
347 generateDocuments: generateDocuments
348 })];
349 }
350 catch (error) {
351 throw new errors_1.DetailedError("\n Failed to compile " + template + " template.\n\n In most cases it's related to the configuration and the GraphQL schema.\n\n " + error.message + "\n\n ");
352 }
353 return [2 /*return*/];
354 }
355 });
356 }); };
357 normalizeOutput = function (item) {
358 var resultName = item.filename;
359 if (!path.isAbsolute(resultName)) {
360 var resolved = path.resolve(process.cwd(), out);
361 if (fs.existsSync(resolved)) {
362 var stats = fs.lstatSync(resolved);
363 if (stats.isDirectory()) {
364 resultName = path.resolve(resolved, item.filename);
365 }
366 else if (stats.isFile()) {
367 resultName = resolved;
368 }
369 }
370 else {
371 if (out.endsWith('/')) {
372 resultName = path.resolve(resolved, item.filename);
373 }
374 else {
375 resultName = resolved;
376 }
377 }
378 }
379 var resultDir = path.dirname(resultName);
380 mkdirp.sync(resultDir);
381 return {
382 content: item.content,
383 filename: resultName
384 };
385 };
386 _a.label = 1;
387 case 1:
388 _a.trys.push([1, 3, , 4]);
389 return [4 /*yield*/, executeGeneration()];
390 case 2:
391 output = _a.sent();
392 return [2 /*return*/, output.map(normalizeOutput)];
393 case 3:
394 error_1 = _a.sent();
395 if (error_1 instanceof errors_1.DetailedError) {
396 throw error_1;
397 }
398 else {
399 throw new errors_1.DetailedError("\n \n Failed to finish the task:\n\n " + error_1.message + "\n\n ", error_1);
400 }
401 return [3 /*break*/, 4];
402 case 4: return [2 /*return*/];
403 }
404 });
405}); };
406//# sourceMappingURL=codegen.js.map
\No newline at end of file