UNPKG

24.1 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 commander = require("commander");
51var path = require("path");
52var fs = require("fs");
53var mkdirp = require("mkdirp");
54var graphql_1 = require("graphql");
55var graphql_config_1 = require("graphql-config");
56var documents_glob_1 = require("./utils/documents-glob");
57var document_loader_1 = require("./loaders/documents/document-loader");
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 introspection_from_file_1 = require("./loaders/schema/introspection-from-file");
62var introspection_from_url_1 = require("./loaders/schema/introspection-from-url");
63var schema_from_typedefs_1 = require("./loaders/schema/schema-from-typedefs");
64var schema_from_export_1 = require("./loaders/schema/schema-from-export");
65var epoxy_1 = require("@graphql-modules/epoxy");
66var graphql_tools_1 = require("graphql-tools");
67process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
68function collect(val, memo) {
69 memo.push(val);
70 return memo;
71}
72exports.initCLI = function (args) {
73 commander
74 .usage('gql-gen [options]')
75 .option('-s, --schema <path>', 'Path to GraphQL schema: local JSON file, GraphQL endpoint, local file that exports GraphQLSchema/AST/JSON')
76 .option('-cs, --clientSchema <path>', 'Path to GraphQL client schema: local JSON file, local file that exports GraphQLSchema/AST/JSON')
77 .option('-h, --header [header]', 'Header to add to the introspection HTTP request when using --url/--schema with url', collect, [])
78 .option('-t, --template <template-name>', 'Language/platform name templates, or a name of NPM modules that `export default` GqlGenConfig object')
79 .option('-p, --project <project-path>', 'Project path(s) to scan for custom template files')
80 .option('--config <json-file>', 'Codegen configuration file, defaults to: ./gql-gen.json')
81 .option('-m, --skip-schema', 'Generates only client side documents, without server side schema types')
82 .option('-c, --skip-documents', 'Generates only server side schema types, without client side documents')
83 .option('-o, --out <path>', 'Output file(s) path', String, './')
84 .option('-r, --require [require]', 'module to preload (option can be repeated)', collect, [])
85 .option('-ow, --no-overwrite', 'Skip file writing if the output file(s) already exists in path')
86 .option('-w, --watch', 'Watch for changes and execute generation automatically')
87 .option('--silent', 'Does not print anything to the console')
88 .option('-ms, --merge-schema <merge-logic>', 'Merge schemas with custom logic')
89 .arguments('<options> [documents...]')
90 .parse(args);
91 return commander;
92};
93exports.cliError = function (err, exitOnError) {
94 if (exitOnError === void 0) { exitOnError = true; }
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('Flag --schema is missing!');
129 }
130 }
131 }
132 if (!template && !project) {
133 exports.cliError('Please specify language/platform, using --template flag, or specify --project to generate with custom project!');
134 }
135};
136var schemaHandlers = [
137 new introspection_from_url_1.IntrospectionFromUrlLoader(),
138 new introspection_from_file_1.IntrospectionFromFileLoader(),
139 new schema_from_typedefs_1.SchemaFromTypedefs(),
140 new schema_from_export_1.SchemaFromExport()
141];
142exports.executeWithOptions = function (options) { return __awaiter(_this, void 0, void 0, function () {
143 var schema, clientSchema, documents, template, project, gqlGenConfigFilePath, out, generateSchema, generateDocuments, modulesToRequire, templateConfig, localFilePath, localFileExists, templateFromExport, configPath, config, templates, resolvedHelpers_1, relevantEnvVars, addToSchema, asArray, executeGeneration, normalizeOutput;
144 var _this = this;
145 return __generator(this, function (_a) {
146 switch (_a.label) {
147 case 0:
148 exports.validateCliOptions(options);
149 schema = options.schema;
150 clientSchema = options.clientSchema;
151 documents = options.args || [];
152 template = options.template;
153 project = options.project;
154 gqlGenConfigFilePath = options.config || './gql-gen.json';
155 out = options.out || './';
156 generateSchema = !options.skipSchema;
157 generateDocuments = !options.skipDocuments;
158 modulesToRequire = options.require || [];
159 modulesToRequire.forEach(function (mod) { return require(mod); });
160 templateConfig = null;
161 if (template && template !== '') {
162 graphql_codegen_core_1.debugLog("[executeWithOptions] using template: " + template);
163 // Backward compatibility for older versions
164 if (template === 'ts' ||
165 template === 'ts-single' ||
166 template === 'typescript' ||
167 template === 'typescript-single') {
168 graphql_codegen_core_1.getLogger().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\"");
169 template = 'graphql-codegen-typescript-template';
170 }
171 else if (template === 'ts-multiple' || template === 'typescript-multiple') {
172 graphql_codegen_core_1.getLogger().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\"");
173 template = 'graphql-codegen-typescript-template-multiple';
174 }
175 localFilePath = path.resolve(process.cwd(), template);
176 localFileExists = fs.existsSync(localFilePath);
177 try {
178 templateFromExport = require(localFileExists ? localFilePath : template);
179 if (!templateFromExport) {
180 throw new Error();
181 }
182 templateConfig = templateFromExport.default || templateFromExport.config || templateFromExport;
183 }
184 catch (e) {
185 throw new Error("Unknown codegen template: \"" + template + "\", please make sure it's installed using npm/Yarn!");
186 }
187 }
188 graphql_codegen_core_1.debugLog("[executeWithOptions] using project: " + project);
189 configPath = path.resolve(process.cwd(), gqlGenConfigFilePath);
190 config = null;
191 if (fs.existsSync(configPath)) {
192 graphql_codegen_core_1.getLogger().info("Loading config file from: " + configPath);
193 config = JSON.parse(fs.readFileSync(configPath).toString());
194 graphql_codegen_core_1.debugLog("[executeWithOptions] Got project config JSON: " + JSON.stringify(config));
195 }
196 if (project && project !== '') {
197 if (config === null) {
198 throw new Error("To use project feature, please specify --config path or create gql-gen.json in your project root!");
199 }
200 templates = templates_scanner_1.scanForTemplatesInPath(project, graphql_codegen_compiler_1.ALLOWED_CUSTOM_TEMPLATE_EXT);
201 resolvedHelpers_1 = {};
202 Object.keys(config.customHelpers || {}).map(function (helperName) {
203 var filePath = config.customHelpers[helperName];
204 var resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
205 if (fs.existsSync(resolvedPath)) {
206 var requiredFile = require(resolvedPath);
207 if (requiredFile && typeof requiredFile === 'function') {
208 resolvedHelpers_1[helperName] = requiredFile;
209 }
210 else {
211 throw new Error("Custom template file " + resolvedPath + " does not have a default export function!");
212 }
213 }
214 else {
215 throw new Error("Custom template file " + helperName + " does not exists in path: " + resolvedPath);
216 }
217 });
218 templateConfig = {
219 inputType: graphql_codegen_core_1.EInputType.PROJECT,
220 templates: templates,
221 flattenTypes: config.flattenTypes,
222 primitives: config.primitives,
223 customHelpers: resolvedHelpers_1
224 };
225 }
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 graphql_codegen_core_1.getLogger().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 loadSchema, schemas, allSchemas, graphQlSchema, _i, addToSchema_1, extension, context, documentSourcesResult, _a, _b, errorCount, loadDocumentErrors, _c, loadDocumentErrors_1, loadDocumentError, _d, _e, graphQLError, transformedDocuments;
269 var _this = this;
270 return __generator(this, function (_f) {
271 switch (_f.label) {
272 case 0:
273 loadSchema = function (pointToSchema) { return __awaiter(_this, void 0, void 0, function () {
274 var _i, schemaHandlers_1, handler;
275 return __generator(this, function (_a) {
276 switch (_a.label) {
277 case 0:
278 _i = 0, schemaHandlers_1 = schemaHandlers;
279 _a.label = 1;
280 case 1:
281 if (!(_i < schemaHandlers_1.length)) return [3 /*break*/, 4];
282 handler = schemaHandlers_1[_i];
283 return [4 /*yield*/, handler.canHandle(pointToSchema)];
284 case 2:
285 if (_a.sent()) {
286 return [2 /*return*/, handler.handle(pointToSchema, options)];
287 }
288 _a.label = 3;
289 case 3:
290 _i++;
291 return [3 /*break*/, 1];
292 case 4: throw new Error('Could not handle schema');
293 }
294 });
295 }); };
296 schemas = [];
297 try {
298 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema is being loaded ");
299 schemas.push(loadSchema(schema));
300 }
301 catch (e) {
302 graphql_codegen_core_1.debugLog("[executeWithOptions] Failed to load schema", e);
303 exports.cliError('Invalid --schema provided, please use a path to local file, HTTP endpoint or a glob expression!');
304 }
305 if (clientSchema) {
306 try {
307 graphql_codegen_core_1.debugLog("[executeWithOptions] Client Schema is being loaded ");
308 schemas.push(loadSchema(clientSchema));
309 }
310 catch (e) {
311 graphql_codegen_core_1.debugLog("[executeWithOptions] Failed to load client schema", e);
312 exports.cliError('Invalid --clientSchema provided, please use a path to local file or a glob expression!');
313 }
314 }
315 return [4 /*yield*/, Promise.all(schemas)];
316 case 1:
317 allSchemas = _f.sent();
318 graphQlSchema = allSchemas.length === 1
319 ? allSchemas[0]
320 : graphql_tools_1.makeExecutableSchema({ typeDefs: epoxy_1.mergeGraphQLSchemas(allSchemas), allowUndefinedInResolve: true });
321 if (addToSchema && addToSchema.length > 0) {
322 for (_i = 0, addToSchema_1 = addToSchema; _i < addToSchema_1.length; _i++) {
323 extension = addToSchema_1[_i];
324 graphql_codegen_core_1.debugLog("Extending GraphQL Schema with: ", extension);
325 graphQlSchema = graphql_1.extendSchema(graphQlSchema, extension);
326 }
327 }
328 if (process.env.VERBOSE !== undefined) {
329 graphql_codegen_core_1.getLogger().info("GraphQL Schema is: ", graphQlSchema);
330 }
331 context = graphql_codegen_core_1.schemaToTemplateContext(graphQlSchema);
332 graphql_codegen_core_1.debugLog("[executeWithOptions] Schema template context build, the result is: ");
333 Object.keys(context).forEach(function (key) {
334 if (Array.isArray(context[key])) {
335 graphql_codegen_core_1.debugLog("Total of " + key + ": " + context[key].length);
336 }
337 });
338 _a = document_loader_1.loadDocumentsSources;
339 _b = [graphQlSchema];
340 return [4 /*yield*/, documents_glob_1.documentsFromGlobs(documents)];
341 case 2:
342 documentSourcesResult = _a.apply(void 0, _b.concat([_f.sent()]));
343 if (Array.isArray(documentSourcesResult) && documentSourcesResult.length > 0) {
344 errorCount = 0;
345 loadDocumentErrors = documentSourcesResult;
346 for (_c = 0, loadDocumentErrors_1 = loadDocumentErrors; _c < loadDocumentErrors_1.length; _c++) {
347 loadDocumentError = loadDocumentErrors_1[_c];
348 for (_d = 0, _e = loadDocumentError.errors; _d < _e.length; _d++) {
349 graphQLError = _e[_d];
350 graphql_codegen_core_1.getLogger().error("[" + loadDocumentError.filePath + "] GraphQL Error: " + graphQLError.message);
351 errorCount++;
352 }
353 }
354 exports.cliError("Found " + errorCount + " errors when validating your GraphQL documents against schema!", !options.watch);
355 }
356 transformedDocuments = graphql_codegen_core_1.transformDocument(graphQlSchema, documentSourcesResult);
357 return [2 /*return*/, graphql_codegen_compiler_1.compileTemplate(templateConfig, context, [transformedDocuments], {
358 generateSchema: generateSchema,
359 generateDocuments: generateDocuments
360 })];
361 }
362 });
363 }); };
364 normalizeOutput = function (item) {
365 var resultName = item.filename;
366 if (!path.isAbsolute(resultName)) {
367 var resolved = path.resolve(process.cwd(), out);
368 if (fs.existsSync(resolved)) {
369 var stats = fs.lstatSync(resolved);
370 if (stats.isDirectory()) {
371 resultName = path.resolve(resolved, item.filename);
372 }
373 else if (stats.isFile()) {
374 resultName = resolved;
375 }
376 }
377 else {
378 if (out.endsWith('/')) {
379 resultName = path.resolve(resolved, item.filename);
380 }
381 else {
382 resultName = resolved;
383 }
384 }
385 }
386 var resultDir = path.dirname(resultName);
387 mkdirp.sync(resultDir);
388 return {
389 content: item.content,
390 filename: resultName
391 };
392 };
393 return [4 /*yield*/, executeGeneration()];
394 case 1: return [2 /*return*/, (_a.sent()).map(normalizeOutput)];
395 }
396 });
397}); };
398//# sourceMappingURL=codegen.js.map
\No newline at end of file