@graphql-tools/stitching-directives 2.1.1-alpha-5d885fa3.0 → 3.0.0-alpha-8ae2f1b1.0

Sign up to get free protection for your applications and to get access to all the features.
package/es5/index.js DELETED
@@ -1,1196 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const tslib = require('tslib');
6
- const graphql = require('graphql');
7
- const utils = require('@graphql-tools/utils/es5');
8
- const delegate = require('@graphql-tools/delegate/es5');
9
-
10
- var defaultStitchingDirectiveOptions = {
11
- keyDirectiveName: 'key',
12
- computedDirectiveName: 'computed',
13
- canonicalDirectiveName: 'canonical',
14
- mergeDirectiveName: 'merge',
15
- pathToDirectivesInExtensions: ['directives'],
16
- };
17
-
18
- function extractVariables(inputValue) {
19
- var _a;
20
- var path = [];
21
- var variablePaths = Object.create(null);
22
- var keyPathVisitor = {
23
- enter: function (_node, key) {
24
- if (typeof key === 'number') {
25
- path.push(key);
26
- }
27
- },
28
- leave: function (_node, key) {
29
- if (typeof key === 'number') {
30
- path.pop();
31
- }
32
- },
33
- };
34
- var fieldPathVisitor = {
35
- enter: function (node) {
36
- path.push(node.name.value);
37
- },
38
- leave: function () {
39
- path.pop();
40
- },
41
- };
42
- var variableVisitor = {
43
- enter: function (node, key) {
44
- if (typeof key === 'number') {
45
- variablePaths[node.name.value] = path.concat([key]);
46
- }
47
- else {
48
- variablePaths[node.name.value] = path.slice();
49
- }
50
- return {
51
- kind: graphql.Kind.NULL,
52
- };
53
- },
54
- };
55
- var newInputValue = graphql.visit(inputValue, (_a = {},
56
- _a[graphql.Kind.OBJECT] = keyPathVisitor,
57
- _a[graphql.Kind.LIST] = keyPathVisitor,
58
- _a[graphql.Kind.OBJECT_FIELD] = fieldPathVisitor,
59
- _a[graphql.Kind.VARIABLE] = variableVisitor,
60
- _a));
61
- return {
62
- inputValue: newInputValue,
63
- variablePaths: variablePaths,
64
- };
65
- }
66
-
67
- var KEY_DELIMITER = '__dot__';
68
- var EXPANSION_PREFIX = '__exp';
69
- function preparseMergeArgsExpr(mergeArgsExpr) {
70
- var variableRegex = /\$[_A-Za-z][_A-Za-z0-9.]*/g;
71
- var dotRegex = /\./g;
72
- mergeArgsExpr = mergeArgsExpr.replace(variableRegex, function (variable) { return variable.replace(dotRegex, KEY_DELIMITER); });
73
- var segments = mergeArgsExpr.split('[[');
74
- var expansionExpressions = Object.create(null);
75
- if (segments.length === 1) {
76
- return { mergeArgsExpr: mergeArgsExpr, expansionExpressions: expansionExpressions };
77
- }
78
- var finalSegments = [segments[0]];
79
- for (var i = 1; i < segments.length; i++) {
80
- var additionalSegments = segments[i].split(']]');
81
- if (additionalSegments.length !== 2) {
82
- throw new Error("Each opening \"[[\" must be matched by a closing \"]]\" without nesting.");
83
- }
84
- finalSegments = finalSegments.concat(additionalSegments);
85
- }
86
- var finalMergeArgsExpr = finalSegments[0];
87
- for (var i = 1; i < finalSegments.length - 1; i += 2) {
88
- var variableName = "" + EXPANSION_PREFIX + ((i - 1) / 2 + 1);
89
- expansionExpressions[variableName] = finalSegments[i];
90
- finalMergeArgsExpr += "$" + variableName + finalSegments[i + 1];
91
- }
92
- return { mergeArgsExpr: finalMergeArgsExpr, expansionExpressions: expansionExpressions };
93
- }
94
-
95
- function addProperty(object, path, value) {
96
- var initialSegment = path[0];
97
- if (path.length === 1) {
98
- object[initialSegment] = value;
99
- return;
100
- }
101
- var field = object[initialSegment];
102
- if (field != null) {
103
- addProperty(field, path.slice(1), value);
104
- return;
105
- }
106
- if (typeof path[1] === 'string') {
107
- field = Object.create(null);
108
- }
109
- else {
110
- field = [];
111
- }
112
- addProperty(field, path.slice(1), value);
113
- object[initialSegment] = field;
114
- }
115
- function getProperty(object, path) {
116
- if (!path.length || object == null) {
117
- return object;
118
- }
119
- var newPath = path.slice();
120
- var key = newPath.shift();
121
- if (key == null) {
122
- return;
123
- }
124
- var prop = object[key];
125
- return getProperty(prop, newPath);
126
- }
127
- function getProperties(object, propertyTree) {
128
- if (object == null) {
129
- return object;
130
- }
131
- var newObject = Object.create(null);
132
- var _loop_1 = function (key) {
133
- var subKey = propertyTree[key];
134
- if (subKey == null) {
135
- newObject[key] = object[key];
136
- return "continue";
137
- }
138
- var prop = object[key];
139
- newObject[key] = deepMap(prop, function deepMapFn(item) {
140
- return getProperties(item, subKey);
141
- });
142
- };
143
- for (var key in propertyTree) {
144
- _loop_1(key);
145
- }
146
- return newObject;
147
- }
148
- function propertyTreeFromPaths(paths) {
149
- var e_1, _a;
150
- var propertyTree = Object.create(null);
151
- try {
152
- for (var paths_1 = tslib.__values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
153
- var path = paths_1_1.value;
154
- addProperty(propertyTree, path, null);
155
- }
156
- }
157
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
158
- finally {
159
- try {
160
- if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
161
- }
162
- finally { if (e_1) throw e_1.error; }
163
- }
164
- return propertyTree;
165
- }
166
- function deepMap(arrayOrItem, fn) {
167
- if (Array.isArray(arrayOrItem)) {
168
- return arrayOrItem.map(function (nestedArrayOrItem) { return deepMap(nestedArrayOrItem, fn); });
169
- }
170
- return fn(arrayOrItem);
171
- }
172
-
173
- function pathsFromSelectionSet(selectionSet, path) {
174
- var e_1, _a, e_2, _b;
175
- var _c;
176
- if (path === void 0) { path = []; }
177
- var paths = [];
178
- try {
179
- for (var _d = tslib.__values(selectionSet.selections), _e = _d.next(); !_e.done; _e = _d.next()) {
180
- var selection = _e.value;
181
- var additions = (_c = pathsFromSelection(selection, path)) !== null && _c !== void 0 ? _c : [];
182
- try {
183
- for (var additions_1 = (e_2 = void 0, tslib.__values(additions)), additions_1_1 = additions_1.next(); !additions_1_1.done; additions_1_1 = additions_1.next()) {
184
- var addition = additions_1_1.value;
185
- paths.push(addition);
186
- }
187
- }
188
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
189
- finally {
190
- try {
191
- if (additions_1_1 && !additions_1_1.done && (_b = additions_1.return)) _b.call(additions_1);
192
- }
193
- finally { if (e_2) throw e_2.error; }
194
- }
195
- }
196
- }
197
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
198
- finally {
199
- try {
200
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
201
- }
202
- finally { if (e_1) throw e_1.error; }
203
- }
204
- return paths;
205
- }
206
- function pathsFromSelection(selection, path) {
207
- var _a, _b;
208
- if (selection.kind === graphql.Kind.FIELD) {
209
- var responseKey = (_b = (_a = selection.alias) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : selection.name.value;
210
- if (selection.selectionSet) {
211
- return pathsFromSelectionSet(selection.selectionSet, path.concat([responseKey]));
212
- }
213
- else {
214
- return [path.concat([responseKey])];
215
- }
216
- }
217
- else if (selection.kind === graphql.Kind.INLINE_FRAGMENT) {
218
- return pathsFromSelectionSet(selection.selectionSet, path);
219
- }
220
- }
221
-
222
- function getSourcePaths(mappingInstructions, selectionSet) {
223
- var e_1, _a, e_2, _b;
224
- var sourcePaths = [];
225
- try {
226
- for (var mappingInstructions_1 = tslib.__values(mappingInstructions), mappingInstructions_1_1 = mappingInstructions_1.next(); !mappingInstructions_1_1.done; mappingInstructions_1_1 = mappingInstructions_1.next()) {
227
- var mappingInstruction = mappingInstructions_1_1.value;
228
- var sourcePath = mappingInstruction.sourcePath;
229
- if (sourcePath.length) {
230
- sourcePaths.push(sourcePath);
231
- continue;
232
- }
233
- if (selectionSet == null) {
234
- continue;
235
- }
236
- var paths = pathsFromSelectionSet(selectionSet);
237
- try {
238
- for (var paths_1 = (e_2 = void 0, tslib.__values(paths)), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
239
- var path = paths_1_1.value;
240
- sourcePaths.push(path);
241
- }
242
- }
243
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
244
- finally {
245
- try {
246
- if (paths_1_1 && !paths_1_1.done && (_b = paths_1.return)) _b.call(paths_1);
247
- }
248
- finally { if (e_2) throw e_2.error; }
249
- }
250
- sourcePaths.push([graphql.TypeNameMetaFieldDef.name]);
251
- }
252
- }
253
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
254
- finally {
255
- try {
256
- if (mappingInstructions_1_1 && !mappingInstructions_1_1.done && (_a = mappingInstructions_1.return)) _a.call(mappingInstructions_1);
257
- }
258
- finally { if (e_1) throw e_1.error; }
259
- }
260
- return sourcePaths;
261
- }
262
-
263
- function parseMergeArgsExpr(mergeArgsExpr, selectionSet) {
264
- var _a = preparseMergeArgsExpr(mergeArgsExpr), newMergeArgsExpr = _a.mergeArgsExpr, expansionExpressions = _a.expansionExpressions;
265
- var inputValue = graphql.parseValue("{ " + newMergeArgsExpr + " }", { noLocation: true });
266
- var _b = extractVariables(inputValue), newInputValue = _b.inputValue, variablePaths = _b.variablePaths;
267
- if (!Object.keys(expansionExpressions).length) {
268
- if (!Object.keys(variablePaths).length) {
269
- throw new Error('Merge arguments must declare a key.');
270
- }
271
- var mappingInstructions = getMappingInstructions(variablePaths);
272
- var usedProperties_1 = propertyTreeFromPaths(getSourcePaths(mappingInstructions, selectionSet));
273
- return { args: graphql.valueFromASTUntyped(newInputValue), usedProperties: usedProperties_1, mappingInstructions: mappingInstructions };
274
- }
275
- var expansionRegEx = new RegExp("^" + EXPANSION_PREFIX + "[0-9]+$");
276
- for (var variableName in variablePaths) {
277
- if (!variableName.match(expansionRegEx)) {
278
- throw new Error('Expansions cannot be mixed with single key declarations.');
279
- }
280
- }
281
- var expansions = [];
282
- var sourcePaths = [];
283
- for (var variableName in expansionExpressions) {
284
- var str = expansionExpressions[variableName];
285
- var valuePath = variablePaths[variableName];
286
- var _c = extractVariables(graphql.parseValue("" + str, { noLocation: true })), expansionInputValue = _c.inputValue, expansionVariablePaths = _c.variablePaths;
287
- if (!Object.keys(expansionVariablePaths).length) {
288
- throw new Error('Merge arguments must declare a key.');
289
- }
290
- var mappingInstructions = getMappingInstructions(expansionVariablePaths);
291
- var value = graphql.valueFromASTUntyped(expansionInputValue);
292
- sourcePaths.push.apply(sourcePaths, tslib.__spreadArray([], tslib.__read(getSourcePaths(mappingInstructions, selectionSet)), false));
293
- assertNotWithinList(valuePath);
294
- expansions.push({
295
- valuePath: valuePath,
296
- value: value,
297
- mappingInstructions: mappingInstructions,
298
- });
299
- }
300
- var usedProperties = propertyTreeFromPaths(sourcePaths);
301
- return { args: graphql.valueFromASTUntyped(newInputValue), usedProperties: usedProperties, expansions: expansions };
302
- }
303
- function getMappingInstructions(variablePaths) {
304
- var mappingInstructions = [];
305
- for (var keyPath in variablePaths) {
306
- var valuePath = variablePaths[keyPath];
307
- var splitKeyPath = keyPath.split(KEY_DELIMITER).slice(1);
308
- assertNotWithinList(valuePath);
309
- mappingInstructions.push({
310
- destinationPath: valuePath,
311
- sourcePath: splitKeyPath,
312
- });
313
- }
314
- return mappingInstructions;
315
- }
316
- function assertNotWithinList(path) {
317
- var e_1, _a;
318
- try {
319
- for (var path_1 = tslib.__values(path), path_1_1 = path_1.next(); !path_1_1.done; path_1_1 = path_1.next()) {
320
- var pathSegment = path_1_1.value;
321
- if (typeof pathSegment === 'number') {
322
- throw new Error('Insertions cannot be made into a list.');
323
- }
324
- }
325
- }
326
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
327
- finally {
328
- try {
329
- if (path_1_1 && !path_1_1.done && (_a = path_1.return)) _a.call(path_1);
330
- }
331
- finally { if (e_1) throw e_1.error; }
332
- }
333
- }
334
-
335
- var dottedNameRegEx = /^[_A-Za-z][_0-9A-Za-z]*(.[_A-Za-z][_0-9A-Za-z]*)*$/;
336
- function stitchingDirectivesValidator(options) {
337
- if (options === void 0) { options = {}; }
338
- var _a = tslib.__assign(tslib.__assign({}, defaultStitchingDirectiveOptions), options), keyDirectiveName = _a.keyDirectiveName, computedDirectiveName = _a.computedDirectiveName, mergeDirectiveName = _a.mergeDirectiveName, pathToDirectivesInExtensions = _a.pathToDirectivesInExtensions;
339
- return function (schema) {
340
- var _a;
341
- var _b;
342
- var queryTypeName = (_b = schema.getQueryType()) === null || _b === void 0 ? void 0 : _b.name;
343
- utils.mapSchema(schema, (_a = {},
344
- _a[utils.MapperKind.OBJECT_TYPE] = function (type) {
345
- var _a;
346
- var keyDirective = (_a = utils.getDirective(schema, type, keyDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
347
- if (keyDirective != null) {
348
- utils.parseSelectionSet(keyDirective['selectionSet']);
349
- }
350
- return undefined;
351
- },
352
- _a[utils.MapperKind.OBJECT_FIELD] = function (fieldConfig, _fieldName, typeName) {
353
- var e_1, _a, e_2, _b;
354
- var _c, _d, _e;
355
- var computedDirective = (_c = utils.getDirective(schema, fieldConfig, computedDirectiveName, pathToDirectivesInExtensions)) === null || _c === void 0 ? void 0 : _c[0];
356
- if (computedDirective != null) {
357
- utils.parseSelectionSet(computedDirective['selectionSet']);
358
- }
359
- var mergeDirective = (_d = utils.getDirective(schema, fieldConfig, mergeDirectiveName, pathToDirectivesInExtensions)) === null || _d === void 0 ? void 0 : _d[0];
360
- if (mergeDirective != null) {
361
- if (typeName !== queryTypeName) {
362
- throw new Error('@merge directive may be used only for root fields of the root Query type.');
363
- }
364
- var returnType = graphql.getNullableType(fieldConfig.type);
365
- if (graphql.isListType(returnType)) {
366
- returnType = graphql.getNullableType(returnType.ofType);
367
- }
368
- if (!graphql.isNamedType(returnType)) {
369
- throw new Error('@merge directive must be used on a field that returns an object or a list of objects.');
370
- }
371
- var mergeArgsExpr = mergeDirective['argsExpr'];
372
- if (mergeArgsExpr != null) {
373
- parseMergeArgsExpr(mergeArgsExpr);
374
- }
375
- var args = Object.keys((_e = fieldConfig.args) !== null && _e !== void 0 ? _e : {});
376
- var keyArg = mergeDirective['keyArg'];
377
- if (keyArg == null) {
378
- if (!mergeArgsExpr && args.length !== 1) {
379
- throw new Error('Cannot use @merge directive without `keyArg` argument if resolver takes more than one argument.');
380
- }
381
- }
382
- else if (!keyArg.match(dottedNameRegEx)) {
383
- throw new Error('`keyArg` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
384
- // TODO: ideally we should check that the arg exists for the resolver
385
- }
386
- var keyField = mergeDirective['keyField'];
387
- if (keyField != null && !keyField.match(dottedNameRegEx)) {
388
- throw new Error('`keyField` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
389
- // TODO: ideally we should check that it is part of the key
390
- }
391
- var key = mergeDirective['key'];
392
- if (key != null) {
393
- if (keyField != null) {
394
- throw new Error('Cannot use @merge directive with both `keyField` and `key` arguments.');
395
- }
396
- try {
397
- for (var key_1 = tslib.__values(key), key_1_1 = key_1.next(); !key_1_1.done; key_1_1 = key_1.next()) {
398
- var keyDef = key_1_1.value;
399
- var _f = tslib.__read(keyDef.split(':'), 2), aliasOrKeyPath = _f[0], keyPath = _f[1];
400
- var aliasPath = void 0;
401
- if (keyPath == null) {
402
- keyPath = aliasPath = aliasOrKeyPath;
403
- }
404
- else {
405
- aliasPath = aliasOrKeyPath;
406
- }
407
- if (keyPath != null && !keyPath.match(dottedNameRegEx)) {
408
- throw new Error('Each partial key within the `key` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
409
- // TODO: ideally we should check that it is part of the key
410
- }
411
- if (aliasPath != null && !aliasOrKeyPath.match(dottedNameRegEx)) {
412
- throw new Error('Each alias within the `key` argument for @merge directive must be a set of valid GraphQL SDL names separated by periods.');
413
- // TODO: ideally we should check that the arg exists within the resolver
414
- }
415
- }
416
- }
417
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
418
- finally {
419
- try {
420
- if (key_1_1 && !key_1_1.done && (_a = key_1.return)) _a.call(key_1);
421
- }
422
- finally { if (e_1) throw e_1.error; }
423
- }
424
- }
425
- var additionalArgs = mergeDirective['additionalArgs'];
426
- if (additionalArgs != null) {
427
- graphql.parseValue("{ " + additionalArgs + " }", { noLocation: true });
428
- }
429
- if (mergeArgsExpr != null && (keyArg != null || additionalArgs != null)) {
430
- throw new Error('Cannot use @merge directive with both `argsExpr` argument and any additional argument.');
431
- }
432
- if (!graphql.isInterfaceType(returnType) && !graphql.isUnionType(returnType) && !graphql.isObjectType(returnType)) {
433
- throw new Error('@merge directive may be used only with resolver that return an object, interface, or union.');
434
- }
435
- var typeNames = mergeDirective['types'];
436
- if (typeNames != null) {
437
- if (!graphql.isAbstractType(returnType)) {
438
- throw new Error('Types argument can only be used with a field that returns an abstract type.');
439
- }
440
- var implementingTypes = graphql.isInterfaceType(returnType)
441
- ? utils.getImplementingTypes(returnType.name, schema).map(function (typeName) { return schema.getType(typeName); })
442
- : returnType.getTypes();
443
- var implementingTypeNames = implementingTypes.map(function (type) { return type === null || type === void 0 ? void 0 : type.name; }).filter(utils.isSome);
444
- try {
445
- for (var typeNames_1 = tslib.__values(typeNames), typeNames_1_1 = typeNames_1.next(); !typeNames_1_1.done; typeNames_1_1 = typeNames_1.next()) {
446
- var typeName_1 = typeNames_1_1.value;
447
- if (!implementingTypeNames.includes(typeName_1)) {
448
- throw new Error("Types argument can only include only type names that implement the field return type's abstract type.");
449
- }
450
- }
451
- }
452
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
453
- finally {
454
- try {
455
- if (typeNames_1_1 && !typeNames_1_1.done && (_b = typeNames_1.return)) _b.call(typeNames_1);
456
- }
457
- finally { if (e_2) throw e_2.error; }
458
- }
459
- }
460
- }
461
- return undefined;
462
- },
463
- _a));
464
- return schema;
465
- };
466
- }
467
-
468
- function stitchingDirectivesTransformer(options) {
469
- if (options === void 0) { options = {}; }
470
- var _a = tslib.__assign(tslib.__assign({}, defaultStitchingDirectiveOptions), options), keyDirectiveName = _a.keyDirectiveName, computedDirectiveName = _a.computedDirectiveName, mergeDirectiveName = _a.mergeDirectiveName, canonicalDirectiveName = _a.canonicalDirectiveName, pathToDirectivesInExtensions = _a.pathToDirectivesInExtensions;
471
- return function (subschemaConfig) {
472
- var _a, _b;
473
- var _c, _d, _e, _f, _g, _h, _j, _k;
474
- var newSubschemaConfig = delegate.cloneSubschemaConfig(subschemaConfig);
475
- var selectionSetsByType = Object.create(null);
476
- var computedFieldSelectionSets = Object.create(null);
477
- var mergedTypesResolversInfo = Object.create(null);
478
- var canonicalTypesInfo = Object.create(null);
479
- var schema = subschemaConfig.schema;
480
- // gateway should also run validation
481
- stitchingDirectivesValidator(options)(schema);
482
- function setCanonicalDefinition(typeName, fieldName) {
483
- var _a;
484
- canonicalTypesInfo[typeName] = canonicalTypesInfo[typeName] || Object.create(null);
485
- if (fieldName) {
486
- var fields = (_a = canonicalTypesInfo[typeName].fields) !== null && _a !== void 0 ? _a : Object.create(null);
487
- canonicalTypesInfo[typeName].fields = fields;
488
- fields[fieldName] = true;
489
- }
490
- else {
491
- canonicalTypesInfo[typeName].canonical = true;
492
- }
493
- }
494
- utils.mapSchema(schema, (_a = {},
495
- _a[utils.MapperKind.OBJECT_TYPE] = function (type) {
496
- var _a, _b;
497
- var keyDirective = (_a = utils.getDirective(schema, type, keyDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
498
- if (keyDirective != null) {
499
- var selectionSet = utils.parseSelectionSet(keyDirective['selectionSet'], { noLocation: true });
500
- selectionSetsByType[type.name] = selectionSet;
501
- }
502
- var canonicalDirective = (_b = utils.getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _b === void 0 ? void 0 : _b[0];
503
- if (canonicalDirective != null) {
504
- setCanonicalDefinition(type.name);
505
- }
506
- return undefined;
507
- },
508
- _a[utils.MapperKind.OBJECT_FIELD] = function (fieldConfig, fieldName, typeName) {
509
- var _a, _b, _c;
510
- var computedDirective = (_a = utils.getDirective(schema, fieldConfig, computedDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
511
- if (computedDirective != null) {
512
- var selectionSet = utils.parseSelectionSet(computedDirective['selectionSet'], { noLocation: true });
513
- if (!computedFieldSelectionSets[typeName]) {
514
- computedFieldSelectionSets[typeName] = Object.create(null);
515
- }
516
- computedFieldSelectionSets[typeName][fieldName] = selectionSet;
517
- }
518
- var mergeDirective = (_b = utils.getDirective(schema, fieldConfig, mergeDirectiveName, pathToDirectivesInExtensions)) === null || _b === void 0 ? void 0 : _b[0];
519
- if ((mergeDirective === null || mergeDirective === void 0 ? void 0 : mergeDirective['keyField']) != null) {
520
- var mergeDirectiveKeyField = mergeDirective['keyField'];
521
- var selectionSet_1 = utils.parseSelectionSet("{ " + mergeDirectiveKeyField + "}", { noLocation: true });
522
- var typeNames_1 = mergeDirective['types'];
523
- var returnType = graphql.getNamedType(fieldConfig.type);
524
- forEachConcreteType(schema, returnType, typeNames_1, function (typeName) {
525
- if (typeNames_1 == null || typeNames_1.includes(typeName)) {
526
- var existingSelectionSet = selectionSetsByType[typeName];
527
- selectionSetsByType[typeName] = existingSelectionSet
528
- ? mergeSelectionSets(existingSelectionSet, selectionSet_1)
529
- : selectionSet_1;
530
- }
531
- });
532
- }
533
- var canonicalDirective = (_c = utils.getDirective(schema, fieldConfig, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _c === void 0 ? void 0 : _c[0];
534
- if (canonicalDirective != null) {
535
- setCanonicalDefinition(typeName, fieldName);
536
- }
537
- return undefined;
538
- },
539
- _a[utils.MapperKind.INTERFACE_TYPE] = function (type) {
540
- var _a;
541
- var canonicalDirective = (_a = utils.getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
542
- if (canonicalDirective) {
543
- setCanonicalDefinition(type.name);
544
- }
545
- return undefined;
546
- },
547
- _a[utils.MapperKind.INTERFACE_FIELD] = function (fieldConfig, fieldName, typeName) {
548
- var _a;
549
- var canonicalDirective = (_a = utils.getDirective(schema, fieldConfig, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
550
- if (canonicalDirective) {
551
- setCanonicalDefinition(typeName, fieldName);
552
- }
553
- return undefined;
554
- },
555
- _a[utils.MapperKind.INPUT_OBJECT_TYPE] = function (type) {
556
- var _a;
557
- var canonicalDirective = (_a = utils.getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
558
- if (canonicalDirective) {
559
- setCanonicalDefinition(type.name);
560
- }
561
- return undefined;
562
- },
563
- _a[utils.MapperKind.INPUT_OBJECT_FIELD] = function (inputFieldConfig, fieldName, typeName) {
564
- var _a;
565
- var canonicalDirective = (_a = utils.getDirective(schema, inputFieldConfig, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
566
- if (canonicalDirective != null) {
567
- setCanonicalDefinition(typeName, fieldName);
568
- }
569
- return undefined;
570
- },
571
- _a[utils.MapperKind.UNION_TYPE] = function (type) {
572
- var _a;
573
- var canonicalDirective = (_a = utils.getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
574
- if (canonicalDirective != null) {
575
- setCanonicalDefinition(type.name);
576
- }
577
- return undefined;
578
- },
579
- _a[utils.MapperKind.ENUM_TYPE] = function (type) {
580
- var _a;
581
- var canonicalDirective = (_a = utils.getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
582
- if (canonicalDirective != null) {
583
- setCanonicalDefinition(type.name);
584
- }
585
- return undefined;
586
- },
587
- _a[utils.MapperKind.SCALAR_TYPE] = function (type) {
588
- var _a;
589
- var canonicalDirective = (_a = utils.getDirective(schema, type, canonicalDirectiveName, pathToDirectivesInExtensions)) === null || _a === void 0 ? void 0 : _a[0];
590
- if (canonicalDirective != null) {
591
- setCanonicalDefinition(type.name);
592
- }
593
- return undefined;
594
- },
595
- _a));
596
- if (subschemaConfig.merge) {
597
- for (var typeName in subschemaConfig.merge) {
598
- var mergedTypeConfig = subschemaConfig.merge[typeName];
599
- if (mergedTypeConfig.selectionSet) {
600
- var selectionSet = utils.parseSelectionSet(mergedTypeConfig.selectionSet, { noLocation: true });
601
- if (selectionSet) {
602
- if (selectionSetsByType[typeName]) {
603
- selectionSetsByType[typeName] = mergeSelectionSets(selectionSetsByType[typeName], selectionSet);
604
- }
605
- else {
606
- selectionSetsByType[typeName] = selectionSet;
607
- }
608
- }
609
- }
610
- if (mergedTypeConfig.fields) {
611
- for (var fieldName in mergedTypeConfig.fields) {
612
- var fieldConfig = mergedTypeConfig.fields[fieldName];
613
- if (!fieldConfig.selectionSet)
614
- continue;
615
- var selectionSet = utils.parseSelectionSet(fieldConfig.selectionSet, { noLocation: true });
616
- if (selectionSet) {
617
- if ((_c = computedFieldSelectionSets[typeName]) === null || _c === void 0 ? void 0 : _c[fieldName]) {
618
- computedFieldSelectionSets[typeName][fieldName] = mergeSelectionSets(computedFieldSelectionSets[typeName][fieldName], selectionSet);
619
- }
620
- else {
621
- if (computedFieldSelectionSets[typeName] == null) {
622
- computedFieldSelectionSets[typeName] = Object.create(null);
623
- }
624
- computedFieldSelectionSets[typeName][fieldName] = selectionSet;
625
- }
626
- }
627
- }
628
- }
629
- }
630
- }
631
- var allSelectionSetsByType = Object.create(null);
632
- for (var typeName in selectionSetsByType) {
633
- allSelectionSetsByType[typeName] = allSelectionSetsByType[typeName] || [];
634
- var selectionSet = selectionSetsByType[typeName];
635
- allSelectionSetsByType[typeName].push(selectionSet);
636
- }
637
- for (var typeName in computedFieldSelectionSets) {
638
- var selectionSets = computedFieldSelectionSets[typeName];
639
- for (var i in selectionSets) {
640
- allSelectionSetsByType[typeName] = allSelectionSetsByType[typeName] || [];
641
- var selectionSet = selectionSets[i];
642
- allSelectionSetsByType[typeName].push(selectionSet);
643
- }
644
- }
645
- utils.mapSchema(schema, (_b = {},
646
- _b[utils.MapperKind.OBJECT_FIELD] = function objectFieldMapper(fieldConfig, fieldName) {
647
- var e_1, _a;
648
- var _b, _c;
649
- var mergeDirective = (_b = utils.getDirective(schema, fieldConfig, mergeDirectiveName, pathToDirectivesInExtensions)) === null || _b === void 0 ? void 0 : _b[0];
650
- if (mergeDirective != null) {
651
- var returnType = graphql.getNullableType(fieldConfig.type);
652
- var returnsList_1 = graphql.isListType(returnType);
653
- var namedType = graphql.getNamedType(returnType);
654
- var mergeArgsExpr_1 = mergeDirective['argsExpr'];
655
- if (mergeArgsExpr_1 == null) {
656
- var key = mergeDirective['key'];
657
- var keyField = mergeDirective['keyField'];
658
- var keyExpr = key != null ? buildKeyExpr(key) : keyField != null ? "$key." + keyField : '$key';
659
- var keyArg = mergeDirective['keyArg'];
660
- var argNames = keyArg == null ? [Object.keys((_c = fieldConfig.args) !== null && _c !== void 0 ? _c : {})[0]] : keyArg.split('.');
661
- var lastArgName = argNames.pop();
662
- mergeArgsExpr_1 = returnsList_1 ? lastArgName + ": [[" + keyExpr + "]]" : lastArgName + ": " + keyExpr;
663
- try {
664
- for (var _d = tslib.__values(argNames.reverse()), _e = _d.next(); !_e.done; _e = _d.next()) {
665
- var argName = _e.value;
666
- mergeArgsExpr_1 = argName + ": { " + mergeArgsExpr_1 + " }";
667
- }
668
- }
669
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
670
- finally {
671
- try {
672
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
673
- }
674
- finally { if (e_1) throw e_1.error; }
675
- }
676
- }
677
- var typeNames = mergeDirective['types'];
678
- forEachConcreteTypeName(namedType, schema, typeNames, function generateResolveInfo(typeName) {
679
- var parsedMergeArgsExpr = parseMergeArgsExpr(mergeArgsExpr_1, allSelectionSetsByType[typeName] == null
680
- ? undefined
681
- : mergeSelectionSets.apply(void 0, tslib.__spreadArray([], tslib.__read(allSelectionSetsByType[typeName]), false)));
682
- var additionalArgs = mergeDirective['additionalArgs'];
683
- if (additionalArgs != null) {
684
- parsedMergeArgsExpr.args = utils.mergeDeep([
685
- parsedMergeArgsExpr.args,
686
- graphql.valueFromASTUntyped(graphql.parseValue("{ " + additionalArgs + " }", { noLocation: true })),
687
- ]);
688
- }
689
- mergedTypesResolversInfo[typeName] = tslib.__assign({ fieldName: fieldName, returnsList: returnsList_1 }, parsedMergeArgsExpr);
690
- });
691
- }
692
- return undefined;
693
- },
694
- _b));
695
- for (var typeName in selectionSetsByType) {
696
- var selectionSet = selectionSetsByType[typeName];
697
- var mergeConfig = (_d = newSubschemaConfig.merge) !== null && _d !== void 0 ? _d : Object.create(null);
698
- newSubschemaConfig.merge = mergeConfig;
699
- if (mergeConfig[typeName] == null) {
700
- newSubschemaConfig.merge[typeName] = Object.create(null);
701
- }
702
- var mergeTypeConfig = mergeConfig[typeName];
703
- mergeTypeConfig.selectionSet = graphql.print(selectionSet);
704
- }
705
- for (var typeName in computedFieldSelectionSets) {
706
- var selectionSets = computedFieldSelectionSets[typeName];
707
- var mergeConfig = (_e = newSubschemaConfig.merge) !== null && _e !== void 0 ? _e : Object.create(null);
708
- newSubschemaConfig.merge = mergeConfig;
709
- if (mergeConfig[typeName] == null) {
710
- mergeConfig[typeName] = Object.create(null);
711
- }
712
- var mergeTypeConfig = newSubschemaConfig.merge[typeName];
713
- var mergeTypeConfigFields = (_f = mergeTypeConfig.fields) !== null && _f !== void 0 ? _f : Object.create(null);
714
- mergeTypeConfig.fields = mergeTypeConfigFields;
715
- for (var fieldName in selectionSets) {
716
- var selectionSet = selectionSets[fieldName];
717
- var fieldConfig = (_g = mergeTypeConfigFields[fieldName]) !== null && _g !== void 0 ? _g : Object.create(null);
718
- mergeTypeConfigFields[fieldName] = fieldConfig;
719
- fieldConfig.selectionSet = graphql.print(selectionSet);
720
- fieldConfig.computed = true;
721
- }
722
- }
723
- for (var typeName in mergedTypesResolversInfo) {
724
- var mergedTypeResolverInfo = mergedTypesResolversInfo[typeName];
725
- var mergeConfig = (_h = newSubschemaConfig.merge) !== null && _h !== void 0 ? _h : Object.create(null);
726
- newSubschemaConfig.merge = mergeConfig;
727
- if (newSubschemaConfig.merge[typeName] == null) {
728
- newSubschemaConfig.merge[typeName] = Object.create(null);
729
- }
730
- var mergeTypeConfig = newSubschemaConfig.merge[typeName];
731
- mergeTypeConfig.fieldName = mergedTypeResolverInfo.fieldName;
732
- if (mergedTypeResolverInfo.returnsList) {
733
- mergeTypeConfig.key = generateKeyFn(mergedTypeResolverInfo);
734
- mergeTypeConfig.argsFromKeys = generateArgsFromKeysFn(mergedTypeResolverInfo);
735
- }
736
- else {
737
- mergeTypeConfig.args = generateArgsFn(mergedTypeResolverInfo);
738
- }
739
- }
740
- for (var typeName in canonicalTypesInfo) {
741
- var canonicalTypeInfo = canonicalTypesInfo[typeName];
742
- var mergeConfig = (_j = newSubschemaConfig.merge) !== null && _j !== void 0 ? _j : Object.create(null);
743
- newSubschemaConfig.merge = mergeConfig;
744
- if (newSubschemaConfig.merge[typeName] == null) {
745
- newSubschemaConfig.merge[typeName] = Object.create(null);
746
- }
747
- var mergeTypeConfig = newSubschemaConfig.merge[typeName];
748
- if (canonicalTypeInfo.canonical) {
749
- mergeTypeConfig.canonical = true;
750
- }
751
- if (canonicalTypeInfo.fields) {
752
- var mergeTypeConfigFields = (_k = mergeTypeConfig.fields) !== null && _k !== void 0 ? _k : Object.create(null);
753
- mergeTypeConfig.fields = mergeTypeConfigFields;
754
- for (var fieldName in canonicalTypeInfo.fields) {
755
- if (mergeTypeConfigFields[fieldName] == null) {
756
- mergeTypeConfigFields[fieldName] = Object.create(null);
757
- }
758
- mergeTypeConfigFields[fieldName].canonical = true;
759
- }
760
- }
761
- }
762
- return newSubschemaConfig;
763
- };
764
- }
765
- function forEachConcreteType(schema, type, typeNames, fn) {
766
- var e_2, _a, e_3, _b;
767
- if (graphql.isInterfaceType(type)) {
768
- try {
769
- for (var _c = tslib.__values(utils.getImplementingTypes(type.name, schema)), _d = _c.next(); !_d.done; _d = _c.next()) {
770
- var typeName = _d.value;
771
- if (typeNames == null || typeNames.includes(typeName)) {
772
- fn(typeName);
773
- }
774
- }
775
- }
776
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
777
- finally {
778
- try {
779
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
780
- }
781
- finally { if (e_2) throw e_2.error; }
782
- }
783
- }
784
- else if (graphql.isUnionType(type)) {
785
- try {
786
- for (var _e = tslib.__values(type.getTypes()), _f = _e.next(); !_f.done; _f = _e.next()) {
787
- var typeName = _f.value.name;
788
- if (typeNames == null || typeNames.includes(typeName)) {
789
- fn(typeName);
790
- }
791
- }
792
- }
793
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
794
- finally {
795
- try {
796
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
797
- }
798
- finally { if (e_3) throw e_3.error; }
799
- }
800
- }
801
- else if (graphql.isObjectType(type)) {
802
- fn(type.name);
803
- }
804
- }
805
- function generateKeyFn(mergedTypeResolverInfo) {
806
- return function keyFn(originalResult) {
807
- return getProperties(originalResult, mergedTypeResolverInfo.usedProperties);
808
- };
809
- }
810
- function generateArgsFromKeysFn(mergedTypeResolverInfo) {
811
- var expansions = mergedTypeResolverInfo.expansions, args = mergedTypeResolverInfo.args;
812
- return function generateArgsFromKeys(keys) {
813
- var e_4, _a, e_5, _b, e_6, _c;
814
- var newArgs = utils.mergeDeep([{}, args]);
815
- if (expansions) {
816
- try {
817
- for (var expansions_1 = tslib.__values(expansions), expansions_1_1 = expansions_1.next(); !expansions_1_1.done; expansions_1_1 = expansions_1.next()) {
818
- var expansion = expansions_1_1.value;
819
- var mappingInstructions = expansion.mappingInstructions;
820
- var expanded = [];
821
- try {
822
- for (var keys_1 = (e_5 = void 0, tslib.__values(keys)), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
823
- var key = keys_1_1.value;
824
- var newValue = utils.mergeDeep([{}, expansion.valuePath]);
825
- try {
826
- for (var mappingInstructions_1 = (e_6 = void 0, tslib.__values(mappingInstructions)), mappingInstructions_1_1 = mappingInstructions_1.next(); !mappingInstructions_1_1.done; mappingInstructions_1_1 = mappingInstructions_1.next()) {
827
- var _d = mappingInstructions_1_1.value, destinationPath = _d.destinationPath, sourcePath = _d.sourcePath;
828
- if (destinationPath.length) {
829
- addProperty(newValue, destinationPath, getProperty(key, sourcePath));
830
- }
831
- else {
832
- newValue = getProperty(key, sourcePath);
833
- }
834
- }
835
- }
836
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
837
- finally {
838
- try {
839
- if (mappingInstructions_1_1 && !mappingInstructions_1_1.done && (_c = mappingInstructions_1.return)) _c.call(mappingInstructions_1);
840
- }
841
- finally { if (e_6) throw e_6.error; }
842
- }
843
- expanded.push(newValue);
844
- }
845
- }
846
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
847
- finally {
848
- try {
849
- if (keys_1_1 && !keys_1_1.done && (_b = keys_1.return)) _b.call(keys_1);
850
- }
851
- finally { if (e_5) throw e_5.error; }
852
- }
853
- addProperty(newArgs, expansion.valuePath, expanded);
854
- }
855
- }
856
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
857
- finally {
858
- try {
859
- if (expansions_1_1 && !expansions_1_1.done && (_a = expansions_1.return)) _a.call(expansions_1);
860
- }
861
- finally { if (e_4) throw e_4.error; }
862
- }
863
- }
864
- return newArgs;
865
- };
866
- }
867
- function generateArgsFn(mergedTypeResolverInfo) {
868
- var mappingInstructions = mergedTypeResolverInfo.mappingInstructions, args = mergedTypeResolverInfo.args, usedProperties = mergedTypeResolverInfo.usedProperties;
869
- return function generateArgs(originalResult) {
870
- var e_7, _a;
871
- var newArgs = utils.mergeDeep([{}, args]);
872
- var filteredResult = getProperties(originalResult, usedProperties);
873
- if (mappingInstructions) {
874
- try {
875
- for (var mappingInstructions_2 = tslib.__values(mappingInstructions), mappingInstructions_2_1 = mappingInstructions_2.next(); !mappingInstructions_2_1.done; mappingInstructions_2_1 = mappingInstructions_2.next()) {
876
- var mappingInstruction = mappingInstructions_2_1.value;
877
- var destinationPath = mappingInstruction.destinationPath, sourcePath = mappingInstruction.sourcePath;
878
- addProperty(newArgs, destinationPath, getProperty(filteredResult, sourcePath));
879
- }
880
- }
881
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
882
- finally {
883
- try {
884
- if (mappingInstructions_2_1 && !mappingInstructions_2_1.done && (_a = mappingInstructions_2.return)) _a.call(mappingInstructions_2);
885
- }
886
- finally { if (e_7) throw e_7.error; }
887
- }
888
- }
889
- return newArgs;
890
- };
891
- }
892
- function buildKeyExpr(key) {
893
- var e_8, _a, _b, e_9, _c, _d;
894
- var mergedObject = {};
895
- try {
896
- for (var key_1 = tslib.__values(key), key_1_1 = key_1.next(); !key_1_1.done; key_1_1 = key_1.next()) {
897
- var keyDef = key_1_1.value;
898
- var _e = tslib.__read(keyDef.split(':'), 2), aliasOrKeyPath = _e[0], keyPath = _e[1];
899
- var aliasPath = void 0;
900
- if (keyPath == null) {
901
- keyPath = aliasPath = aliasOrKeyPath;
902
- }
903
- else {
904
- aliasPath = aliasOrKeyPath;
905
- }
906
- var aliasParts = aliasPath.split('.');
907
- var lastAliasPart = aliasParts.pop();
908
- if (lastAliasPart == null) {
909
- throw new Error("Key \"" + key + "\" is invalid, no path provided.");
910
- }
911
- var object = (_b = {}, _b[lastAliasPart] = "$key." + keyPath, _b);
912
- try {
913
- for (var _f = (e_9 = void 0, tslib.__values(aliasParts.reverse())), _g = _f.next(); !_g.done; _g = _f.next()) {
914
- var aliasPart = _g.value;
915
- object = (_d = {}, _d[aliasPart] = object, _d);
916
- }
917
- }
918
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
919
- finally {
920
- try {
921
- if (_g && !_g.done && (_c = _f.return)) _c.call(_f);
922
- }
923
- finally { if (e_9) throw e_9.error; }
924
- }
925
- mergedObject = utils.mergeDeep([mergedObject, object]);
926
- }
927
- }
928
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
929
- finally {
930
- try {
931
- if (key_1_1 && !key_1_1.done && (_a = key_1.return)) _a.call(key_1);
932
- }
933
- finally { if (e_8) throw e_8.error; }
934
- }
935
- return JSON.stringify(mergedObject).replace(/"/g, '');
936
- }
937
- function mergeSelectionSets() {
938
- var e_10, _a, e_11, _b;
939
- var selectionSets = [];
940
- for (var _i = 0; _i < arguments.length; _i++) {
941
- selectionSets[_i] = arguments[_i];
942
- }
943
- var normalizedSelections = Object.create(null);
944
- try {
945
- for (var selectionSets_1 = tslib.__values(selectionSets), selectionSets_1_1 = selectionSets_1.next(); !selectionSets_1_1.done; selectionSets_1_1 = selectionSets_1.next()) {
946
- var selectionSet = selectionSets_1_1.value;
947
- try {
948
- for (var _c = (e_11 = void 0, tslib.__values(selectionSet.selections)), _d = _c.next(); !_d.done; _d = _c.next()) {
949
- var selection = _d.value;
950
- var normalizedSelection = graphql.print(selection);
951
- normalizedSelections[normalizedSelection] = selection;
952
- }
953
- }
954
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
955
- finally {
956
- try {
957
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
958
- }
959
- finally { if (e_11) throw e_11.error; }
960
- }
961
- }
962
- }
963
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
964
- finally {
965
- try {
966
- if (selectionSets_1_1 && !selectionSets_1_1.done && (_a = selectionSets_1.return)) _a.call(selectionSets_1);
967
- }
968
- finally { if (e_10) throw e_10.error; }
969
- }
970
- var newSelectionSet = {
971
- kind: graphql.Kind.SELECTION_SET,
972
- selections: Object.values(normalizedSelections),
973
- };
974
- return newSelectionSet;
975
- }
976
- function forEachConcreteTypeName(returnType, schema, typeNames, fn) {
977
- var e_12, _a, e_13, _b;
978
- if (graphql.isInterfaceType(returnType)) {
979
- try {
980
- for (var _c = tslib.__values(utils.getImplementingTypes(returnType.name, schema)), _d = _c.next(); !_d.done; _d = _c.next()) {
981
- var typeName = _d.value;
982
- if (typeNames == null || typeNames.includes(typeName)) {
983
- fn(typeName);
984
- }
985
- }
986
- }
987
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
988
- finally {
989
- try {
990
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
991
- }
992
- finally { if (e_12) throw e_12.error; }
993
- }
994
- }
995
- else if (graphql.isUnionType(returnType)) {
996
- try {
997
- for (var _e = tslib.__values(returnType.getTypes()), _f = _e.next(); !_f.done; _f = _e.next()) {
998
- var type = _f.value;
999
- if (typeNames == null || typeNames.includes(type.name)) {
1000
- fn(type.name);
1001
- }
1002
- }
1003
- }
1004
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
1005
- finally {
1006
- try {
1007
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1008
- }
1009
- finally { if (e_13) throw e_13.error; }
1010
- }
1011
- }
1012
- else if (graphql.isObjectType(returnType) && (typeNames == null || typeNames.includes(returnType.name))) {
1013
- fn(returnType.name);
1014
- }
1015
- }
1016
-
1017
- function stitchingDirectives(options) {
1018
- if (options === void 0) { options = {}; }
1019
- var finalOptions = tslib.__assign(tslib.__assign({}, defaultStitchingDirectiveOptions), options);
1020
- var keyDirectiveName = finalOptions.keyDirectiveName, computedDirectiveName = finalOptions.computedDirectiveName, mergeDirectiveName = finalOptions.mergeDirectiveName, canonicalDirectiveName = finalOptions.canonicalDirectiveName;
1021
- var keyDirectiveTypeDefs = /* GraphQL */ "directive @" + keyDirectiveName + "(selectionSet: String!) on OBJECT";
1022
- var computedDirectiveTypeDefs = /* GraphQL */ "directive @" + computedDirectiveName + "(selectionSet: String!) on FIELD_DEFINITION";
1023
- var mergeDirectiveTypeDefs = /* GraphQL */ "directive @" + mergeDirectiveName + "(argsExpr: String, keyArg: String, keyField: String, key: [String!], additionalArgs: String) on FIELD_DEFINITION";
1024
- var canonicalDirectiveTypeDefs = /* GraphQL */ "directive @" + canonicalDirectiveName + " on OBJECT | INTERFACE | INPUT_OBJECT | UNION | ENUM | SCALAR | FIELD_DEFINITION | INPUT_FIELD_DEFINITION";
1025
- var keyDirective = new graphql.GraphQLDirective({
1026
- name: keyDirectiveName,
1027
- locations: ['OBJECT'],
1028
- args: {
1029
- selectionSet: { type: new graphql.GraphQLNonNull(graphql.GraphQLString) },
1030
- },
1031
- });
1032
- var computedDirective = new graphql.GraphQLDirective({
1033
- name: computedDirectiveName,
1034
- locations: ['FIELD_DEFINITION'],
1035
- args: {
1036
- selectionSet: { type: new graphql.GraphQLNonNull(graphql.GraphQLString) },
1037
- },
1038
- });
1039
- var mergeDirective = new graphql.GraphQLDirective({
1040
- name: mergeDirectiveName,
1041
- locations: ['FIELD_DEFINITION'],
1042
- args: {
1043
- argsExpr: { type: graphql.GraphQLString },
1044
- keyArg: { type: graphql.GraphQLString },
1045
- keyField: { type: graphql.GraphQLString },
1046
- key: { type: new graphql.GraphQLList(new graphql.GraphQLNonNull(graphql.GraphQLString)) },
1047
- additionalArgs: { type: graphql.GraphQLString },
1048
- },
1049
- });
1050
- var canonicalDirective = new graphql.GraphQLDirective({
1051
- name: canonicalDirectiveName,
1052
- locations: [
1053
- 'OBJECT',
1054
- 'INTERFACE',
1055
- 'INPUT_OBJECT',
1056
- 'UNION',
1057
- 'ENUM',
1058
- 'SCALAR',
1059
- 'FIELD_DEFINITION',
1060
- 'INPUT_FIELD_DEFINITION',
1061
- ],
1062
- });
1063
- var allStitchingDirectivesTypeDefs = [
1064
- keyDirectiveTypeDefs,
1065
- computedDirectiveTypeDefs,
1066
- mergeDirectiveTypeDefs,
1067
- canonicalDirectiveTypeDefs,
1068
- ].join('\n');
1069
- return {
1070
- keyDirectiveTypeDefs: keyDirectiveTypeDefs,
1071
- computedDirectiveTypeDefs: computedDirectiveTypeDefs,
1072
- mergeDirectiveTypeDefs: mergeDirectiveTypeDefs,
1073
- canonicalDirectiveTypeDefs: canonicalDirectiveTypeDefs,
1074
- stitchingDirectivesTypeDefs: allStitchingDirectivesTypeDefs,
1075
- allStitchingDirectivesTypeDefs: allStitchingDirectivesTypeDefs,
1076
- keyDirective: keyDirective,
1077
- computedDirective: computedDirective,
1078
- mergeDirective: mergeDirective,
1079
- canonicalDirective: canonicalDirective,
1080
- allStitchingDirectives: [keyDirective, computedDirective, mergeDirective, canonicalDirective],
1081
- stitchingDirectivesValidator: stitchingDirectivesValidator(finalOptions),
1082
- stitchingDirectivesTransformer: stitchingDirectivesTransformer(finalOptions),
1083
- };
1084
- }
1085
-
1086
- // Taken from https://github.com/gmac/federation-to-stitching-sdl/blob/main/index.js
1087
- var extensionKind = /Extension$/;
1088
- var entityKinds = [
1089
- graphql.Kind.OBJECT_TYPE_DEFINITION,
1090
- graphql.Kind.OBJECT_TYPE_EXTENSION,
1091
- graphql.Kind.INTERFACE_TYPE_DEFINITION,
1092
- graphql.Kind.INTERFACE_TYPE_EXTENSION,
1093
- ];
1094
- function isEntityKind(def) {
1095
- return entityKinds.includes(def.kind);
1096
- }
1097
- function getQueryTypeDef(definitions) {
1098
- var _a;
1099
- var schemaDef = definitions.find(function (def) { return def.kind === graphql.Kind.SCHEMA_DEFINITION; });
1100
- var typeName = schemaDef
1101
- ? (_a = schemaDef.operationTypes.find(function (_a) {
1102
- var operation = _a.operation;
1103
- return operation === 'query';
1104
- })) === null || _a === void 0 ? void 0 : _a.type.name.value
1105
- : 'Query';
1106
- return definitions.find(function (def) { return def.kind === graphql.Kind.OBJECT_TYPE_DEFINITION && def.name.value === typeName; });
1107
- }
1108
- // Federation services are actually fairly complex,
1109
- // as the `buildFederatedSchema` helper does a fair amount
1110
- // of hidden work to setup the Federation schema specification:
1111
- // https://www.apollographql.com/docs/federation/federation-spec/#federation-schema-specification
1112
- function federationToStitchingSDL(federationSDL, stitchingConfig) {
1113
- if (stitchingConfig === void 0) { stitchingConfig = stitchingDirectives(); }
1114
- var doc = graphql.parse(federationSDL);
1115
- var entityTypes = [];
1116
- var baseTypeNames = doc.definitions.reduce(function (memo, typeDef) {
1117
- if (!extensionKind.test(typeDef.kind) && 'name' in typeDef && typeDef.name) {
1118
- memo[typeDef.name.value] = true;
1119
- }
1120
- return memo;
1121
- }, {});
1122
- doc.definitions.forEach(function (typeDef) {
1123
- var _a, _b, _c;
1124
- // Un-extend all types (remove "extends" keywords)...
1125
- // extended types are invalid GraphQL without a local base type to extend from.
1126
- // Stitching merges flat types in lieu of hierarchical extensions.
1127
- if (extensionKind.test(typeDef.kind) && 'name' in typeDef && typeDef.name && !baseTypeNames[typeDef.name.value]) {
1128
- typeDef.kind = typeDef.kind.replace(extensionKind, 'Definition');
1129
- }
1130
- if (!isEntityKind(typeDef))
1131
- return;
1132
- // Find object definitions with "@key" directives;
1133
- // these are federated entities that get turned into merged types.
1134
- var keyDirs = [];
1135
- var otherDirs = [];
1136
- (_a = typeDef.directives) === null || _a === void 0 ? void 0 : _a.forEach(function (dir) {
1137
- if (dir.name.value === 'key') {
1138
- keyDirs.push(dir);
1139
- }
1140
- else {
1141
- otherDirs.push(dir);
1142
- }
1143
- });
1144
- if (!keyDirs.length)
1145
- return;
1146
- // Setup stitching MergedTypeConfig for all federated entities:
1147
- var selectionSet = "{ " + keyDirs.map(function (dir) { return dir.arguments[0].value.value; }).join(' ') + " }";
1148
- var keyFields = graphql.parse(selectionSet).definitions[0].selectionSet.selections.map(function (sel) { return sel.name.value; });
1149
- var keyDir = keyDirs[0];
1150
- keyDir.name.value = stitchingConfig.keyDirective.name;
1151
- keyDir.arguments[0].name.value = 'selectionSet';
1152
- keyDir.arguments[0].value.value = selectionSet;
1153
- typeDef.directives = tslib.__spreadArray([keyDir], tslib.__read(otherDirs), false);
1154
- // Remove non-key "@external" fields from the type...
1155
- // the stitching query planner expects services to only publish their own fields.
1156
- // This makes "@provides" moot because the query planner can automate the logic.
1157
- typeDef.fields = (_b = typeDef.fields) === null || _b === void 0 ? void 0 : _b.filter(function (fieldDef) {
1158
- var _a;
1159
- return (keyFields.includes(fieldDef.name.value) || !((_a = fieldDef.directives) === null || _a === void 0 ? void 0 : _a.find(function (dir) { return dir.name.value === 'external'; })));
1160
- });
1161
- // Discard remaining "@external" directives and any "@provides" directives
1162
- (_c = typeDef.fields) === null || _c === void 0 ? void 0 : _c.forEach(function (fieldDef) {
1163
- fieldDef.directives = fieldDef.directives.filter(function (dir) { return !/^(external|provides)$/.test(dir.name.value); });
1164
- fieldDef.directives.forEach(function (dir) {
1165
- if (dir.name.value === 'requires') {
1166
- dir.name.value = stitchingConfig.computedDirective.name;
1167
- dir.arguments[0].name.value = 'selectionSet';
1168
- dir.arguments[0].value.value = "{ " + dir.arguments[0].value.value + " }";
1169
- }
1170
- });
1171
- });
1172
- if (typeDef.kind === graphql.Kind.OBJECT_TYPE_DEFINITION || typeDef.kind === graphql.Kind.OBJECT_TYPE_EXTENSION) {
1173
- entityTypes.push(typeDef.name.value);
1174
- }
1175
- });
1176
- // Federation service SDLs are incomplete because they omit the federation spec itself...
1177
- // (https://www.apollographql.com/docs/federation/federation-spec/#federation-schema-specification)
1178
- // To make federation SDLs into valid and parsable GraphQL schemas,
1179
- // we must fill in the missing details from the specification.
1180
- if (entityTypes.length) {
1181
- var queryDef = getQueryTypeDef(doc.definitions);
1182
- var entitiesSchema = graphql.parse(/* GraphQL */ "\n scalar _Any\n union _Entity = " + entityTypes.filter(function (v, i, a) { return a.indexOf(v) === i; }).join(' | ') + "\n type Query { _entities(representations: [_Any!]!): [_Entity]! @" + stitchingConfig.mergeDirective.name + " }\n ").definitions;
1183
- doc.definitions.push(entitiesSchema[0]);
1184
- doc.definitions.push(entitiesSchema[1]);
1185
- if (queryDef) {
1186
- queryDef.fields.push(entitiesSchema[2].fields[0]);
1187
- }
1188
- else {
1189
- doc.definitions.push(entitiesSchema[2]);
1190
- }
1191
- }
1192
- return [stitchingConfig.stitchingDirectivesTypeDefs, graphql.print(doc)].join('\n');
1193
- }
1194
-
1195
- exports.federationToStitchingSDL = federationToStitchingSDL;
1196
- exports.stitchingDirectives = stitchingDirectives;