-
-
Notifications
You must be signed in to change notification settings - Fork 801
/
index.ts
366 lines (317 loc) · 9.65 KB
/
index.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import { existsSync, promises as fsPromises, readFileSync } from 'fs';
import { createRequire } from 'module';
import { isAbsolute, resolve } from 'path';
import { cwd, env } from 'process';
import type { GlobbyOptions } from 'globby';
import globby from 'globby';
import { DocumentNode, GraphQLSchema, isSchema, parse } from 'graphql';
import unixify from 'unixify';
import {
gqlPluckFromCodeString,
gqlPluckFromCodeStringSync,
GraphQLTagPluckOptions,
} from '@graphql-tools/graphql-tag-pluck';
import {
asArray,
BaseLoaderOptions,
isDocumentNode,
isValidPath,
Loader,
parseGraphQLSDL,
Source,
} from '@graphql-tools/utils';
import { tryToLoadFromExport, tryToLoadFromExportSync } from './load-from-module.js';
const { readFile, access } = fsPromises;
export type CodeFileLoaderConfig = {
pluckConfig?: GraphQLTagPluckOptions;
noPluck?: boolean;
noRequire?: boolean;
/**
* Set to `true` to raise errors if any matched files are not valid GraphQL
*/
noSilentErrors?: boolean;
};
/**
* Additional options for loading from a code file
*/
export type CodeFileLoaderOptions = {
require?: string | string[];
} & CodeFileLoaderConfig &
BaseLoaderOptions;
const FILE_EXTENSIONS = [
'.ts',
'.mts',
'.cts',
'.tsx',
'.js',
'.mjs',
'cjs',
'.jsx',
'.vue',
'.svelte',
'.astro',
];
function createGlobbyOptions(options: CodeFileLoaderOptions): GlobbyOptions {
return { absolute: true, ...options, ignore: [] };
}
const buildIgnoreGlob = (path: string) => `!${path}`;
/**
* This loader loads GraphQL documents and type definitions from code files
* using `graphql-tag-pluck`.
*
* ```js
* const documents = await loadDocuments('queries/*.js', {
* loaders: [
* new CodeFileLoader()
* ]
* });
* ```
*
* Supported extensions include: `.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs`,
* `.cjs`, `.jsx`, `.vue`, `.svelte`, `.astro`
*/
export class CodeFileLoader implements Loader<CodeFileLoaderOptions> {
private config: CodeFileLoaderConfig;
constructor(config?: CodeFileLoaderConfig) {
this.config = config ?? {};
}
private getMergedOptions(options: CodeFileLoaderOptions): CodeFileLoaderOptions {
return {
...this.config,
...options,
pluckConfig: { ...(this.config.pluckConfig || {}), ...(options.pluckConfig || {}) },
};
}
async canLoad(pointer: string, options: CodeFileLoaderOptions): Promise<boolean> {
options = this.getMergedOptions(options);
if (isValidPath(pointer)) {
if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
const normalizedFilePath = isAbsolute(pointer)
? pointer
: resolve(options.cwd || cwd(), pointer);
try {
await access(normalizedFilePath);
return true;
} catch {
return false;
}
}
}
return false;
}
canLoadSync(pointer: string, options: CodeFileLoaderOptions): boolean {
options = this.getMergedOptions(options);
if (isValidPath(pointer)) {
if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
const normalizedFilePath = isAbsolute(pointer)
? pointer
: resolve(options.cwd || cwd(), pointer);
return existsSync(normalizedFilePath);
}
}
return false;
}
private _buildGlobs(glob: string, options: CodeFileLoaderOptions) {
const ignores = asArray(options.ignore || []);
const globs = [unixify(glob), ...ignores.map(v => buildIgnoreGlob(unixify(v)))];
return globs;
}
async resolveGlobs(glob: string, options: CodeFileLoaderOptions) {
options = this.getMergedOptions(options);
const globs = this._buildGlobs(glob, options);
return globby(globs, createGlobbyOptions(options));
}
resolveGlobsSync(glob: string, options: CodeFileLoaderOptions) {
options = this.getMergedOptions(options);
const globs = this._buildGlobs(glob, options);
return globby.sync(globs, createGlobbyOptions(options));
}
async load(pointer: string, options: CodeFileLoaderOptions): Promise<Source[]> {
options = this.getMergedOptions(options);
const resolvedPaths = await this.resolveGlobs(pointer, options);
const finalResult: Source[] = [];
const errors: Error[] = [];
await Promise.all(
resolvedPaths.map(async path => {
try {
const result = await this.handleSinglePath(path, options);
result?.forEach(result => finalResult.push(result));
} catch (e: any) {
if (env['DEBUG']) {
console.error(e);
}
errors.push(e);
}
}),
);
if (errors.length > 0 && (options.noSilentErrors || finalResult.length === 0)) {
if (errors.length === 1) {
throw errors[0];
}
throw new AggregateError(
errors,
`Reading from ${pointer} failed ; \n ` + errors.map((e: Error) => e.message).join('\n'),
);
}
return finalResult;
}
loadSync(pointer: string, options: CodeFileLoaderOptions): Source[] | null {
options = this.getMergedOptions(options);
const resolvedPaths = this.resolveGlobsSync(pointer, options);
const finalResult: Source[] = [];
const errors: Error[] = [];
for (const path of resolvedPaths) {
if (this.canLoadSync(path, options)) {
try {
const result = this.handleSinglePathSync(path, options);
result?.forEach(result => finalResult.push(result));
} catch (e: any) {
if (env['DEBUG']) {
console.error(e);
}
errors.push(e);
}
}
}
if (errors.length > 0 && (options.noSilentErrors || finalResult.length === 0)) {
if (errors.length === 1) {
throw errors[0];
}
throw new AggregateError(
errors,
`Reading from ${pointer} failed ; \n ` + errors.map((e: Error) => e.message).join('\n'),
);
}
return finalResult;
}
async handleSinglePath(location: string, options: CodeFileLoaderOptions): Promise<Source[]> {
if (!(await this.canLoad(location, options))) {
return [];
}
options = this.getMergedOptions(options);
const normalizedFilePath = ensureAbsolutePath(location, options);
const errors: Error[] = [];
if (!options.noPluck) {
try {
const content = await readFile(normalizedFilePath, { encoding: 'utf-8' });
const sources = await gqlPluckFromCodeString(
normalizedFilePath,
content,
options.pluckConfig,
);
if (sources.length) {
return sources.map(source => ({
rawSDL: source.body,
document: parse(source),
location,
}));
}
} catch (e: any) {
if (env['DEBUG']) {
console.error(
`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`,
);
}
errors.push(e);
}
}
if (!options.noRequire) {
try {
if (options && options.require) {
await Promise.all(asArray(options.require).map(m => import(m)));
}
const loaded = await tryToLoadFromExport(normalizedFilePath);
const sources = asArray(loaded)
.map(value => resolveSource(location, value, options))
.filter(Boolean);
if (sources.length) {
return sources as Source[];
}
} catch (e: any) {
errors.push(e);
}
}
if (errors.length > 0) {
throw errors[0];
}
return [];
}
handleSinglePathSync(location: string, options: CodeFileLoaderOptions): Source[] | null {
if (!this.canLoadSync(location, options)) {
return [];
}
options = this.getMergedOptions(options);
const normalizedFilePath = ensureAbsolutePath(location, options);
const errors: Error[] = [];
if (!options.noPluck) {
try {
const content = readFileSync(normalizedFilePath, { encoding: 'utf-8' });
const sources = gqlPluckFromCodeStringSync(
normalizedFilePath,
content,
options.pluckConfig,
);
if (sources.length) {
return sources.map(source => ({
rawSDL: source.body,
document: parse(source),
location,
}));
}
} catch (e: any) {
if (env['DEBUG']) {
console.error(
`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`,
);
}
errors.push(e);
}
}
if (!options.noRequire) {
try {
if (options && options.require) {
const cwdRequire = createRequire(options.cwd || cwd());
for (const m of asArray(options.require)) {
cwdRequire(m);
}
}
const loaded = tryToLoadFromExportSync(normalizedFilePath);
const sources = asArray(loaded)
.map(value => resolveSource(location, value, options))
.filter(Boolean);
if (sources.length) {
return sources as Source[];
}
} catch (e: any) {
errors.push(e);
}
}
if (errors.length > 0) {
throw errors[0];
}
return null;
}
}
function resolveSource(
pointer: string,
value: GraphQLSchema | DocumentNode | string | null,
options: CodeFileLoaderOptions,
): Source | null {
if (typeof value === 'string') {
return parseGraphQLSDL(pointer, value, options);
} else if (isSchema(value)) {
return {
location: pointer,
schema: value,
};
} else if (isDocumentNode(value)) {
return {
location: pointer,
document: value,
};
}
return null;
}
function ensureAbsolutePath(pointer: string, options: CodeFileLoaderOptions): string {
return isAbsolute(pointer) ? pointer : resolve(options.cwd || cwd(), pointer);
}