forked from danielwaltz/vite-plugin-graphql-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
299 lines (266 loc) · 7.47 KB
/
index.ts
File metadata and controls
299 lines (266 loc) · 7.47 KB
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
import process from "node:process";
import {
CodegenContext,
generate,
loadContext,
type CodegenConfig,
} from "@graphql-codegen/cli";
import { debugLog } from "./utils/debugLog";
import { isCodegenConfig, isGeneratedFile } from "./utils/fileMatchers";
import { createMatchCache } from "./utils/matchCache";
import { isBuildMode, isServeMode, type ViteMode } from "./utils/viteModes";
import type { Plugin } from "vite";
export interface SkipContext {
trigger: "start" | "build" | "watch";
filePath?: string;
}
export type SkipFn = (context: SkipContext) => boolean | Promise<boolean>;
export interface Options {
/**
* Run codegen on server start.
*
* @default true
*/
runOnStart?: boolean;
/**
* Run codegen on build. Will prevent build if codegen fails.
*
* @default true
*/
runOnBuild?: boolean;
/**
* Enable codegen integration with vite file watcher.
*
* @default true
*/
enableWatcher?: boolean;
/**
* Automatically add schemas and documents referenced in the codegen config
* to the Vite file watcher.
*
* @default true
*/
watchCodegenConfigFiles?: boolean;
/**
* Throw an error if codegen fails on server start.
*
* @default false
*/
throwOnStart?: boolean;
/**
* Throw an error if codegen fails on build.
*
* @default true
*/
throwOnBuild?: boolean;
/**
* Run codegen when a document matches.
*
* @default true
*/
matchOnDocuments?: boolean;
/**
* Run codegen when a schema matches.
*
* @default false
*/
matchOnSchemas?: boolean;
/**
* Name of a project in a multi-project config file.
*/
project?: string;
/**
* Manually define the codegen config.
*/
config?: CodegenConfig;
/**
* Override parts of the codegen config just for this plugin.
*/
configOverride?: Partial<CodegenConfig>;
/**
* Override parts of the codegen config just for this plugin on server start.
*/
configOverrideOnStart?: Partial<CodegenConfig>;
/**
* Override parts of the codegen config just for this plugin on build.
*/
configOverrideOnBuild?: Partial<CodegenConfig>;
/**
* Override parts of the codegen config just for this plugin in the watcher.
*/
configOverrideWatcher?: Partial<CodegenConfig>;
/**
* Override the codegen config file path.
*/
configFilePathOverride?: string;
/**
* Skip codegen for a given cycle.
*
* @default false
*/
skip?: boolean | SkipFn;
/**
* Log various steps to aid in tracking down bugs.
*
* @default false
*/
debug?: boolean;
}
export function GraphQLCodegen(options?: Options): Plugin {
let codegenContext: CodegenContext;
let viteMode: ViteMode;
const {
runOnStart = true,
runOnBuild = true,
enableWatcher = true,
watchCodegenConfigFiles = true,
throwOnStart = false,
throwOnBuild = true,
matchOnDocuments = true,
matchOnSchemas = false,
project = null,
config = null,
configOverride = {},
configOverrideOnStart = {},
configOverrideOnBuild = {},
configOverrideWatcher = {},
configFilePathOverride,
skip = false,
debug = false,
} = options ?? {};
const log = (...args: unknown[]) => {
if (!debug) return;
debugLog(...args);
};
const shouldSkipGeneration = async (context: SkipContext) =>
typeof skip === "function" ? await skip(context) : skip;
const generateWithOverride = async (
overrideConfig: Partial<CodegenConfig>,
skipContext: SkipContext,
) => {
if (await shouldSkipGeneration(skipContext)) {
log("Generation skipped", skipContext);
return;
}
const currentConfig = codegenContext.getConfig();
await generate({
...currentConfig,
...configOverride,
...overrideConfig,
// Vite handles file watching
watch: false,
});
log(`Generation successful on ${skipContext.trigger}`);
};
if (options) log("Plugin initialized with options:", options);
return {
name: "graphql-codegen",
async config(_userConfig, env) {
try {
if (config) {
log("Manual config passed, creating codegen context");
codegenContext = new CodegenContext({ config });
} else {
const cwd = process.cwd();
log("Loading codegen context:", configFilePathOverride ?? cwd);
codegenContext = await loadContext(configFilePathOverride);
}
if (project != null) codegenContext.useProject(project);
log("Loading codegen context successful");
} catch (error) {
log("Loading codegen context failed");
throw error;
}
viteMode = env.command;
},
async buildStart() {
if (isServeMode(viteMode)) {
if (!runOnStart) return;
try {
await generateWithOverride(configOverrideOnStart, {
trigger: "start",
});
} catch (error) {
// GraphQL Codegen handles logging useful errors
log("Generation failed on start");
if (throwOnStart) throw error;
}
}
if (isBuildMode(viteMode)) {
if (!runOnBuild) return;
try {
await generateWithOverride(configOverrideOnBuild, {
trigger: "build",
});
} catch (error) {
// GraphQL Codegen handles logging useful errors
log("Generation failed on build");
if (throwOnBuild) throw error;
}
}
},
configureServer(server) {
if (!enableWatcher) return;
const matchCache = createMatchCache(codegenContext, {
matchOnDocuments,
matchOnSchemas,
});
async function checkFile(filePath: string) {
log(`Checking file: ${filePath}`);
if (matchCache.has(filePath)) {
log("File is in match cache");
try {
await generateWithOverride(configOverrideWatcher, {
trigger: "watch",
filePath,
});
} catch {
// GraphQL Codegen handles logging useful errors
log("Generation failed in file watcher");
}
return;
}
if (isCodegenConfig(filePath, codegenContext)) {
log("Codegen config file matched, restarting vite");
server.restart();
return;
}
log("File did not match");
}
async function initializeWatcher() {
try {
log("Match cache initialing");
await matchCache.init();
if (watchCodegenConfigFiles) {
log("Adding codegen config files to watcher", matchCache.entries());
server.watcher.add(matchCache.entries());
}
log("Match cache initialized");
} catch (error) {
log("Match cache initialization failed", error);
}
server.watcher.on("add", async (filePath) => {
log(`File added: ${filePath}`);
if (isGeneratedFile(filePath, codegenContext)) {
log("File is a generated output file, skipping");
return;
}
try {
log("Match cache refreshing");
await matchCache.refresh();
log("Match cache refreshed");
} catch (error) {
log("Match cache refresh failed", error);
}
await checkFile(filePath);
});
server.watcher.on("change", async (filePath) => {
log(`File changed: ${filePath}`);
await checkFile(filePath);
});
}
initializeWatcher();
},
} as const satisfies Plugin;
}
export default GraphQLCodegen;