-
Notifications
You must be signed in to change notification settings - Fork 348
/
process.ts
709 lines (675 loc) · 22.6 KB
/
process.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
import { camelCase } from 'camel-case';
import { DocumentNode, parse, print, visit } from 'graphql';
import { pascalCase } from 'pascal-case';
import { useMaskedErrors } from '@envelop/core';
import { path as pathModule, process } from '@graphql-mesh/cross-helpers';
import type { GetMeshOptions, MeshResolvedSource } from '@graphql-mesh/runtime';
import { FsStoreStorageAdapter, InMemoryStoreStorageAdapter, MeshStore } from '@graphql-mesh/store';
import {
ImportFn,
MeshHandlerLibrary,
MeshMergerLibrary,
MeshPlugin,
MeshPluginFactory,
MeshTransformLibrary,
YamlConfig,
} from '@graphql-mesh/types';
import {
defaultImportFn,
parseWithCache,
printWithCache,
resolveAdditionalResolvers,
} from '@graphql-mesh/utils';
import { usePersistedOperations } from '@graphql-yoga/plugin-persisted-operations';
import { getAdditionalResolversFromTypeDefs } from './getAdditionalResolversFromTypeDefs.js';
import {
getPackage,
hashSHA256,
resolveAdditionalTypeDefs,
resolveCache,
resolveCustomFetch,
resolveDocuments,
resolveLogger,
resolvePubSub,
Source,
} from './utils.js';
const ENVELOP_CORE_PLUGINS_MAP: Record<
string,
{
moduleName: string;
importName: string;
pluginFactory(...args: any[]): MeshPlugin<any>;
}
> = {
maskedErrors: {
moduleName: '@envelop/core',
importName: 'useMaskedErrors',
pluginFactory: useMaskedErrors,
},
};
export type ConfigProcessOptions = {
dir?: string;
importFn?: ImportFn;
store?: MeshStore;
ignoreAdditionalResolvers?: boolean;
configName?: string;
artifactsDir?: string;
additionalPackagePrefixes?: string[];
generateCode?: boolean;
initialLoggerPrefix?: string;
throwOnInvalidConfig?: boolean;
};
export type ProcessedConfig = GetMeshOptions & {
config: YamlConfig.Config;
documents: Source[];
store: MeshStore;
importCodes: Set<string>;
codes: Set<string>;
};
function getDefaultMeshStore(dir: string, importFn: ImportFn, artifactsDir: string) {
const isProd = process.env.NODE_ENV?.toLowerCase() === 'production';
const storeStorageAdapter = isProd
? new FsStoreStorageAdapter({
cwd: dir,
importFn,
fileType: 'ts',
})
: new InMemoryStoreStorageAdapter();
return new MeshStore(pathModule.resolve(dir, artifactsDir), storeStorageAdapter, {
/**
* TODO:
* `mesh start` => { readonly: true, validate: false }
* `mesh dev` => { readonly: false, validate: true } => validation error should show a prompt for confirmation
* `mesh validate` => { readonly: true, validate: true } => should fetch from remote and try to update
* readonly
*/
readonly: isProd,
validate: false,
});
}
export async function processConfig(
config: YamlConfig.Config,
options?: ConfigProcessOptions,
): Promise<ProcessedConfig> {
if (config.skipSSLValidation) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
const importCodes = new Set([
`import type { GetMeshOptions } from '@graphql-mesh/runtime';`,
`import type { YamlConfig } from '@graphql-mesh/types';`,
]);
const codes = new Set([
`export const rawServeConfig: YamlConfig.Config['serve'] = ${JSON.stringify(
config.serve,
)} as any`,
`export async function getMeshOptions(): Promise<GetMeshOptions> {`,
]);
const {
dir,
importFn = defaultImportFn,
store: providedStore,
artifactsDir,
additionalPackagePrefixes = [],
} = options || {};
if (config.require) {
await Promise.all(config.require.map(mod => importFn(mod)));
for (const mod of config.require) {
importCodes.add(`import '${mod}';`);
}
}
const rootStore = providedStore || getDefaultMeshStore(dir, importFn, artifactsDir || '.mesh');
const {
pubsub,
importCode: pubsubImportCode,
code: pubsubCode,
} = await resolvePubSub(config.pubsub, importFn, dir, additionalPackagePrefixes);
importCodes.add(pubsubImportCode);
codes.add(pubsubCode);
const sourcesStore = rootStore.child('sources');
codes.add(`const sourcesStore = rootStore.child('sources');`);
const {
logger,
importCode: loggerImportCode,
code: loggerCode,
} = await resolveLogger(
config.logger,
importFn,
dir,
additionalPackagePrefixes,
options?.initialLoggerPrefix,
);
importCodes.add(loggerImportCode);
codes.add(loggerCode);
const {
cache,
importCode: cacheImportCode,
code: cacheCode,
} = await resolveCache(
config.cache,
importFn,
rootStore,
dir,
pubsub,
logger,
additionalPackagePrefixes,
);
importCodes.add(cacheImportCode);
codes.add(cacheCode);
const {
fetchFn,
importCode: fetchFnImportCode,
code: fetchFnCode,
} = await resolveCustomFetch({
fetchConfig: config.customFetch,
cache,
importFn,
cwd: dir,
additionalPackagePrefixes,
});
importCodes.add(fetchFnImportCode);
codes.add(fetchFnCode);
importCodes.add(`import { MeshResolvedSource } from '@graphql-mesh/runtime';`);
codes.add(`const sources: MeshResolvedSource[] = [];`);
importCodes.add(`import { MeshTransform, MeshPlugin } from '@graphql-mesh/types';`);
codes.add(`const transforms: MeshTransform[] = [];`);
codes.add(`const additionalEnvelopPlugins: MeshPlugin<any>[] = [];`);
const [
sources,
transforms,
additionalEnvelopPlugins,
additionalTypeDefs,
additionalResolvers,
documents,
] = await Promise.all([
Promise.all(
config.sources.map<Promise<MeshResolvedSource>>(async (source, sourceIndex) => {
const handlerName = Object.keys(source.handler)[0].toString();
const handlerConfig = source.handler[handlerName];
const handlerVariableName = camelCase(`${source.name}_Handler`);
const transformsVariableName = camelCase(`${source.name}_Transforms`);
codes.add(`const ${transformsVariableName} = [];`);
const [handler, transforms] = await Promise.all([
await getPackage<MeshHandlerLibrary>({
name: handlerName,
type: 'handler',
importFn,
cwd: dir,
additionalPrefixes: additionalPackagePrefixes,
}).then(({ resolved: HandlerCtor, moduleName }) => {
if (options.generateCode) {
const handlerImportName = pascalCase(handlerName + '_Handler');
importCodes.add(`import ${handlerImportName} from ${JSON.stringify(moduleName)}`);
codes.add(`const ${handlerVariableName} = new ${handlerImportName}({
name: ${JSON.stringify(source.name)},
config: ${JSON.stringify(handlerConfig)},
baseDir,
cache,
pubsub,
store: sourcesStore.child(${JSON.stringify(source.name)}),
logger: logger.child(${JSON.stringify(source.name)}),
importFn,
});`);
}
return new HandlerCtor({
name: source.name,
config: handlerConfig,
baseDir: dir,
cache,
pubsub,
store: sourcesStore.child(source.name),
logger: logger.child(source.name),
importFn,
});
}),
Promise.all(
(source.transforms || []).map(async (t, transformIndex) => {
const transformName = Object.keys(t)[0].toString();
const transformConfig = t[transformName];
const { resolved: TransformCtor, moduleName } =
await getPackage<MeshTransformLibrary>({
name: transformName,
type: 'transform',
importFn,
cwd: dir,
additionalPrefixes: additionalPackagePrefixes,
});
if (options.generateCode) {
const transformImportName = pascalCase(transformName + '_Transform');
importCodes.add(
`import ${transformImportName} from ${JSON.stringify(moduleName)};`,
);
codes.add(`${transformsVariableName}[${transformIndex}] = new ${transformImportName}({
apiName: ${JSON.stringify(source.name)},
config: ${JSON.stringify(transformConfig)},
baseDir,
cache,
pubsub,
importFn,
logger,
});`);
}
return new TransformCtor({
apiName: source.name,
config: transformConfig,
baseDir: dir,
cache,
pubsub,
importFn,
logger,
});
}),
),
]);
if (options.generateCode) {
codes.add(`sources[${sourceIndex}] = {
name: '${source.name}',
handler: ${handlerVariableName},
transforms: ${transformsVariableName}
}`);
}
return {
name: source.name,
handler,
transforms,
};
}),
),
Promise.all(
config.transforms?.map(async (t, transformIndex) => {
const transformName = Object.keys(t)[0].toString();
const transformConfig = t[transformName];
const { resolved: TransformLibrary, moduleName } = await getPackage<MeshTransformLibrary>({
name: transformName,
type: 'transform',
importFn,
cwd: dir,
additionalPrefixes: additionalPackagePrefixes,
});
if (options.generateCode) {
const transformImportName = pascalCase(transformName + '_Transform');
importCodes.add(`import ${transformImportName} from ${JSON.stringify(moduleName)};`);
codes.add(`transforms[${transformIndex}] = new (${transformImportName} as any)({
apiName: '',
config: ${JSON.stringify(transformConfig)},
baseDir,
cache,
pubsub,
importFn,
logger,
})`);
}
return new TransformLibrary({
apiName: '',
config: transformConfig,
baseDir: dir,
cache,
pubsub,
importFn,
logger,
});
}) || [],
),
Promise.all(
config.plugins?.map(async (p, pluginIndex) => {
const [pluginName, maybeImportName] = Object.keys(p)[0].toString().split('#');
const pluginConfig: any = p[pluginName];
if (ENVELOP_CORE_PLUGINS_MAP[pluginName] != null) {
const { importName, moduleName, pluginFactory } = ENVELOP_CORE_PLUGINS_MAP[pluginName];
if (options.generateCode) {
importCodes.add(`import { ${importName} } from ${JSON.stringify(moduleName)};`);
codes.add(
`additionalEnvelopPlugins[${pluginIndex}] = await ${importName}(${JSON.stringify(
pluginConfig,
null,
2,
)});`,
);
}
return pluginFactory(pluginConfig);
}
const { resolved: possiblePluginFactory, moduleName } = await getPackage<any>({
name: pluginName,
type: 'plugin',
importFn,
cwd: dir,
additionalPrefixes: [
...additionalPackagePrefixes,
'@envelop/',
'@graphql-yoga/plugin-',
'@escape.tech/graphql-armor-',
],
});
let pluginFactory: MeshPluginFactory<YamlConfig.Plugin[keyof YamlConfig.Plugin]>;
if (typeof possiblePluginFactory === 'function') {
pluginFactory = possiblePluginFactory;
if (options.generateCode) {
const importName = pascalCase('use_' + pluginName);
importCodes.add(`import ${importName} from ${JSON.stringify(moduleName)};`);
codes.add(`additionalEnvelopPlugins[${pluginIndex}] = await ${importName}({
...(${JSON.stringify(pluginConfig, null, 2)}),
logger: logger.child(${JSON.stringify(pluginName)}),
cache,
pubsub,
baseDir,
importFn,
})`);
}
} else {
const importName =
maybeImportName ||
Object.keys(possiblePluginFactory)
.find(
iName =>
(iName.toString().startsWith('use') || iName.toString().endsWith('Plugin')) &&
typeof possiblePluginFactory[iName] === 'function',
)
.toString();
if (importName) {
pluginFactory = possiblePluginFactory[importName];
if (options.generateCode) {
importCodes.add(`import { ${importName} } from ${JSON.stringify(moduleName)};`);
codes.add(
`additionalEnvelopPlugins[${pluginIndex}] = await ${importName}({
...(${JSON.stringify(pluginConfig, null, 2)}),
logger: logger.child(${JSON.stringify(pluginName)}),
cache,
pubsub,
baseDir,
importFn,
});`,
);
}
}
}
return pluginFactory({
...pluginConfig,
logger: logger.child(pluginName),
cache,
pubsub,
baseDir: dir,
importFn,
});
}) || [],
),
resolveAdditionalTypeDefs(dir, config.additionalTypeDefs).then(additionalTypeDefs => {
if (options.generateCode) {
codes.add(
`const additionalTypeDefs = [${(additionalTypeDefs || []).map(
parsedTypeDefs => `parse(${JSON.stringify(print(parsedTypeDefs))}),`,
)}] as any[];`,
);
if (additionalTypeDefs?.length) {
importCodes.add(`import { parse } from 'graphql';`);
}
}
return additionalTypeDefs;
}),
options?.ignoreAdditionalResolvers
? []
: resolveAdditionalResolvers(dir, config.additionalResolvers, importFn, pubsub),
resolveDocuments(config.documents, dir),
]);
if (options.generateCode) {
if (config.additionalResolvers?.length) {
codes.add(`const additionalResolvers = await Promise.all([
${config.additionalResolvers
.map(additionalResolverDefinition => {
if (typeof additionalResolverDefinition === 'string') {
return `import(${JSON.stringify(
pathModule.join('..', additionalResolverDefinition).split('\\').join('/'),
)})
.then(m => m.resolvers || m.default || m)`;
} else {
importCodes.add(
`import { resolveAdditionalResolversWithoutImport } from '@graphql-mesh/utils';`,
);
return `resolveAdditionalResolversWithoutImport(
${JSON.stringify(additionalResolverDefinition, null, 2)}
)`;
}
})
.join(',\n')}
]);`);
} else {
codes.add(`const additionalResolvers = [] as any[]`);
}
}
if (additionalTypeDefs?.length) {
const additionalResolversConfigFromTypeDefs =
getAdditionalResolversFromTypeDefs(additionalTypeDefs);
if (additionalResolversConfigFromTypeDefs?.length) {
const resolveToDirectiveDefinition = /* GraphQL */ `
scalar ResolveToSourceArgs
directive @resolveTo(
requiredSelectionSet: String
sourceName: String!
sourceTypeName: String!
sourceFieldName: String!
sourceSelectionSet: String
sourceArgs: ResolveToSourceArgs
keyField: String
keysArg: String
pubsubTopic: String
filterBy: String
additionalArgs: ResolveToSourceArgs
result: String
resultType: String
) on FIELD_DEFINITION
`;
const resolvedAdditionalResolvers = await resolveAdditionalResolvers(
dir,
additionalResolversConfigFromTypeDefs,
importFn,
pubsub,
);
additionalTypeDefs.unshift(parse(resolveToDirectiveDefinition));
additionalResolvers.push(...resolvedAdditionalResolvers);
if (options.generateCode && resolvedAdditionalResolvers.length) {
importCodes.add(`import { resolveAdditionalResolvers } from '@graphql-mesh/utils';`);
codes.add(
`additionalTypeDefs.unshift(parse(/* GraphQL */\`${resolveToDirectiveDefinition}\`))`,
);
codes.add(`const additionalResolversFromTypeDefs = await resolveAdditionalResolvers(
baseDir,
${JSON.stringify(additionalResolversConfigFromTypeDefs)},
importFn,
pubsub
);`);
codes.add(`additionalResolvers.push(...additionalResolversFromTypeDefs)`);
}
}
}
let mergerName = config.merger;
// Decide what is the default merger
if (!mergerName) {
if (config.sources.length > 1) {
mergerName = 'stitching';
} else {
// eslint-disable-next-line no-labels
resolversLoop: for (const resolversObj of additionalResolvers || []) {
for (const typeName in resolversObj || {}) {
const fieldResolvers = resolversObj[typeName];
if (typeof fieldResolvers === 'object') {
for (const fieldName in fieldResolvers) {
const fieldResolveObj = fieldResolvers[fieldName];
if (typeof fieldResolveObj === 'object') {
// selectionSet needs stitching merger even if there is a single source
if (fieldResolveObj.selectionSet != null) {
mergerName = 'stitching';
// eslint-disable-next-line no-labels
break resolversLoop;
}
}
}
}
}
}
if (!mergerName) {
mergerName = 'bare';
}
}
}
const { resolved: Merger, moduleName: mergerModuleName } = await getPackage<MeshMergerLibrary>({
name: mergerName,
type: 'merger',
importFn,
cwd: dir,
additionalPrefixes: additionalPackagePrefixes,
});
if (options.generateCode) {
const mergerImportName = pascalCase(`${mergerName}Merger`);
importCodes.add(`import ${mergerImportName} from ${JSON.stringify(mergerModuleName)};`);
codes.add(`const merger = new(${mergerImportName} as any)({
cache,
pubsub,
logger: logger.child('${mergerName}Merger'),
store: rootStore.child('${mergerName}Merger')
})`);
}
const merger = new Merger({
cache,
pubsub,
logger: logger.child(`${mergerName}Merger`),
store: rootStore.child(`${mergerName}Merger`),
});
if (config.additionalEnvelopPlugins) {
codes.add(
`const importedAdditionalEnvelopPlugins = await import(${JSON.stringify(
pathModule.join('..', config.additionalEnvelopPlugins).split('\\').join('/'),
)}).then(m => m.default || m);`,
);
const importedAdditionalEnvelopPlugins = await importFn(
pathModule.isAbsolute(config.additionalEnvelopPlugins)
? config.additionalEnvelopPlugins
: pathModule.join(dir, config.additionalEnvelopPlugins),
);
if (typeof importedAdditionalEnvelopPlugins === 'function') {
const factoryResult = await importedAdditionalEnvelopPlugins(config);
if (Array.isArray(factoryResult)) {
if (options.generateCode) {
codes.add(
`additionalEnvelopPlugins.push(...(await importedAdditionalEnvelopPlugins()));`,
);
}
additionalEnvelopPlugins.push(...factoryResult);
} else {
if (options.generateCode) {
codes.add(`additionalEnvelopPlugins.push(await importedAdditionalEnvelopPlugins());`);
}
additionalEnvelopPlugins.push(factoryResult);
}
} else {
if (Array.isArray(importedAdditionalEnvelopPlugins)) {
if (options.generateCode) {
codes.add(`additionalEnvelopPlugins.push(...importedAdditionalEnvelopPlugins)`);
}
additionalEnvelopPlugins.push(...importedAdditionalEnvelopPlugins);
} else {
if (options.generateCode) {
codes.add(`additionalEnvelopPlugins.push(importedAdditionalEnvelopPlugins)`);
}
additionalEnvelopPlugins.push(importedAdditionalEnvelopPlugins);
}
}
}
const documentVariableNames: string[] = [];
const documentVariableHashCodeMap = new Map<string, string>();
if (documents?.length) {
const documentHashMap = new Map<string, DocumentNode | string>();
const documentHashMapCodes = new Set<string>();
if (options.generateCode) {
importCodes.add(`import { printWithCache } from '@graphql-mesh/utils';`);
}
await Promise.all(
documents.map(async documentSource => {
const documentStr = documentSource.rawSDL || printWithCache(documentSource.document);
const sha256Hash = await hashSHA256(documentStr);
documentHashMap.set(sha256Hash, documentStr);
documentSource.sha256Hash = sha256Hash;
if (options.generateCode) {
visit(documentSource.document || parseWithCache(documentStr), {
OperationDefinition(node) {
const variableName = pascalCase(node.name.value + '_Document');
documentVariableNames.push(variableName);
documentVariableHashCodeMap.set(variableName, sha256Hash);
if (options.generateCode) {
documentHashMapCodes.add(`${JSON.stringify(sha256Hash)}: ${variableName}`);
}
},
});
}
}),
);
additionalEnvelopPlugins.push(
usePersistedOperations({
getPersistedOperation(key) {
return documentHashMap.get(key);
},
skipDocumentValidation: true,
allowArbitraryOperations: true,
}),
);
if (options.generateCode) {
importCodes.add(
`import { usePersistedOperations } from '@graphql-yoga/plugin-persisted-operations';`,
);
codes.add(`const documentHashMap = {
${[...documentHashMapCodes].join(',\n')}
}`);
codes.add(`additionalEnvelopPlugins.push(usePersistedOperations({
getPersistedOperation(key) {
return documentHashMap[key];
},
}))`);
}
}
if (options.generateCode) {
codes.add(`
return {
sources,
transforms,
additionalTypeDefs,
additionalResolvers,
cache,
pubsub,
merger,
logger,
additionalEnvelopPlugins,
get documents() {
return [
${documentVariableNames
.map(
documentVarName => `{
document: ${documentVarName},
get rawSDL() {
return printWithCache(${documentVarName});
},
location: '${documentVarName}.graphql',
sha256Hash: '${documentVariableHashCodeMap.get(documentVarName)}'
}`,
)
.join(',')}
];
},
fetchFn,
};
}`);
}
return {
sources,
transforms,
additionalTypeDefs,
additionalResolvers,
cache,
merger,
pubsub,
config,
documents,
logger,
store: rootStore,
additionalEnvelopPlugins,
importCodes,
codes,
fetchFn,
};
}