-
Notifications
You must be signed in to change notification settings - Fork 470
/
codegen.ts
309 lines (278 loc) · 11.5 KB
/
codegen.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import "apollo-env";
import { flags } from "@oclif/command";
import path from "path";
import { Kind, DocumentNode } from "graphql";
import { Gaze } from "gaze";
import URI from "vscode-uri";
import chalk from "chalk";
import { Debug } from "apollo-language-server";
import { TargetType, default as generate } from "../../generate";
import { ClientCommand, ProjectCommand } from "../../Command";
const waitForKey = async () => {
console.log("Press any key to stop.");
process.stdin.setRawMode!(true);
return new Promise<void>((resolve) =>
process.stdin.once("data", () => {
(process.stdin as any).unref();
process.stdin.setRawMode!(false);
resolve();
})
);
};
export default class Generate extends ClientCommand {
static aliases = ["codegen:generate"];
static description =
"[DEPRECATED] Generate static types for GraphQL queries. Can use the published schema in the Apollo registry or a downloaded schema.";
static flags = {
...ClientCommand.flags,
watch: flags.boolean({
description: "Watch for file changes and reload codegen",
}),
// general
target: flags.string({
description:
"Type of code generator to use (swift | typescript | flow | scala | json | json-modern (exposes raw json types))",
required: true,
}),
localSchemaFile: flags.string({
description:
"Path to one or more local GraphQL schema file(s), as introspection result or SDL. Supports comma-separated list of paths (ex. `--localSchemaFile=schema.graphql,extensions.graphql`)",
}),
addTypename: flags.boolean({
description:
"[default: true] Automatically add __typename to your queries, can be unset with --no-addTypename",
default: true,
allowNo: true,
}),
passthroughCustomScalars: flags.boolean({
description: "Use your own types for custom scalars",
}),
customScalarsPrefix: flags.string({
description:
"Include a prefix when using provided types for custom scalars",
}),
mergeInFieldsFromFragmentSpreads: flags.boolean({
description: "Merge fragment fields onto its enclosing type",
}),
// swift
namespace: flags.string({
description: "The namespace to emit generated code into.",
}),
omitDeprecatedEnumCases: flags.boolean({
description:
"Omit deprecated enum cases from generated code [Swift only]",
}),
operationIdsPath: flags.string({
description:
"Path to an operation id JSON map file. If specified, also stores the operation ids (hashes) as properties on operation types [currently Swift-only]",
}),
only: flags.string({
description:
"Parse all input files, but only output generated code for the specified file [Swift only]",
}),
suppressSwiftMultilineStringLiterals: flags.boolean({
description:
"Prevents operations from being rendered as multiline strings [Swift only]",
}),
// flow
useFlowExactObjects: flags.boolean({
description: "Use Flow exact objects for generated types [flow only]",
}),
useFlowReadOnlyTypes: flags.boolean({
description:
"Use read only types for generated types [flow only]. **Deprecated in favor of `useReadOnlyTypes`.**",
}),
// flow / TS
useReadOnlyTypes: flags.boolean({
description:
"Use read only types for generated types [flow | typescript]",
}),
outputFlat: flags.boolean({
description:
'By default, TypeScript/Flow will put each generated file in a directory next to its source file using the value of the "output" as the directory name. Set "outputFlat" to put all generated files in the directory relative to the current working directory defined by "output".',
}),
// typescript
globalTypesFile: flags.string({
description:
'By default, TypeScript will put a file named "globalTypes.ts" inside the "output" directory. Set "globalTypesFile" to specify a different path. Alternatively, set "tsFileExtension" to modify the extension of the file, for example "d.ts" will output "globalTypes.d.ts"',
}),
tsFileExtension: flags.string({
description:
'By default, TypeScript will output "ts" files. Set "tsFileExtension" to specify a different file extension, for example "d.ts"',
}),
suppressDeprecationWarning: flags.boolean({
description:
"Silence the deprecation warning output by the codegen command",
}),
};
static args = [
{
name: "output",
description: `Directory to which generated files will be written.
- For TypeScript/Flow generators, this specifies a directory relative to each source file by default.
- For TypeScript/Flow generators with the "outputFlat" flag is set, and for the Swift generator, this specifies a file or directory (absolute or relative to the current working directory) to which:
- a file will be written for each query (if "output" is a directory)
- all generated types will be written
- For all other types, this defines a file (absolute or relative to the current working directory) to which all generated types are written.`,
},
];
DEPRECATION_MSG =
"\n--------------------------------------------------------------------------------\n" +
"DEPRECATED: This command will be removed from the `apollo` CLI in \n" +
"its next major version. Replacement functionality is available via \n" +
"the `graphql-code-generator` project: https://www.graphql-code-generator.com/\n" +
"This message can be suppressed with the --suppressDeprecationWarning flag.\n" +
"--------------------------------------------------------------------------------\n";
protected printDeprecationWarning() {
console.error(this.DEPRECATION_MSG);
}
async run() {
const {
flags: { watch, suppressDeprecationWarning },
args: { output },
} = this.parse(Generate);
if (!suppressDeprecationWarning) {
this.printDeprecationWarning();
}
let write;
const run = () =>
this.runTasks(({ flags, args, project, config }) => {
let inferredTarget: TargetType = "" as TargetType;
if (
[
"json",
"json-modern",
"swift",
"typescript",
"flow",
"scala",
].includes(flags.target)
) {
inferredTarget = flags.target as TargetType;
} else {
throw new Error(`Unsupported target: ${flags.target}`);
}
if (
!args.output &&
inferredTarget != "typescript" &&
inferredTarget != "flow"
) {
throw new Error(
"The output path must be specified in the arguments for targets that aren't TypeScript or Flow"
);
}
if (
!flags.outputFlat &&
(inferredTarget === "typescript" || inferredTarget === "flow") &&
args.output &&
(path.isAbsolute(args.output) ||
args.output.split(path.sep).length > 1)
) {
throw new Error(
'For TypeScript and Flow generators, "output" must be empty or a single directory name, unless the "outputFlat" flag is set.'
);
}
return [
{
title: "Generating query files",
task: async (ctx, task) => {
task.title = `Generating query files with '${inferredTarget}' target`;
const schema = await project.resolveSchema({
tag: config.variant,
});
if (!schema) throw new Error("Error loading schema");
write = () => {
// make sure all of the doucuments that we are going to be using for codegen
// are valid documents
project.validate();
// to prevent silent erroring of syntax errors, we check the project's
// documents to make sure there are no errors. If there are, we error here
// instead of project initialization
for (const document of this.project.documents) {
if (document.syntaxErrors.length) {
const errors = document.syntaxErrors.map(
(e) =>
`Syntax error in ${document.source.name}: ${e.message}\n`
);
throw new Error(errors.toString());
}
}
const operations = Object.values(this.project.operations);
const fragments = Object.values(this.project.fragments);
if (!operations.length && !fragments.length) {
throw new Error(
"No operations or fragments found to generate code for."
);
}
const document: DocumentNode = {
kind: Kind.DOCUMENT,
definitions: [...operations, ...fragments],
};
return generate(
document,
schema,
typeof args.output === "string"
? args.output
: "__generated__",
flags.only,
inferredTarget,
flags.tagName as string,
!flags.outputFlat,
{
passthroughCustomScalars:
flags.passthroughCustomScalars ||
!!flags.customScalarsPrefix,
customScalarsPrefix: flags.customScalarsPrefix || "",
addTypename: flags.addTypename,
namespace: flags.namespace,
operationIdsPath: flags.operationIdsPath,
generateOperationIds: !!flags.operationIdsPath,
mergeInFieldsFromFragmentSpreads:
flags.mergeInFieldsFromFragmentSpreads,
useFlowExactObjects: flags.useFlowExactObjects,
useReadOnlyTypes:
flags.useReadOnlyTypes || flags.useFlowReadOnlyTypes,
globalTypesFile: flags.globalTypesFile,
tsFileExtension: flags.tsFileExtension,
suppressSwiftMultilineStringLiterals:
flags.suppressSwiftMultilineStringLiterals,
omitDeprecatedEnumCases: flags.omitDeprecatedEnumCases,
exposeTypeNodes: inferredTarget === "json-modern",
}
);
};
const writtenFiles = write();
task.title = `Generating query files with '${inferredTarget}' target - wrote ${writtenFiles} files`;
},
},
];
});
if (watch) {
await run().catch(() => {});
const watcher = new Gaze(this.project.config.client.includes);
// FIXME: support excludes with the glob
watcher.on("all", (event, file) => {
// don't trigger write events for generated file changes
if (file.indexOf("__generated__") > -1) return;
// don't trigger write events on single output file
if (file.indexOf(output) > -1) return;
this.project.fileDidChange(URI.file(file).toString());
console.log("\nChange detected, generating types...");
try {
const fileCount = write();
console.log(`${chalk.green("✔")} Wrote ${fileCount} files`);
} catch (e) {
Debug.error("Error while generating types: " + e.message);
}
});
if (process.stdin.isTTY) {
await waitForKey();
watcher.close();
process.exit(0);
}
return;
} else {
return run();
}
}
}