@graphql-codegen/cli 2.7.0 → 2.7.1-alpha-223b75f49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/bin.js +13 -0
- package/cjs/cli.js +60 -0
- package/cjs/codegen.js +319 -0
- package/cjs/config.js +303 -0
- package/cjs/generate-and-save.js +110 -0
- package/cjs/graphql-config.js +69 -0
- package/cjs/hooks.js +87 -0
- package/cjs/index.js +13 -0
- package/cjs/init/helpers.js +64 -0
- package/cjs/init/index.js +60 -0
- package/cjs/init/plugins.js +163 -0
- package/cjs/init/questions.js +147 -0
- package/cjs/init/targets.js +44 -0
- package/cjs/init/types.js +14 -0
- package/cjs/load.js +93 -0
- package/cjs/package.json +1 -0
- package/cjs/plugins.js +45 -0
- package/cjs/presets.js +50 -0
- package/cjs/utils/cli-error.js +25 -0
- package/cjs/utils/debugging.js +27 -0
- package/cjs/utils/file-system.js +26 -0
- package/cjs/utils/logger.js +25 -0
- package/cjs/utils/watcher.js +140 -0
- package/esm/bin.js +11 -0
- package/esm/cli.js +32 -0
- package/esm/codegen.js +314 -0
- package/esm/config.js +290 -0
- package/esm/generate-and-save.js +105 -0
- package/esm/graphql-config.js +64 -0
- package/esm/hooks.js +83 -0
- package/esm/index.js +7 -0
- package/esm/init/helpers.js +55 -0
- package/esm/init/index.js +55 -0
- package/esm/init/plugins.js +160 -0
- package/esm/init/questions.js +140 -0
- package/esm/init/targets.js +40 -0
- package/esm/init/types.js +11 -0
- package/esm/load.js +88 -0
- package/esm/plugins.js +41 -0
- package/esm/presets.js +46 -0
- package/esm/utils/cli-error.js +20 -0
- package/esm/utils/debugging.js +21 -0
- package/esm/utils/file-system.js +19 -0
- package/esm/utils/logger.js +18 -0
- package/esm/utils/watcher.js +135 -0
- package/package.json +33 -29
- package/typings/bin.d.ts +2 -0
- package/{cli.d.ts → typings/cli.d.ts} +0 -0
- package/{codegen.d.ts → typings/codegen.d.ts} +1 -1
- package/{config.d.ts → typings/config.d.ts} +0 -0
- package/{generate-and-save.d.ts → typings/generate-and-save.d.ts} +1 -1
- package/{graphql-config.d.ts → typings/graphql-config.d.ts} +0 -0
- package/{hooks.d.ts → typings/hooks.d.ts} +0 -0
- package/typings/index.d.ts +7 -0
- package/{init → typings/init}/helpers.d.ts +1 -1
- package/{init → typings/init}/index.d.ts +0 -0
- package/{init → typings/init}/plugins.d.ts +1 -1
- package/{init → typings/init}/questions.d.ts +1 -1
- package/{init → typings/init}/targets.d.ts +1 -1
- package/{init → typings/init}/types.d.ts +0 -0
- package/{load.d.ts → typings/load.d.ts} +0 -0
- package/{plugins.d.ts → typings/plugins.d.ts} +0 -0
- package/{presets.d.ts → typings/presets.d.ts} +0 -0
- package/{utils → typings/utils}/cli-error.d.ts +0 -0
- package/{utils → typings/utils}/debugging.d.ts +0 -0
- package/{utils → typings/utils}/file-system.d.ts +0 -0
- package/{utils → typings/utils}/logger.d.ts +0 -0
- package/{utils → typings/utils}/watcher.d.ts +1 -1
- package/bin.d.ts +0 -1
- package/bin.js +0 -1891
- package/index.d.ts +0 -7
- package/index.js +0 -1902
- package/index.mjs +0 -1858
- package/utils/indentString.d.ts +0 -26
- package/utils/listr-renderer.d.ts +0 -18
package/cjs/config.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ensureContext = exports.CodegenContext = exports.updateContextWithCliFlags = exports.createContext = exports.parseArgv = exports.buildOptions = exports.loadContext = exports.loadCodegenConfig = exports.generateSearchPlaces = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const cosmiconfig_1 = require("cosmiconfig");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
|
|
8
|
+
const string_env_interpolation_1 = require("string-env-interpolation");
|
|
9
|
+
const yargs_1 = tslib_1.__importDefault(require("yargs"));
|
|
10
|
+
const graphql_config_js_1 = require("./graphql-config.js");
|
|
11
|
+
const load_js_1 = require("./load.js");
|
|
12
|
+
const graphql_1 = require("graphql");
|
|
13
|
+
const yaml_1 = tslib_1.__importDefault(require("yaml"));
|
|
14
|
+
const module_1 = require("module");
|
|
15
|
+
const fs_1 = require("fs");
|
|
16
|
+
const crypto_1 = require("crypto");
|
|
17
|
+
const { lstat } = fs_1.promises;
|
|
18
|
+
function generateSearchPlaces(moduleName) {
|
|
19
|
+
const extensions = ['json', 'yaml', 'yml', 'js', 'config.js'];
|
|
20
|
+
// gives codegen.json...
|
|
21
|
+
const regular = extensions.map(ext => `${moduleName}.${ext}`);
|
|
22
|
+
// gives .codegenrc.json... but no .codegenrc.config.js
|
|
23
|
+
const dot = extensions.filter(ext => ext !== 'config.js').map(ext => `.${moduleName}rc.${ext}`);
|
|
24
|
+
return [...regular.concat(dot), 'package.json'];
|
|
25
|
+
}
|
|
26
|
+
exports.generateSearchPlaces = generateSearchPlaces;
|
|
27
|
+
function customLoader(ext) {
|
|
28
|
+
function loader(filepath, content) {
|
|
29
|
+
if (typeof process !== 'undefined' && 'env' in process) {
|
|
30
|
+
content = (0, string_env_interpolation_1.env)(content);
|
|
31
|
+
}
|
|
32
|
+
if (ext === 'json') {
|
|
33
|
+
return cosmiconfig_1.defaultLoaders['.json'](filepath, content);
|
|
34
|
+
}
|
|
35
|
+
if (ext === 'yaml') {
|
|
36
|
+
try {
|
|
37
|
+
const result = yaml_1.default.parse(content, { prettyErrors: true, merge: true });
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
error.message = `YAML Error in ${filepath}:\n${error.message}`;
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (ext === 'js') {
|
|
46
|
+
return cosmiconfig_1.defaultLoaders['.js'](filepath, content);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return loader;
|
|
50
|
+
}
|
|
51
|
+
async function loadCodegenConfig({ configFilePath, moduleName, searchPlaces: additionalSearchPlaces, packageProp, loaders: customLoaders, }) {
|
|
52
|
+
configFilePath = configFilePath || process.cwd();
|
|
53
|
+
moduleName = moduleName || 'codegen';
|
|
54
|
+
packageProp = packageProp || moduleName;
|
|
55
|
+
const cosmi = (0, cosmiconfig_1.cosmiconfig)(moduleName, {
|
|
56
|
+
searchPlaces: generateSearchPlaces(moduleName).concat(additionalSearchPlaces || []),
|
|
57
|
+
packageProp,
|
|
58
|
+
loaders: {
|
|
59
|
+
'.json': customLoader('json'),
|
|
60
|
+
'.yaml': customLoader('yaml'),
|
|
61
|
+
'.yml': customLoader('yaml'),
|
|
62
|
+
'.js': customLoader('js'),
|
|
63
|
+
noExt: customLoader('yaml'),
|
|
64
|
+
...customLoaders,
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
const pathStats = await lstat(configFilePath);
|
|
68
|
+
return pathStats.isDirectory() ? cosmi.search(configFilePath) : cosmi.load(configFilePath);
|
|
69
|
+
}
|
|
70
|
+
exports.loadCodegenConfig = loadCodegenConfig;
|
|
71
|
+
async function loadContext(configFilePath) {
|
|
72
|
+
const graphqlConfig = await (0, graphql_config_js_1.findAndLoadGraphQLConfig)(configFilePath);
|
|
73
|
+
if (graphqlConfig) {
|
|
74
|
+
return new CodegenContext({
|
|
75
|
+
graphqlConfig,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const result = await loadCodegenConfig({ configFilePath });
|
|
79
|
+
if (!result) {
|
|
80
|
+
if (configFilePath) {
|
|
81
|
+
throw new plugin_helpers_1.DetailedError(`Config ${configFilePath} does not exist`, `
|
|
82
|
+
Config ${configFilePath} does not exist.
|
|
83
|
+
|
|
84
|
+
$ graphql-codegen --config ${configFilePath}
|
|
85
|
+
|
|
86
|
+
Please make sure the --config points to a correct file.
|
|
87
|
+
`);
|
|
88
|
+
}
|
|
89
|
+
throw new plugin_helpers_1.DetailedError(`Unable to find Codegen config file!`, `
|
|
90
|
+
Please make sure that you have a configuration file under the current directory!
|
|
91
|
+
`);
|
|
92
|
+
}
|
|
93
|
+
if (result.isEmpty) {
|
|
94
|
+
throw new plugin_helpers_1.DetailedError(`Found Codegen config file but it was empty!`, `
|
|
95
|
+
Please make sure that you have a valid configuration file under the current directory!
|
|
96
|
+
`);
|
|
97
|
+
}
|
|
98
|
+
return new CodegenContext({
|
|
99
|
+
filepath: result.filepath,
|
|
100
|
+
config: result.config,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
exports.loadContext = loadContext;
|
|
104
|
+
function getCustomConfigPath(cliFlags) {
|
|
105
|
+
const configFile = cliFlags.config;
|
|
106
|
+
return configFile ? (0, path_1.resolve)(process.cwd(), configFile) : null;
|
|
107
|
+
}
|
|
108
|
+
function buildOptions() {
|
|
109
|
+
return {
|
|
110
|
+
c: {
|
|
111
|
+
alias: 'config',
|
|
112
|
+
type: 'string',
|
|
113
|
+
describe: 'Path to GraphQL codegen YAML config file, defaults to "codegen.yml" on the current directory',
|
|
114
|
+
},
|
|
115
|
+
w: {
|
|
116
|
+
alias: 'watch',
|
|
117
|
+
describe: 'Watch for changes and execute generation automatically. You can also specify a glob expreession for custom watch list.',
|
|
118
|
+
coerce: (watch) => {
|
|
119
|
+
if (watch === 'false') {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
if (typeof watch === 'string' || Array.isArray(watch)) {
|
|
123
|
+
return watch;
|
|
124
|
+
}
|
|
125
|
+
return !!watch;
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
r: {
|
|
129
|
+
alias: 'require',
|
|
130
|
+
describe: 'Loads specific require.extensions before running the codegen and reading the configuration',
|
|
131
|
+
type: 'array',
|
|
132
|
+
default: [],
|
|
133
|
+
},
|
|
134
|
+
o: {
|
|
135
|
+
alias: 'overwrite',
|
|
136
|
+
describe: 'Overwrites existing files',
|
|
137
|
+
type: 'boolean',
|
|
138
|
+
},
|
|
139
|
+
s: {
|
|
140
|
+
alias: 'silent',
|
|
141
|
+
describe: 'Suppresses printing errors',
|
|
142
|
+
type: 'boolean',
|
|
143
|
+
},
|
|
144
|
+
e: {
|
|
145
|
+
alias: 'errors-only',
|
|
146
|
+
describe: 'Only print errors',
|
|
147
|
+
type: 'boolean',
|
|
148
|
+
},
|
|
149
|
+
profile: {
|
|
150
|
+
describe: 'Use profiler to measure performance',
|
|
151
|
+
type: 'boolean',
|
|
152
|
+
},
|
|
153
|
+
p: {
|
|
154
|
+
alias: 'project',
|
|
155
|
+
describe: 'Name of a project in GraphQL Config',
|
|
156
|
+
type: 'string',
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
exports.buildOptions = buildOptions;
|
|
161
|
+
function parseArgv(argv = process.argv) {
|
|
162
|
+
return (0, yargs_1.default)(argv).options(buildOptions()).parse(argv);
|
|
163
|
+
}
|
|
164
|
+
exports.parseArgv = parseArgv;
|
|
165
|
+
async function createContext(cliFlags = parseArgv(process.argv)) {
|
|
166
|
+
if (cliFlags.require && cliFlags.require.length > 0) {
|
|
167
|
+
const relativeRequire = (0, module_1.createRequire)(process.cwd());
|
|
168
|
+
await Promise.all(cliFlags.require.map(mod => Promise.resolve().then(() => tslib_1.__importStar(require(relativeRequire.resolve(mod, {
|
|
169
|
+
paths: [process.cwd()],
|
|
170
|
+
}))))));
|
|
171
|
+
}
|
|
172
|
+
const customConfigPath = getCustomConfigPath(cliFlags);
|
|
173
|
+
const context = await loadContext(customConfigPath);
|
|
174
|
+
updateContextWithCliFlags(context, cliFlags);
|
|
175
|
+
return context;
|
|
176
|
+
}
|
|
177
|
+
exports.createContext = createContext;
|
|
178
|
+
function updateContextWithCliFlags(context, cliFlags) {
|
|
179
|
+
const config = {
|
|
180
|
+
configFilePath: context.filepath,
|
|
181
|
+
};
|
|
182
|
+
if (cliFlags.watch) {
|
|
183
|
+
config.watch = cliFlags.watch;
|
|
184
|
+
}
|
|
185
|
+
if (cliFlags.overwrite === true) {
|
|
186
|
+
config.overwrite = cliFlags.overwrite;
|
|
187
|
+
}
|
|
188
|
+
if (cliFlags.silent === true) {
|
|
189
|
+
config.silent = cliFlags.silent;
|
|
190
|
+
}
|
|
191
|
+
if (cliFlags.errorsOnly === true) {
|
|
192
|
+
config.errorsOnly = cliFlags.errorsOnly;
|
|
193
|
+
}
|
|
194
|
+
if (cliFlags.project) {
|
|
195
|
+
context.useProject(cliFlags.project);
|
|
196
|
+
}
|
|
197
|
+
if (cliFlags.profile === true) {
|
|
198
|
+
context.useProfiler();
|
|
199
|
+
}
|
|
200
|
+
context.updateConfig(config);
|
|
201
|
+
}
|
|
202
|
+
exports.updateContextWithCliFlags = updateContextWithCliFlags;
|
|
203
|
+
class CodegenContext {
|
|
204
|
+
constructor({ config, graphqlConfig, filepath, }) {
|
|
205
|
+
this._pluginContext = {};
|
|
206
|
+
this._config = config;
|
|
207
|
+
this._graphqlConfig = graphqlConfig;
|
|
208
|
+
this.filepath = this._graphqlConfig ? this._graphqlConfig.filepath : filepath;
|
|
209
|
+
this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : process.cwd();
|
|
210
|
+
this.profiler = (0, plugin_helpers_1.createNoopProfiler)();
|
|
211
|
+
}
|
|
212
|
+
useProject(name) {
|
|
213
|
+
this._project = name;
|
|
214
|
+
}
|
|
215
|
+
getConfig(extraConfig) {
|
|
216
|
+
if (!this.config) {
|
|
217
|
+
if (this._graphqlConfig) {
|
|
218
|
+
const project = this._graphqlConfig.getProject(this._project);
|
|
219
|
+
this.config = {
|
|
220
|
+
...project.extension('codegen'),
|
|
221
|
+
schema: project.schema,
|
|
222
|
+
documents: project.documents,
|
|
223
|
+
pluginContext: this._pluginContext,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
this.config = { ...this._config, pluginContext: this._pluginContext };
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
...extraConfig,
|
|
232
|
+
...this.config,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
updateConfig(config) {
|
|
236
|
+
this.config = {
|
|
237
|
+
...this.getConfig(),
|
|
238
|
+
...config,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
useProfiler() {
|
|
242
|
+
this.profiler = (0, plugin_helpers_1.createProfiler)();
|
|
243
|
+
const now = new Date(); // 2011-10-05T14:48:00.000Z
|
|
244
|
+
const datetime = now.toISOString().split('.')[0]; // 2011-10-05T14:48:00
|
|
245
|
+
const datetimeNormalized = datetime.replace(/-|:/g, ''); // 20111005T144800
|
|
246
|
+
this.profilerOutput = `codegen-${datetimeNormalized}.json`;
|
|
247
|
+
}
|
|
248
|
+
getPluginContext() {
|
|
249
|
+
return this._pluginContext;
|
|
250
|
+
}
|
|
251
|
+
async loadSchema(pointer) {
|
|
252
|
+
const config = this.getConfig(load_js_1.defaultSchemaLoadOptions);
|
|
253
|
+
if (this._graphqlConfig) {
|
|
254
|
+
// TODO: SchemaWithLoader won't work here
|
|
255
|
+
return addHashToSchema(this._graphqlConfig.getProject(this._project).loadSchema(pointer, 'GraphQLSchema', config));
|
|
256
|
+
}
|
|
257
|
+
return addHashToSchema((0, load_js_1.loadSchema)(pointer, config));
|
|
258
|
+
}
|
|
259
|
+
async loadDocuments(pointer) {
|
|
260
|
+
const config = this.getConfig(load_js_1.defaultDocumentsLoadOptions);
|
|
261
|
+
if (this._graphqlConfig) {
|
|
262
|
+
// TODO: pointer won't work here
|
|
263
|
+
return addHashToDocumentFiles(this._graphqlConfig.getProject(this._project).loadDocuments(pointer, config));
|
|
264
|
+
}
|
|
265
|
+
return addHashToDocumentFiles((0, load_js_1.loadDocuments)(pointer, config));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
exports.CodegenContext = CodegenContext;
|
|
269
|
+
function ensureContext(input) {
|
|
270
|
+
return input instanceof CodegenContext ? input : new CodegenContext({ config: input });
|
|
271
|
+
}
|
|
272
|
+
exports.ensureContext = ensureContext;
|
|
273
|
+
function hashContent(content) {
|
|
274
|
+
return (0, crypto_1.createHash)('sha256').update(content).digest('hex');
|
|
275
|
+
}
|
|
276
|
+
function hashSchema(schema) {
|
|
277
|
+
return hashContent((0, graphql_1.print)((0, plugin_helpers_1.getCachedDocumentNodeFromSchema)(schema)));
|
|
278
|
+
}
|
|
279
|
+
function addHashToSchema(schemaPromise) {
|
|
280
|
+
return schemaPromise.then(schema => {
|
|
281
|
+
// It's consumed later on. The general purpose is to use it for caching.
|
|
282
|
+
if (!schema.extensions) {
|
|
283
|
+
schema.extensions = {};
|
|
284
|
+
}
|
|
285
|
+
schema.extensions['hash'] = hashSchema(schema);
|
|
286
|
+
return schema;
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
function hashDocument(doc) {
|
|
290
|
+
if (doc.rawSDL) {
|
|
291
|
+
return hashContent(doc.rawSDL);
|
|
292
|
+
}
|
|
293
|
+
if (doc.document) {
|
|
294
|
+
return hashContent((0, graphql_1.print)(doc.document));
|
|
295
|
+
}
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
function addHashToDocumentFiles(documentFilesPromise) {
|
|
299
|
+
return documentFilesPromise.then(documentFiles => documentFiles.map(doc => {
|
|
300
|
+
doc.hash = hashDocument(doc);
|
|
301
|
+
return doc;
|
|
302
|
+
}));
|
|
303
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generate = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const hooks_js_1 = require("./hooks.js");
|
|
6
|
+
const codegen_js_1 = require("./codegen.js");
|
|
7
|
+
const watcher_js_1 = require("./utils/watcher.js");
|
|
8
|
+
const file_system_js_1 = require("./utils/file-system.js");
|
|
9
|
+
const mkdirp_1 = tslib_1.__importDefault(require("mkdirp"));
|
|
10
|
+
const path_1 = require("path");
|
|
11
|
+
const debugging_js_1 = require("./utils/debugging.js");
|
|
12
|
+
const config_js_1 = require("./config.js");
|
|
13
|
+
const crypto_1 = require("crypto");
|
|
14
|
+
const hash = (content) => (0, crypto_1.createHash)('sha1').update(content).digest('base64');
|
|
15
|
+
async function generate(input, saveToFile = true) {
|
|
16
|
+
const context = (0, config_js_1.ensureContext)(input);
|
|
17
|
+
const config = context.getConfig();
|
|
18
|
+
await context.profiler.run(() => (0, hooks_js_1.lifecycleHooks)(config.hooks).afterStart(), 'Lifecycle: afterStart');
|
|
19
|
+
let previouslyGeneratedFilenames = [];
|
|
20
|
+
function removeStaleFiles(config, generationResult) {
|
|
21
|
+
const filenames = generationResult.map(o => o.filename);
|
|
22
|
+
// find stale files from previous build which are not present in current build
|
|
23
|
+
const staleFilenames = previouslyGeneratedFilenames.filter(f => !filenames.includes(f));
|
|
24
|
+
staleFilenames.forEach(filename => {
|
|
25
|
+
if (shouldOverwrite(config, filename)) {
|
|
26
|
+
return (0, file_system_js_1.unlinkFile)(filename, err => {
|
|
27
|
+
const prettyFilename = filename.replace(`${input.cwd || process.cwd()}/`, '');
|
|
28
|
+
if (err) {
|
|
29
|
+
(0, debugging_js_1.debugLog)(`Cannot remove stale file: ${prettyFilename}\n${err}`);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
(0, debugging_js_1.debugLog)(`Removed stale file: ${prettyFilename}`);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
previouslyGeneratedFilenames = filenames;
|
|
38
|
+
}
|
|
39
|
+
const recentOutputHash = new Map();
|
|
40
|
+
async function writeOutput(generationResult) {
|
|
41
|
+
if (!saveToFile) {
|
|
42
|
+
return generationResult;
|
|
43
|
+
}
|
|
44
|
+
if (config.watch) {
|
|
45
|
+
removeStaleFiles(config, generationResult);
|
|
46
|
+
}
|
|
47
|
+
await context.profiler.run(async () => {
|
|
48
|
+
await (0, hooks_js_1.lifecycleHooks)(config.hooks).beforeAllFileWrite(generationResult.map(r => r.filename));
|
|
49
|
+
}, 'Lifecycle: beforeAllFileWrite');
|
|
50
|
+
await context.profiler.run(() => Promise.all(generationResult.map(async (result) => {
|
|
51
|
+
const exists = await (0, file_system_js_1.fileExists)(result.filename);
|
|
52
|
+
if (!shouldOverwrite(config, result.filename) && exists) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const content = result.content || '';
|
|
56
|
+
const currentHash = hash(content);
|
|
57
|
+
let previousHash = recentOutputHash.get(result.filename);
|
|
58
|
+
if (!previousHash && exists) {
|
|
59
|
+
previousHash = hash(await (0, file_system_js_1.readFile)(result.filename));
|
|
60
|
+
}
|
|
61
|
+
if (previousHash && currentHash === previousHash) {
|
|
62
|
+
(0, debugging_js_1.debugLog)(`Skipping file (${result.filename}) writing due to indentical hash...`);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (content.length === 0) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
recentOutputHash.set(result.filename, currentHash);
|
|
69
|
+
const basedir = (0, path_1.dirname)(result.filename);
|
|
70
|
+
await (0, hooks_js_1.lifecycleHooks)(result.hooks).beforeOneFileWrite(result.filename);
|
|
71
|
+
await (0, hooks_js_1.lifecycleHooks)(config.hooks).beforeOneFileWrite(result.filename);
|
|
72
|
+
await (0, mkdirp_1.default)(basedir);
|
|
73
|
+
const absolutePath = (0, path_1.isAbsolute)(result.filename)
|
|
74
|
+
? result.filename
|
|
75
|
+
: (0, path_1.join)(input.cwd || process.cwd(), result.filename);
|
|
76
|
+
await (0, file_system_js_1.writeFile)(absolutePath, result.content);
|
|
77
|
+
await (0, hooks_js_1.lifecycleHooks)(result.hooks).afterOneFileWrite(result.filename);
|
|
78
|
+
await (0, hooks_js_1.lifecycleHooks)(config.hooks).afterOneFileWrite(result.filename);
|
|
79
|
+
})), 'Write files');
|
|
80
|
+
await context.profiler.run(() => (0, hooks_js_1.lifecycleHooks)(config.hooks).afterAllFileWrite(generationResult.map(r => r.filename)), 'Lifecycle: afterAllFileWrite');
|
|
81
|
+
return generationResult;
|
|
82
|
+
}
|
|
83
|
+
// watch mode
|
|
84
|
+
if (config.watch) {
|
|
85
|
+
return (0, watcher_js_1.createWatcher)(context, writeOutput);
|
|
86
|
+
}
|
|
87
|
+
const outputFiles = await context.profiler.run(() => (0, codegen_js_1.executeCodegen)(context), 'executeCodegen');
|
|
88
|
+
await context.profiler.run(() => writeOutput(outputFiles), 'writeOutput');
|
|
89
|
+
await context.profiler.run(() => (0, hooks_js_1.lifecycleHooks)(config.hooks).beforeDone(), 'Lifecycle: beforeDone');
|
|
90
|
+
if (context.profilerOutput) {
|
|
91
|
+
await (0, file_system_js_1.writeFile)((0, path_1.join)(context.cwd, context.profilerOutput), JSON.stringify(context.profiler.collect()));
|
|
92
|
+
}
|
|
93
|
+
return outputFiles;
|
|
94
|
+
}
|
|
95
|
+
exports.generate = generate;
|
|
96
|
+
function shouldOverwrite(config, outputPath) {
|
|
97
|
+
const globalValue = config.overwrite === undefined ? true : !!config.overwrite;
|
|
98
|
+
const outputConfig = config.generates[outputPath];
|
|
99
|
+
if (!outputConfig) {
|
|
100
|
+
(0, debugging_js_1.debugLog)(`Couldn't find a config of ${outputPath}`);
|
|
101
|
+
return globalValue;
|
|
102
|
+
}
|
|
103
|
+
if (isConfiguredOutput(outputConfig) && typeof outputConfig.overwrite === 'boolean') {
|
|
104
|
+
return outputConfig.overwrite;
|
|
105
|
+
}
|
|
106
|
+
return globalValue;
|
|
107
|
+
}
|
|
108
|
+
function isConfiguredOutput(output) {
|
|
109
|
+
return typeof output.plugins !== 'undefined';
|
|
110
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.findAndLoadGraphQLConfig = exports.CodegenExtension = void 0;
|
|
4
|
+
const graphql_config_1 = require("graphql-config");
|
|
5
|
+
const apollo_engine_loader_1 = require("@graphql-tools/apollo-engine-loader");
|
|
6
|
+
const code_file_loader_1 = require("@graphql-tools/code-file-loader");
|
|
7
|
+
const git_loader_1 = require("@graphql-tools/git-loader");
|
|
8
|
+
const github_loader_1 = require("@graphql-tools/github-loader");
|
|
9
|
+
const prisma_loader_1 = require("@graphql-tools/prisma-loader");
|
|
10
|
+
const CodegenExtension = (api) => {
|
|
11
|
+
// Schema
|
|
12
|
+
api.loaders.schema.register(new code_file_loader_1.CodeFileLoader({
|
|
13
|
+
pluckConfig: {
|
|
14
|
+
skipIndent: true,
|
|
15
|
+
},
|
|
16
|
+
}));
|
|
17
|
+
api.loaders.schema.register(new git_loader_1.GitLoader());
|
|
18
|
+
api.loaders.schema.register(new github_loader_1.GithubLoader());
|
|
19
|
+
api.loaders.schema.register(new apollo_engine_loader_1.ApolloEngineLoader());
|
|
20
|
+
api.loaders.schema.register(new prisma_loader_1.PrismaLoader());
|
|
21
|
+
// Documents
|
|
22
|
+
api.loaders.documents.register(new code_file_loader_1.CodeFileLoader({
|
|
23
|
+
pluckConfig: {
|
|
24
|
+
skipIndent: true,
|
|
25
|
+
},
|
|
26
|
+
}));
|
|
27
|
+
api.loaders.documents.register(new git_loader_1.GitLoader());
|
|
28
|
+
api.loaders.documents.register(new github_loader_1.GithubLoader());
|
|
29
|
+
return {
|
|
30
|
+
name: 'codegen',
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
exports.CodegenExtension = CodegenExtension;
|
|
34
|
+
async function findAndLoadGraphQLConfig(filepath) {
|
|
35
|
+
const config = await (0, graphql_config_1.loadConfig)({
|
|
36
|
+
filepath,
|
|
37
|
+
rootDir: process.cwd(),
|
|
38
|
+
extensions: [exports.CodegenExtension],
|
|
39
|
+
throwOnEmpty: false,
|
|
40
|
+
throwOnMissing: false,
|
|
41
|
+
});
|
|
42
|
+
if (isGraphQLConfig(config)) {
|
|
43
|
+
return config;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
exports.findAndLoadGraphQLConfig = findAndLoadGraphQLConfig;
|
|
47
|
+
// Kamil: user might load a config that is not GraphQL Config
|
|
48
|
+
// so we need to check if it's a regular config or not
|
|
49
|
+
function isGraphQLConfig(config) {
|
|
50
|
+
if (!config) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
return config.getDefault().hasExtension('codegen');
|
|
55
|
+
}
|
|
56
|
+
catch (e) { }
|
|
57
|
+
try {
|
|
58
|
+
for (const projectName in config.projects) {
|
|
59
|
+
if (config.projects.hasOwnProperty(projectName)) {
|
|
60
|
+
const project = config.projects[projectName];
|
|
61
|
+
if (project.hasExtension('codegen')) {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch (e) { }
|
|
68
|
+
return false;
|
|
69
|
+
}
|
package/cjs/hooks.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.lifecycleHooks = void 0;
|
|
4
|
+
const debugging_js_1 = require("./utils/debugging.js");
|
|
5
|
+
const child_process_1 = require("child_process");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const DEFAULT_HOOKS = {
|
|
8
|
+
afterStart: [],
|
|
9
|
+
beforeDone: [],
|
|
10
|
+
onWatchTriggered: [],
|
|
11
|
+
onError: [],
|
|
12
|
+
afterOneFileWrite: [],
|
|
13
|
+
afterAllFileWrite: [],
|
|
14
|
+
beforeOneFileWrite: [],
|
|
15
|
+
beforeAllFileWrite: [],
|
|
16
|
+
};
|
|
17
|
+
function normalizeHooks(_hooks) {
|
|
18
|
+
const keys = Object.keys({
|
|
19
|
+
...DEFAULT_HOOKS,
|
|
20
|
+
..._hooks,
|
|
21
|
+
});
|
|
22
|
+
return keys.reduce((prev, hookName) => {
|
|
23
|
+
if (typeof _hooks[hookName] === 'string') {
|
|
24
|
+
return {
|
|
25
|
+
...prev,
|
|
26
|
+
[hookName]: [_hooks[hookName]],
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
if (typeof _hooks[hookName] === 'function') {
|
|
30
|
+
return {
|
|
31
|
+
...prev,
|
|
32
|
+
[hookName]: [_hooks[hookName]],
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
if (Array.isArray(_hooks[hookName])) {
|
|
36
|
+
return {
|
|
37
|
+
...prev,
|
|
38
|
+
[hookName]: _hooks[hookName],
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
return prev;
|
|
42
|
+
}, {});
|
|
43
|
+
}
|
|
44
|
+
function execShellCommand(cmd) {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
(0, child_process_1.exec)(cmd, {
|
|
47
|
+
env: {
|
|
48
|
+
...process.env,
|
|
49
|
+
PATH: `${process.env.PATH}${path_1.delimiter}${process.cwd()}${path_1.sep}node_modules${path_1.sep}.bin`,
|
|
50
|
+
},
|
|
51
|
+
}, (error, stdout, stderr) => {
|
|
52
|
+
if (error) {
|
|
53
|
+
reject(error);
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
resolve(stdout || stderr);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
async function executeHooks(hookName, scripts = [], args = []) {
|
|
62
|
+
(0, debugging_js_1.debugLog)(`Running lifecycle hook "${hookName}" scripts...`);
|
|
63
|
+
for (const script of scripts) {
|
|
64
|
+
if (typeof script === 'string') {
|
|
65
|
+
(0, debugging_js_1.debugLog)(`Running lifecycle hook "${hookName}" script: ${script} with args: ${args.join(' ')}...`);
|
|
66
|
+
await execShellCommand(`${script} ${args.join(' ')}`);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
(0, debugging_js_1.debugLog)(`Running lifecycle hook "${hookName}" script: ${script.name} with args: ${args.join(' ')}...`);
|
|
70
|
+
await script(...args);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const lifecycleHooks = (_hooks = {}) => {
|
|
75
|
+
const hooks = normalizeHooks(_hooks);
|
|
76
|
+
return {
|
|
77
|
+
afterStart: async () => executeHooks('afterStart', hooks.afterStart),
|
|
78
|
+
onWatchTriggered: async (event, path) => executeHooks('onWatchTriggered', hooks.onWatchTriggered, [event, path]),
|
|
79
|
+
onError: async (error) => executeHooks('onError', hooks.onError, [`"${error}"`]),
|
|
80
|
+
afterOneFileWrite: async (path) => executeHooks('afterOneFileWrite', hooks.afterOneFileWrite, [path]),
|
|
81
|
+
afterAllFileWrite: async (paths) => executeHooks('afterAllFileWrite', hooks.afterAllFileWrite, paths),
|
|
82
|
+
beforeOneFileWrite: async (path) => executeHooks('beforeOneFileWrite', hooks.beforeOneFileWrite, [path]),
|
|
83
|
+
beforeAllFileWrite: async (paths) => executeHooks('beforeAllFileWrite', hooks.beforeAllFileWrite, paths),
|
|
84
|
+
beforeDone: async () => executeHooks('beforeDone', hooks.beforeDone),
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
exports.lifecycleHooks = lifecycleHooks;
|
package/cjs/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generate = exports.executeCodegen = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
var codegen_js_1 = require("./codegen.js");
|
|
6
|
+
Object.defineProperty(exports, "executeCodegen", { enumerable: true, get: function () { return codegen_js_1.executeCodegen; } });
|
|
7
|
+
var generate_and_save_js_1 = require("./generate-and-save.js");
|
|
8
|
+
Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return generate_and_save_js_1.generate; } });
|
|
9
|
+
tslib_1.__exportStar(require("./config.js"), exports);
|
|
10
|
+
tslib_1.__exportStar(require("./init/index.js"), exports);
|
|
11
|
+
tslib_1.__exportStar(require("./utils/cli-error.js"), exports);
|
|
12
|
+
tslib_1.__exportStar(require("./cli.js"), exports);
|
|
13
|
+
tslib_1.__exportStar(require("./graphql-config.js"), exports);
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.italic = exports.grey = exports.bold = exports.writePackage = exports.writeConfig = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const chalk_1 = tslib_1.__importDefault(require("chalk"));
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const fs_1 = require("fs");
|
|
8
|
+
const detect_indent_1 = tslib_1.__importDefault(require("detect-indent"));
|
|
9
|
+
const latest_version_1 = tslib_1.__importDefault(require("latest-version"));
|
|
10
|
+
// Parses config and writes it to a file
|
|
11
|
+
async function writeConfig(answers, config) {
|
|
12
|
+
const YAML = await Promise.resolve().then(() => tslib_1.__importStar(require('json-to-pretty-yaml'))).then(m => ('default' in m ? m.default : m));
|
|
13
|
+
const ext = answers.config.toLocaleLowerCase().endsWith('.json') ? 'json' : 'yml';
|
|
14
|
+
const content = ext === 'json' ? JSON.stringify(config) : YAML.stringify(config);
|
|
15
|
+
const fullPath = (0, path_1.resolve)(process.cwd(), answers.config);
|
|
16
|
+
const relativePath = (0, path_1.relative)(process.cwd(), answers.config);
|
|
17
|
+
(0, fs_1.writeFileSync)(fullPath, content, {
|
|
18
|
+
encoding: 'utf-8',
|
|
19
|
+
});
|
|
20
|
+
return {
|
|
21
|
+
relativePath,
|
|
22
|
+
fullPath,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
exports.writeConfig = writeConfig;
|
|
26
|
+
// Updates package.json (script and plugins as dependencies)
|
|
27
|
+
async function writePackage(answers, configLocation) {
|
|
28
|
+
// script
|
|
29
|
+
const pkgPath = (0, path_1.resolve)(process.cwd(), 'package.json');
|
|
30
|
+
const pkgContent = (0, fs_1.readFileSync)(pkgPath, {
|
|
31
|
+
encoding: 'utf-8',
|
|
32
|
+
});
|
|
33
|
+
const pkg = JSON.parse(pkgContent);
|
|
34
|
+
const { indent } = (0, detect_indent_1.default)(pkgContent);
|
|
35
|
+
if (!pkg.scripts) {
|
|
36
|
+
pkg.scripts = {};
|
|
37
|
+
}
|
|
38
|
+
pkg.scripts[answers.script] = `graphql-codegen --config ${configLocation}`;
|
|
39
|
+
// plugin
|
|
40
|
+
if (!pkg.devDependencies) {
|
|
41
|
+
pkg.devDependencies = {};
|
|
42
|
+
}
|
|
43
|
+
await Promise.all(answers.plugins.map(async (plugin) => {
|
|
44
|
+
pkg.devDependencies[plugin.package] = await (0, latest_version_1.default)(plugin.package);
|
|
45
|
+
}));
|
|
46
|
+
if (answers.introspection) {
|
|
47
|
+
pkg.devDependencies['@graphql-codegen/introspection'] = await (0, latest_version_1.default)('@graphql-codegen/introspection');
|
|
48
|
+
}
|
|
49
|
+
pkg.devDependencies['@graphql-codegen/cli'] = await (0, latest_version_1.default)('@graphql-codegen/cli');
|
|
50
|
+
(0, fs_1.writeFileSync)(pkgPath, JSON.stringify(pkg, null, indent));
|
|
51
|
+
}
|
|
52
|
+
exports.writePackage = writePackage;
|
|
53
|
+
function bold(str) {
|
|
54
|
+
return chalk_1.default.bold(str);
|
|
55
|
+
}
|
|
56
|
+
exports.bold = bold;
|
|
57
|
+
function grey(str) {
|
|
58
|
+
return chalk_1.default.grey(str);
|
|
59
|
+
}
|
|
60
|
+
exports.grey = grey;
|
|
61
|
+
function italic(str) {
|
|
62
|
+
return chalk_1.default.italic(str);
|
|
63
|
+
}
|
|
64
|
+
exports.italic = italic;
|