UNPKG

80.3 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7const graphql = require('graphql');
8const utils = require('@graphql-tools/utils');
9const delegate = require('@graphql-tools/delegate');
10const tslib = require('tslib');
11const isPromise = _interopDefault(require('is-promise'));
12
13function generateProxyingResolvers(subschemaConfig) {
14 var _a;
15 const targetSchema = subschemaConfig.schema;
16 const createProxyingResolver = (_a = subschemaConfig.createProxyingResolver) !== null && _a !== void 0 ? _a : defaultCreateProxyingResolver;
17 const transformedSchema = delegate.applySchemaTransforms(targetSchema, subschemaConfig);
18 const operationTypes = {
19 query: targetSchema.getQueryType(),
20 mutation: targetSchema.getMutationType(),
21 subscription: targetSchema.getSubscriptionType(),
22 };
23 const resolvers = {};
24 Object.keys(operationTypes).forEach((operation) => {
25 const rootType = operationTypes[operation];
26 if (rootType != null) {
27 const typeName = rootType.name;
28 const fields = rootType.getFields();
29 resolvers[typeName] = {};
30 Object.keys(fields).forEach(fieldName => {
31 const proxyingResolver = createProxyingResolver({
32 subschemaConfig,
33 transformedSchema,
34 operation,
35 fieldName,
36 });
37 const finalResolver = createPossiblyNestedProxyingResolver(subschemaConfig, proxyingResolver);
38 if (operation === 'subscription') {
39 resolvers[typeName][fieldName] = {
40 subscribe: finalResolver,
41 resolve: (payload, _, __, { fieldName: targetFieldName }) => payload[targetFieldName],
42 };
43 }
44 else {
45 resolvers[typeName][fieldName] = {
46 resolve: finalResolver,
47 };
48 }
49 });
50 }
51 });
52 return resolvers;
53}
54function createPossiblyNestedProxyingResolver(subschemaConfig, proxyingResolver) {
55 return (parent, args, context, info) => {
56 if (parent != null) {
57 const responseKey = utils.getResponseKeyFromInfo(info);
58 // Check to see if the parent contains a proxied result
59 if (delegate.isExternalObject(parent)) {
60 const unpathedErrors = delegate.getUnpathedErrors(parent);
61 const subschema = delegate.getSubschema(parent, responseKey);
62 // If there is a proxied result from this subschema, return it
63 // This can happen even for a root field when the root type ia
64 // also nested as a field within a different type.
65 if (subschemaConfig === subschema && parent[responseKey] !== undefined) {
66 return delegate.resolveExternalValue(parent[responseKey], unpathedErrors, subschema, context, info);
67 }
68 }
69 }
70 return proxyingResolver(parent, args, context, info);
71 };
72}
73function defaultCreateProxyingResolver({ subschemaConfig, operation, transformedSchema, }) {
74 return (_parent, _args, context, info) => delegate.delegateToSchema({
75 schema: subschemaConfig,
76 operation,
77 context,
78 info,
79 transformedSchema,
80 });
81}
82
83function wrapSchema(subschemaConfig) {
84 const targetSchema = subschemaConfig.schema;
85 const proxyingResolvers = generateProxyingResolvers(subschemaConfig);
86 const schema = createWrappingSchema(targetSchema, proxyingResolvers);
87 const transformedSchema = delegate.applySchemaTransforms(schema, subschemaConfig);
88 return delegate.applySchemaTransforms(schema, subschemaConfig, transformedSchema);
89}
90function createWrappingSchema(schema, proxyingResolvers) {
91 return utils.mapSchema(schema, {
92 [utils.MapperKind.ROOT_OBJECT]: type => {
93 const config = type.toConfig();
94 const fieldConfigMap = config.fields;
95 Object.keys(fieldConfigMap).forEach(fieldName => {
96 fieldConfigMap[fieldName] = {
97 ...fieldConfigMap[fieldName],
98 ...proxyingResolvers[type.name][fieldName],
99 };
100 });
101 return new graphql.GraphQLObjectType(config);
102 },
103 [utils.MapperKind.OBJECT_TYPE]: type => {
104 const config = type.toConfig();
105 config.isTypeOf = undefined;
106 Object.keys(config.fields).forEach(fieldName => {
107 config.fields[fieldName].resolve = delegate.defaultMergedResolver;
108 config.fields[fieldName].subscribe = null;
109 });
110 return new graphql.GraphQLObjectType(config);
111 },
112 [utils.MapperKind.INTERFACE_TYPE]: type => {
113 const config = type.toConfig();
114 delete config.resolveType;
115 return new graphql.GraphQLInterfaceType(config);
116 },
117 [utils.MapperKind.UNION_TYPE]: type => {
118 const config = type.toConfig();
119 delete config.resolveType;
120 return new graphql.GraphQLUnionType(config);
121 },
122 });
123}
124
125class RenameTypes {
126 constructor(renamer, options) {
127 this.renamer = renamer;
128 this.map = Object.create(null);
129 this.reverseMap = Object.create(null);
130 const { renameBuiltins = false, renameScalars = true } = options != null ? options : {};
131 this.renameBuiltins = renameBuiltins;
132 this.renameScalars = renameScalars;
133 }
134 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
135 return utils.mapSchema(originalWrappingSchema, {
136 [utils.MapperKind.TYPE]: (type) => {
137 if (graphql.isSpecifiedScalarType(type) && !this.renameBuiltins) {
138 return undefined;
139 }
140 if (graphql.isScalarType(type) && !this.renameScalars) {
141 return undefined;
142 }
143 const oldName = type.name;
144 const newName = this.renamer(oldName);
145 if (newName !== undefined && newName !== oldName) {
146 this.map[oldName] = newName;
147 this.reverseMap[newName] = oldName;
148 return utils.renameType(type, newName);
149 }
150 },
151 [utils.MapperKind.ROOT_OBJECT]() {
152 return undefined;
153 },
154 });
155 }
156 transformRequest(originalRequest, _delegationContext, _transformationContext) {
157 const document = graphql.visit(originalRequest.document, {
158 [graphql.Kind.NAMED_TYPE]: (node) => {
159 const name = node.name.value;
160 if (name in this.reverseMap) {
161 return {
162 ...node,
163 name: {
164 kind: graphql.Kind.NAME,
165 value: this.reverseMap[name],
166 },
167 };
168 }
169 },
170 });
171 return {
172 ...originalRequest,
173 document,
174 };
175 }
176 transformResult(originalResult, _delegationContext, _transformationContext) {
177 return {
178 ...originalResult,
179 data: utils.visitData(originalResult.data, object => {
180 const typeName = object === null || object === void 0 ? void 0 : object.__typename;
181 if (typeName != null && typeName in this.map) {
182 object.__typename = this.map[typeName];
183 }
184 return object;
185 }),
186 };
187 }
188}
189
190class FilterTypes {
191 constructor(filter) {
192 this.filter = filter;
193 }
194 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
195 return utils.mapSchema(originalWrappingSchema, {
196 [utils.MapperKind.TYPE]: (type) => {
197 if (this.filter(type)) {
198 return undefined;
199 }
200 return null;
201 },
202 });
203 }
204}
205
206class RenameRootTypes {
207 constructor(renamer) {
208 this.renamer = renamer;
209 this.map = Object.create(null);
210 this.reverseMap = Object.create(null);
211 }
212 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
213 return utils.mapSchema(originalWrappingSchema, {
214 [utils.MapperKind.ROOT_OBJECT]: type => {
215 const oldName = type.name;
216 const newName = this.renamer(oldName);
217 if (newName !== undefined && newName !== oldName) {
218 this.map[oldName] = newName;
219 this.reverseMap[newName] = oldName;
220 return utils.renameType(type, newName);
221 }
222 },
223 });
224 }
225 transformRequest(originalRequest, _delegationContext, _transformationContext) {
226 const document = graphql.visit(originalRequest.document, {
227 [graphql.Kind.NAMED_TYPE]: (node) => {
228 const name = node.name.value;
229 if (name in this.reverseMap) {
230 return {
231 ...node,
232 name: {
233 kind: graphql.Kind.NAME,
234 value: this.reverseMap[name],
235 },
236 };
237 }
238 },
239 });
240 return {
241 ...originalRequest,
242 document,
243 };
244 }
245 transformResult(originalResult, _delegationContext, _transformationContext) {
246 return {
247 ...originalResult,
248 data: utils.visitData(originalResult.data, object => {
249 const typeName = object === null || object === void 0 ? void 0 : object.__typename;
250 if (typeName != null && typeName in this.map) {
251 object.__typename = this.map[typeName];
252 }
253 return object;
254 }),
255 };
256 }
257}
258
259class TransformCompositeFields {
260 constructor(fieldTransformer, fieldNodeTransformer, dataTransformer, errorsTransformer) {
261 this.fieldTransformer = fieldTransformer;
262 this.fieldNodeTransformer = fieldNodeTransformer;
263 this.dataTransformer = dataTransformer;
264 this.errorsTransformer = errorsTransformer;
265 this.mapping = {};
266 }
267 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
268 var _a;
269 this.transformedSchema = utils.mapSchema(originalWrappingSchema, {
270 [utils.MapperKind.COMPOSITE_FIELD]: (fieldConfig, fieldName, typeName) => {
271 const transformedField = this.fieldTransformer(typeName, fieldName, fieldConfig);
272 if (Array.isArray(transformedField)) {
273 const newFieldName = transformedField[0];
274 if (newFieldName !== fieldName) {
275 if (!(typeName in this.mapping)) {
276 this.mapping[typeName] = {};
277 }
278 this.mapping[typeName][newFieldName] = fieldName;
279 }
280 }
281 return transformedField;
282 },
283 });
284 this.typeInfo = new graphql.TypeInfo(this.transformedSchema);
285 this.subscriptionTypeName = (_a = originalWrappingSchema.getSubscriptionType()) === null || _a === void 0 ? void 0 : _a.name;
286 return this.transformedSchema;
287 }
288 transformRequest(originalRequest, _delegationContext, transformationContext) {
289 const document = originalRequest.document;
290 const fragments = Object.create(null);
291 document.definitions.forEach(def => {
292 if (def.kind === graphql.Kind.FRAGMENT_DEFINITION) {
293 fragments[def.name.value] = def;
294 }
295 });
296 return {
297 ...originalRequest,
298 document: this.transformDocument(document, fragments, transformationContext),
299 };
300 }
301 transformResult(result, _delegationContext, transformationContext) {
302 if (this.dataTransformer != null) {
303 result.data = utils.visitData(result.data, value => this.dataTransformer(value, transformationContext));
304 }
305 if (this.errorsTransformer != null) {
306 result.errors = this.errorsTransformer(result.errors, transformationContext);
307 }
308 return result;
309 }
310 transformDocument(document, fragments, transformationContext) {
311 return graphql.visit(document, graphql.visitWithTypeInfo(this.typeInfo, {
312 leave: {
313 [graphql.Kind.SELECTION_SET]: node => this.transformSelectionSet(node, this.typeInfo, fragments, transformationContext),
314 },
315 }));
316 }
317 transformSelectionSet(node, typeInfo, fragments, transformationContext) {
318 const parentType = typeInfo.getParentType();
319 if (parentType == null) {
320 return undefined;
321 }
322 const parentTypeName = parentType.name;
323 let newSelections = [];
324 node.selections.forEach(selection => {
325 var _a, _b;
326 if (selection.kind !== graphql.Kind.FIELD) {
327 newSelections.push(selection);
328 return;
329 }
330 const newName = selection.name.value;
331 // See https://github.com/ardatan/graphql-tools/issues/2282
332 if ((this.dataTransformer != null || this.errorsTransformer != null) &&
333 (this.subscriptionTypeName == null || parentTypeName !== this.subscriptionTypeName)) {
334 newSelections.push({
335 kind: graphql.Kind.FIELD,
336 name: {
337 kind: graphql.Kind.NAME,
338 value: '__typename',
339 },
340 });
341 }
342 let transformedSelection;
343 if (this.fieldNodeTransformer == null) {
344 transformedSelection = selection;
345 }
346 else {
347 transformedSelection = this.fieldNodeTransformer(parentTypeName, newName, selection, fragments, transformationContext);
348 transformedSelection = transformedSelection === undefined ? selection : transformedSelection;
349 }
350 if (transformedSelection == null) {
351 return;
352 }
353 else if (Array.isArray(transformedSelection)) {
354 newSelections = newSelections.concat(transformedSelection);
355 return;
356 }
357 else if (transformedSelection.kind !== graphql.Kind.FIELD) {
358 newSelections.push(transformedSelection);
359 return;
360 }
361 const typeMapping = this.mapping[parentTypeName];
362 if (typeMapping == null) {
363 newSelections.push(transformedSelection);
364 return;
365 }
366 const oldName = this.mapping[parentTypeName][newName];
367 if (oldName == null) {
368 newSelections.push(transformedSelection);
369 return;
370 }
371 newSelections.push({
372 ...transformedSelection,
373 name: {
374 kind: graphql.Kind.NAME,
375 value: oldName,
376 },
377 alias: {
378 kind: graphql.Kind.NAME,
379 value: (_b = (_a = transformedSelection.alias) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : newName,
380 },
381 });
382 });
383 return {
384 ...node,
385 selections: newSelections,
386 };
387 }
388}
389
390class TransformObjectFields {
391 constructor(objectFieldTransformer, fieldNodeTransformer) {
392 this.objectFieldTransformer = objectFieldTransformer;
393 this.fieldNodeTransformer = fieldNodeTransformer;
394 }
395 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
396 const compositeToObjectFieldTransformer = (typeName, fieldName, fieldConfig) => {
397 if (graphql.isObjectType(originalWrappingSchema.getType(typeName))) {
398 return this.objectFieldTransformer(typeName, fieldName, fieldConfig);
399 }
400 return undefined;
401 };
402 this.transformer = new TransformCompositeFields(compositeToObjectFieldTransformer, this.fieldNodeTransformer);
403 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
404 }
405 transformRequest(originalRequest, delegationContext, transformationContext) {
406 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
407 }
408 transformResult(originalResult, delegationContext, transformationContext) {
409 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
410 }
411}
412
413class TransformRootFields {
414 constructor(rootFieldTransformer, fieldNodeTransformer) {
415 this.rootFieldTransformer = rootFieldTransformer;
416 this.fieldNodeTransformer = fieldNodeTransformer;
417 }
418 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
419 var _a, _b, _c;
420 const queryTypeName = (_a = originalWrappingSchema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name;
421 const mutationTypeName = (_b = originalWrappingSchema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name;
422 const subscriptionTypeName = (_c = originalWrappingSchema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name;
423 const rootToObjectFieldTransformer = (typeName, fieldName, fieldConfig) => {
424 if (typeName === queryTypeName) {
425 return this.rootFieldTransformer('Query', fieldName, fieldConfig);
426 }
427 if (typeName === mutationTypeName) {
428 return this.rootFieldTransformer('Mutation', fieldName, fieldConfig);
429 }
430 if (typeName === subscriptionTypeName) {
431 return this.rootFieldTransformer('Subscription', fieldName, fieldConfig);
432 }
433 return undefined;
434 };
435 this.transformer = new TransformObjectFields(rootToObjectFieldTransformer, this.fieldNodeTransformer);
436 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
437 }
438 transformRequest(originalRequest, delegationContext, transformationContext) {
439 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
440 }
441 transformResult(originalResult, delegationContext, transformationContext) {
442 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
443 }
444}
445
446class RenameRootFields {
447 constructor(renamer) {
448 this.transformer = new TransformRootFields((operation, fieldName, fieldConfig) => [renamer(operation, fieldName, fieldConfig), fieldConfig]);
449 }
450 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
451 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
452 }
453 transformRequest(originalRequest, delegationContext, transformationContext) {
454 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
455 }
456}
457
458class FilterRootFields {
459 constructor(filter) {
460 this.transformer = new TransformRootFields((operation, fieldName, fieldConfig) => {
461 if (filter(operation, fieldName, fieldConfig)) {
462 return undefined;
463 }
464 return null;
465 });
466 }
467 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
468 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
469 }
470}
471
472class RenameObjectFields {
473 constructor(renamer) {
474 this.transformer = new TransformObjectFields((typeName, fieldName, fieldConfig) => [
475 renamer(typeName, fieldName, fieldConfig),
476 fieldConfig,
477 ]);
478 }
479 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
480 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
481 }
482 transformRequest(originalRequest, delegationContext, transformationContext) {
483 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
484 }
485}
486
487class FilterObjectFields {
488 constructor(filter) {
489 this.transformer = new TransformObjectFields((typeName, fieldName, fieldConfig) => filter(typeName, fieldName, fieldConfig) ? undefined : null);
490 }
491 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
492 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
493 }
494}
495
496class TransformInterfaceFields {
497 constructor(interfaceFieldTransformer, fieldNodeTransformer) {
498 this.interfaceFieldTransformer = interfaceFieldTransformer;
499 this.fieldNodeTransformer = fieldNodeTransformer;
500 }
501 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
502 const compositeToObjectFieldTransformer = (typeName, fieldName, fieldConfig) => {
503 if (graphql.isInterfaceType(originalWrappingSchema.getType(typeName))) {
504 return this.interfaceFieldTransformer(typeName, fieldName, fieldConfig);
505 }
506 return undefined;
507 };
508 this.transformer = new TransformCompositeFields(compositeToObjectFieldTransformer, this.fieldNodeTransformer);
509 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
510 }
511 transformRequest(originalRequest, delegationContext, transformationContext) {
512 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
513 }
514 transformResult(originalResult, delegationContext, transformationContext) {
515 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
516 }
517}
518
519class RenameInterfaceFields {
520 constructor(renamer) {
521 this.transformer = new TransformInterfaceFields((typeName, fieldName, fieldConfig) => [
522 renamer(typeName, fieldName, fieldConfig),
523 fieldConfig,
524 ]);
525 }
526 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
527 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
528 }
529 transformRequest(originalRequest, delegationContext, transformationContext) {
530 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
531 }
532}
533
534class FilterInterfaceFields {
535 constructor(filter) {
536 this.transformer = new TransformInterfaceFields((typeName, fieldName, fieldConfig) => filter(typeName, fieldName, fieldConfig) ? undefined : null);
537 }
538 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
539 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
540 }
541}
542
543class TransformInputObjectFields {
544 constructor(inputFieldTransformer, inputFieldNodeTransformer, inputObjectNodeTransformer) {
545 this.inputFieldTransformer = inputFieldTransformer;
546 this.inputFieldNodeTransformer = inputFieldNodeTransformer;
547 this.inputObjectNodeTransformer = inputObjectNodeTransformer;
548 this.mapping = {};
549 }
550 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
551 this.transformedSchema = utils.mapSchema(originalWrappingSchema, {
552 [utils.MapperKind.INPUT_OBJECT_FIELD]: (inputFieldConfig, fieldName, typeName) => {
553 const transformedInputField = this.inputFieldTransformer(typeName, fieldName, inputFieldConfig);
554 if (Array.isArray(transformedInputField)) {
555 const newFieldName = transformedInputField[0];
556 if (newFieldName !== fieldName) {
557 if (!(typeName in this.mapping)) {
558 this.mapping[typeName] = {};
559 }
560 this.mapping[typeName][newFieldName] = fieldName;
561 }
562 }
563 return transformedInputField;
564 },
565 });
566 return this.transformedSchema;
567 }
568 transformRequest(originalRequest, delegationContext, _transformationContext) {
569 const variableValues = originalRequest.variables;
570 const fragments = Object.create(null);
571 const operations = [];
572 originalRequest.document.definitions.forEach(def => {
573 if (def.kind === graphql.Kind.OPERATION_DEFINITION) {
574 operations.push(def);
575 }
576 else {
577 fragments[def.name.value] = def;
578 }
579 });
580 operations.forEach(def => {
581 const variableDefs = def.variableDefinitions;
582 if (variableDefs != null) {
583 variableDefs.forEach(variableDef => {
584 const varName = variableDef.variable.name.value;
585 // requirement for 'as NamedTypeNode' appears to be a bug within types, as function should take any TypeNode
586 const varType = graphql.typeFromAST(delegationContext.transformedSchema, variableDef.type);
587 variableValues[varName] = utils.transformInputValue(varType, variableValues[varName], undefined, (type, originalValue) => {
588 const newValue = Object.create(null);
589 const fields = type.getFields();
590 Object.keys(originalValue).forEach(key => {
591 var _a;
592 const field = fields[key];
593 if (field != null) {
594 const newFieldName = (_a = this.mapping[type.name]) === null || _a === void 0 ? void 0 : _a[field.name];
595 if (newFieldName != null) {
596 newValue[newFieldName] = originalValue[field.name];
597 }
598 else {
599 newValue[field.name] = originalValue[field.name];
600 }
601 }
602 });
603 return newValue;
604 });
605 });
606 }
607 });
608 originalRequest.document.definitions
609 .filter(def => def.kind === graphql.Kind.FRAGMENT_DEFINITION)
610 .forEach(def => {
611 fragments[def.name.value] = def;
612 });
613 const document = this.transformDocument(originalRequest.document, this.mapping, this.inputFieldNodeTransformer, this.inputObjectNodeTransformer, originalRequest, delegationContext);
614 return {
615 ...originalRequest,
616 document,
617 variables: variableValues,
618 };
619 }
620 transformDocument(document, mapping, inputFieldNodeTransformer, inputObjectNodeTransformer, request, delegationContext) {
621 const typeInfo = new graphql.TypeInfo(this.transformedSchema);
622 const newDocument = graphql.visit(document, graphql.visitWithTypeInfo(typeInfo, {
623 leave: {
624 [graphql.Kind.OBJECT]: (node) => {
625 const parentType = typeInfo.getInputType();
626 if (parentType != null) {
627 const parentTypeName = parentType.name;
628 const newInputFields = [];
629 node.fields.forEach(inputField => {
630 const newName = inputField.name.value;
631 const transformedInputField = inputFieldNodeTransformer != null
632 ? inputFieldNodeTransformer(parentTypeName, newName, inputField, request, delegationContext)
633 : inputField;
634 if (Array.isArray(transformedInputField)) {
635 transformedInputField.forEach(individualTransformedInputField => {
636 const typeMapping = mapping[parentTypeName];
637 if (typeMapping == null) {
638 newInputFields.push(individualTransformedInputField);
639 return;
640 }
641 const oldName = typeMapping[newName];
642 if (oldName == null) {
643 newInputFields.push(individualTransformedInputField);
644 return;
645 }
646 newInputFields.push({
647 ...individualTransformedInputField,
648 name: {
649 ...individualTransformedInputField.name,
650 value: oldName,
651 },
652 });
653 });
654 return;
655 }
656 const typeMapping = mapping[parentTypeName];
657 if (typeMapping == null) {
658 newInputFields.push(transformedInputField);
659 return;
660 }
661 const oldName = typeMapping[newName];
662 if (oldName == null) {
663 newInputFields.push(transformedInputField);
664 return;
665 }
666 newInputFields.push({
667 ...transformedInputField,
668 name: {
669 ...transformedInputField.name,
670 value: oldName,
671 },
672 });
673 });
674 const newNode = {
675 ...node,
676 fields: newInputFields,
677 };
678 return inputObjectNodeTransformer != null
679 ? inputObjectNodeTransformer(parentTypeName, newNode, request, delegationContext)
680 : newNode;
681 }
682 },
683 },
684 }));
685 return newDocument;
686 }
687}
688
689class RenameInputObjectFields {
690 constructor(renamer) {
691 this.renamer = renamer;
692 this.transformer = new TransformInputObjectFields((typeName, inputFieldName, inputFieldConfig) => {
693 const newName = renamer(typeName, inputFieldName, inputFieldConfig);
694 if (newName !== undefined && newName !== inputFieldName) {
695 return [renamer(typeName, inputFieldName, inputFieldConfig), inputFieldConfig];
696 }
697 }, (typeName, inputFieldName, inputFieldNode) => {
698 if (!(typeName in this.reverseMap)) {
699 return inputFieldNode;
700 }
701 const inputFieldNameMap = this.reverseMap[typeName];
702 if (!(inputFieldName in inputFieldNameMap)) {
703 return inputFieldNode;
704 }
705 return {
706 ...inputFieldNode,
707 name: {
708 ...inputFieldNode.name,
709 value: inputFieldNameMap[inputFieldName],
710 },
711 };
712 });
713 this.reverseMap = Object.create(null);
714 }
715 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
716 utils.mapSchema(originalWrappingSchema, {
717 [utils.MapperKind.INPUT_OBJECT_FIELD]: (inputFieldConfig, fieldName, typeName) => {
718 const newName = this.renamer(typeName, fieldName, inputFieldConfig);
719 if (newName !== undefined && newName !== fieldName) {
720 if (this.reverseMap[typeName] == null) {
721 this.reverseMap[typeName] = Object.create(null);
722 }
723 this.reverseMap[typeName][newName] = fieldName;
724 }
725 return undefined;
726 },
727 [utils.MapperKind.ROOT_OBJECT]() {
728 return undefined;
729 },
730 });
731 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
732 }
733 transformRequest(originalRequest, delegationContext, transformationContext) {
734 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
735 }
736}
737
738class FilterInputObjectFields {
739 constructor(filter, inputObjectNodeTransformer) {
740 this.transformer = new TransformInputObjectFields((typeName, fieldName, inputFieldConfig) => filter(typeName, fieldName, inputFieldConfig) ? undefined : null, undefined, inputObjectNodeTransformer);
741 }
742 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
743 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
744 }
745 transformRequest(originalRequest, delegationContext, transformationContext) {
746 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
747 }
748}
749
750class MapLeafValues {
751 constructor(inputValueTransformer, outputValueTransformer) {
752 this.inputValueTransformer = inputValueTransformer;
753 this.outputValueTransformer = outputValueTransformer;
754 this.resultVisitorMap = Object.create(null);
755 }
756 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
757 this.originalWrappingSchema = originalWrappingSchema;
758 const typeMap = originalWrappingSchema.getTypeMap();
759 Object.keys(typeMap).forEach(typeName => {
760 const type = typeMap[typeName];
761 if (!typeName.startsWith('__')) {
762 if (graphql.isLeafType(type)) {
763 this.resultVisitorMap[typeName] = (value) => this.outputValueTransformer(typeName, value);
764 }
765 }
766 });
767 this.typeInfo = new graphql.TypeInfo(originalWrappingSchema);
768 return originalWrappingSchema;
769 }
770 transformRequest(originalRequest, _delegationContext, transformationContext) {
771 const document = originalRequest.document;
772 const variableValues = originalRequest.variables;
773 const operations = document.definitions.filter(def => def.kind === graphql.Kind.OPERATION_DEFINITION);
774 const fragments = document.definitions.filter(def => def.kind === graphql.Kind.FRAGMENT_DEFINITION);
775 const newOperations = this.transformOperations(operations, variableValues);
776 const transformedRequest = {
777 ...originalRequest,
778 document: {
779 ...document,
780 definitions: [...newOperations, ...fragments],
781 },
782 variables: variableValues,
783 };
784 transformationContext.transformedRequest = transformedRequest;
785 return transformedRequest;
786 }
787 transformResult(originalResult, _delegationContext, transformationContext) {
788 return utils.visitResult(originalResult, transformationContext.transformedRequest, this.originalWrappingSchema, this.resultVisitorMap);
789 }
790 transformOperations(operations, variableValues) {
791 return operations.map((operation) => {
792 const variableDefinitionMap = operation.variableDefinitions.reduce((prev, def) => ({
793 ...prev,
794 [def.variable.name.value]: def,
795 }), {});
796 const newOperation = graphql.visit(operation, graphql.visitWithTypeInfo(this.typeInfo, {
797 [graphql.Kind.FIELD]: node => this.transformFieldNode(node, variableDefinitionMap, variableValues),
798 }));
799 return {
800 ...newOperation,
801 variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
802 };
803 });
804 }
805 transformFieldNode(field, variableDefinitionMap, variableValues) {
806 const targetField = this.typeInfo.getFieldDef();
807 if (!targetField.name.startsWith('__')) {
808 const argumentNodes = field.arguments;
809 if (argumentNodes != null) {
810 const argumentNodeMap = argumentNodes.reduce((prev, argument) => ({
811 ...prev,
812 [argument.name.value]: argument,
813 }), Object.create(null));
814 targetField.args.forEach((argument) => {
815 const argName = argument.name;
816 const argType = argument.type;
817 const argumentNode = argumentNodeMap[argName];
818 const argValue = argumentNode === null || argumentNode === void 0 ? void 0 : argumentNode.value;
819 let value;
820 if (argValue != null) {
821 value = graphql.valueFromAST(argValue, argType, variableValues);
822 }
823 utils.updateArgument(argName, argType, argumentNodeMap, variableDefinitionMap, variableValues, utils.transformInputValue(argType, value, (t, v) => {
824 const newValue = this.inputValueTransformer(t.name, v);
825 return newValue === undefined ? v : newValue;
826 }));
827 });
828 return {
829 ...field,
830 arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
831 };
832 }
833 }
834 }
835}
836
837class TransformEnumValues {
838 constructor(enumValueTransformer, inputValueTransformer, outputValueTransformer) {
839 this.enumValueTransformer = enumValueTransformer;
840 this.mapping = Object.create(null);
841 this.reverseMapping = Object.create(null);
842 this.transformer = new MapLeafValues(generateValueTransformer(inputValueTransformer, this.reverseMapping), generateValueTransformer(outputValueTransformer, this.mapping));
843 }
844 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
845 const mappingSchema = this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
846 this.transformedSchema = utils.mapSchema(mappingSchema, {
847 [utils.MapperKind.ENUM_VALUE]: (valueConfig, typeName, _schema, externalValue) => this.transformEnumValue(typeName, externalValue, valueConfig),
848 });
849 return this.transformedSchema;
850 }
851 transformRequest(originalRequest, delegationContext, transformationContext) {
852 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
853 }
854 transformResult(originalResult, delegationContext, transformationContext) {
855 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
856 }
857 transformEnumValue(typeName, externalValue, enumValueConfig) {
858 const transformedEnumValue = this.enumValueTransformer(typeName, externalValue, enumValueConfig);
859 if (Array.isArray(transformedEnumValue)) {
860 const newExternalValue = transformedEnumValue[0];
861 if (newExternalValue !== externalValue) {
862 if (!(typeName in this.mapping)) {
863 this.mapping[typeName] = Object.create(null);
864 this.reverseMapping[typeName] = Object.create(null);
865 }
866 this.mapping[typeName][externalValue] = newExternalValue;
867 this.reverseMapping[typeName][newExternalValue] = externalValue;
868 }
869 }
870 return transformedEnumValue;
871 }
872}
873function mapEnumValues(typeName, value, mapping) {
874 var _a;
875 const newExternalValue = (_a = mapping[typeName]) === null || _a === void 0 ? void 0 : _a[value];
876 return newExternalValue != null ? newExternalValue : value;
877}
878function generateValueTransformer(valueTransformer, mapping) {
879 if (valueTransformer == null) {
880 return (typeName, value) => mapEnumValues(typeName, value, mapping);
881 }
882 else {
883 return (typeName, value) => mapEnumValues(typeName, valueTransformer(typeName, value), mapping);
884 }
885}
886
887class TransformQuery {
888 constructor({ path, queryTransformer, resultTransformer = result => result, errorPathTransformer = errorPath => [].concat(errorPath), fragments = {}, }) {
889 this.path = path;
890 this.queryTransformer = queryTransformer;
891 this.resultTransformer = resultTransformer;
892 this.errorPathTransformer = errorPathTransformer;
893 this.fragments = fragments;
894 }
895 transformRequest(originalRequest, _delegationContext, _transformationContext) {
896 const pathLength = this.path.length;
897 let index = 0;
898 const document = graphql.visit(originalRequest.document, {
899 [graphql.Kind.FIELD]: {
900 enter: node => {
901 if (index === pathLength || node.name.value !== this.path[index]) {
902 return false;
903 }
904 index++;
905 if (index === pathLength) {
906 const selectionSet = this.queryTransformer(node.selectionSet, this.fragments);
907 return {
908 ...node,
909 selectionSet,
910 };
911 }
912 },
913 leave: () => {
914 index--;
915 },
916 },
917 });
918 return {
919 ...originalRequest,
920 document,
921 };
922 }
923 transformResult(originalResult, _delegationContext, _transformationContext) {
924 const data = this.transformData(originalResult.data);
925 const errors = originalResult.errors;
926 return {
927 data,
928 errors: errors != null ? this.transformErrors(errors) : undefined,
929 };
930 }
931 transformData(data) {
932 const leafIndex = this.path.length - 1;
933 let index = 0;
934 let newData = data;
935 if (newData) {
936 let next = this.path[index];
937 while (index < leafIndex) {
938 if (data[next]) {
939 newData = newData[next];
940 }
941 else {
942 break;
943 }
944 index++;
945 next = this.path[index];
946 }
947 newData[next] = this.resultTransformer(newData[next]);
948 }
949 return newData;
950 }
951 transformErrors(errors) {
952 return errors.map(error => {
953 const path = error.path;
954 let match = true;
955 let index = 0;
956 while (index < this.path.length) {
957 if (path[index] !== this.path[index]) {
958 match = false;
959 break;
960 }
961 index++;
962 }
963 const newPath = match ? path.slice(0, index).concat(this.errorPathTransformer(path.slice(index))) : path;
964 return utils.relocatedError(error, newPath);
965 });
966 }
967}
968
969class FilterObjectFieldDirectives {
970 constructor(filter) {
971 this.filter = filter;
972 }
973 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
974 const transformer = new TransformObjectFields((_typeName, _fieldName, fieldConfig) => {
975 const keepDirectives = fieldConfig.astNode.directives.filter(dir => {
976 const directiveDef = originalWrappingSchema.getDirective(dir.name.value);
977 const directiveValue = directiveDef ? utils.getArgumentValues(directiveDef, dir) : undefined;
978 return this.filter(dir.name.value, directiveValue);
979 });
980 if (keepDirectives.length !== fieldConfig.astNode.directives.length) {
981 fieldConfig = {
982 ...fieldConfig,
983 astNode: {
984 ...fieldConfig.astNode,
985 directives: keepDirectives,
986 },
987 };
988 return fieldConfig;
989 }
990 });
991 return transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
992 }
993}
994
995class RemoveObjectFieldDirectives {
996 constructor(directiveName, args = {}) {
997 this.transformer = new FilterObjectFieldDirectives((dirName, dirValue) => {
998 return !(utils.valueMatchesCriteria(dirName, directiveName) && utils.valueMatchesCriteria(dirValue, args));
999 });
1000 }
1001 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1002 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
1003 }
1004}
1005
1006class RemoveObjectFieldsWithDirective {
1007 constructor(directiveName, args = {}) {
1008 this.directiveName = directiveName;
1009 this.args = args;
1010 }
1011 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1012 const transformer = new FilterObjectFields((_typeName, _fieldName, fieldConfig) => {
1013 const valueMap = utils.getDirectives(originalWrappingSchema, fieldConfig);
1014 return !Object.keys(valueMap).some(directiveName => utils.valueMatchesCriteria(directiveName, this.directiveName) &&
1015 ((Array.isArray(valueMap[directiveName]) &&
1016 valueMap[directiveName].some((value) => utils.valueMatchesCriteria(value, this.args))) ||
1017 utils.valueMatchesCriteria(valueMap[directiveName], this.args)));
1018 });
1019 return transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
1020 }
1021}
1022
1023class RemoveObjectFieldDeprecations {
1024 constructor(reason) {
1025 const args = { reason };
1026 this.removeDirectives = new FilterObjectFieldDirectives((dirName, dirValue) => {
1027 return !(dirName === 'deprecated' && utils.valueMatchesCriteria(dirValue, args));
1028 });
1029 this.removeDeprecations = new TransformObjectFields((_typeName, _fieldName, fieldConfig) => {
1030 if (fieldConfig.deprecationReason && utils.valueMatchesCriteria(fieldConfig.deprecationReason, reason)) {
1031 fieldConfig = { ...fieldConfig };
1032 delete fieldConfig.deprecationReason;
1033 }
1034 return fieldConfig;
1035 });
1036 }
1037 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1038 return this.removeDeprecations.transformSchema(this.removeDirectives.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema), subschemaConfig, transformedSchema);
1039 }
1040}
1041
1042class RemoveObjectFieldsWithDeprecation {
1043 constructor(reason) {
1044 this.transformer = new FilterObjectFields((_typeName, _fieldName, fieldConfig) => {
1045 if (fieldConfig.deprecationReason) {
1046 return !utils.valueMatchesCriteria(fieldConfig.deprecationReason, reason);
1047 }
1048 return true;
1049 });
1050 }
1051 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1052 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
1053 }
1054}
1055
1056class PruneTypes {
1057 constructor(options = {}) {
1058 this.options = options;
1059 }
1060 transformSchema(originalWrappingSchema, _subschemaConfig, _transformedSchema) {
1061 return utils.pruneSchema(originalWrappingSchema, this.options);
1062 }
1063}
1064
1065class MapFields {
1066 constructor(fieldNodeTransformerMap, objectValueTransformerMap, errorsTransformer) {
1067 this.fieldNodeTransformerMap = fieldNodeTransformerMap;
1068 this.objectValueTransformerMap = objectValueTransformerMap;
1069 this.errorsTransformer = errorsTransformer;
1070 }
1071 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1072 var _a;
1073 const subscriptionTypeName = (_a = originalWrappingSchema.getSubscriptionType()) === null || _a === void 0 ? void 0 : _a.name;
1074 this.transformer = new TransformCompositeFields(() => undefined, (typeName, fieldName, fieldNode, fragments, transformationContext) => {
1075 const typeTransformers = this.fieldNodeTransformerMap[typeName];
1076 if (typeTransformers == null) {
1077 return undefined;
1078 }
1079 const fieldNodeTransformer = typeTransformers[fieldName];
1080 if (fieldNodeTransformer == null) {
1081 return undefined;
1082 }
1083 return fieldNodeTransformer(fieldNode, fragments, transformationContext);
1084 }, this.objectValueTransformerMap != null
1085 ? (data, transformationContext) => {
1086 if (data == null) {
1087 return data;
1088 }
1089 let typeName = data.__typename;
1090 if (typeName == null) {
1091 // see https://github.com/ardatan/graphql-tools/issues/2282
1092 typeName = subscriptionTypeName;
1093 if (typeName == null) {
1094 return data;
1095 }
1096 }
1097 const transformer = this.objectValueTransformerMap[typeName];
1098 if (transformer == null) {
1099 return data;
1100 }
1101 return transformer(data, transformationContext);
1102 }
1103 : undefined, this.errorsTransformer != null ? this.errorsTransformer : undefined);
1104 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
1105 }
1106 transformRequest(originalRequest, delegationContext, transformationContext) {
1107 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
1108 }
1109 transformResult(originalResult, delegationContext, transformationContext) {
1110 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
1111 }
1112}
1113
1114class WrapFields {
1115 constructor(outerTypeName, wrappingFieldNames, wrappingTypeNames, fieldNames, prefix = 'gqtld') {
1116 this.outerTypeName = outerTypeName;
1117 this.wrappingFieldNames = wrappingFieldNames;
1118 this.wrappingTypeNames = wrappingTypeNames;
1119 this.numWraps = wrappingFieldNames.length;
1120 this.fieldNames = fieldNames;
1121 const remainingWrappingFieldNames = this.wrappingFieldNames.slice();
1122 const outerMostWrappingFieldName = remainingWrappingFieldNames.shift();
1123 this.transformer = new MapFields({
1124 [outerTypeName]: {
1125 [outerMostWrappingFieldName]: (fieldNode, fragments, transformationContext) => hoistFieldNodes({
1126 fieldNode,
1127 path: remainingWrappingFieldNames,
1128 fieldNames,
1129 fragments,
1130 transformationContext,
1131 prefix,
1132 }),
1133 },
1134 }, {
1135 [outerTypeName]: (value, context) => dehoistValue(value, context),
1136 }, (errors, context) => dehoistErrors(errors, context));
1137 }
1138 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1139 var _a, _b, _c;
1140 const targetFieldConfigMap = utils.selectObjectFields(originalWrappingSchema, this.outerTypeName, !this.fieldNames ? () => true : fieldName => this.fieldNames.includes(fieldName));
1141 const newTargetFieldConfigMap = Object.create(null);
1142 Object.keys(targetFieldConfigMap).forEach(fieldName => {
1143 const field = targetFieldConfigMap[fieldName];
1144 const newField = {
1145 ...field,
1146 resolve: delegate.defaultMergedResolver,
1147 };
1148 newTargetFieldConfigMap[fieldName] = newField;
1149 });
1150 let wrapIndex = this.numWraps - 1;
1151 let wrappingTypeName = this.wrappingTypeNames[wrapIndex];
1152 let wrappingFieldName = this.wrappingFieldNames[wrapIndex];
1153 let newSchema = utils.appendObjectFields(originalWrappingSchema, wrappingTypeName, newTargetFieldConfigMap);
1154 for (wrapIndex--; wrapIndex > -1; wrapIndex--) {
1155 const nextWrappingTypeName = this.wrappingTypeNames[wrapIndex];
1156 newSchema = utils.appendObjectFields(newSchema, nextWrappingTypeName, {
1157 [wrappingFieldName]: {
1158 type: newSchema.getType(wrappingTypeName),
1159 resolve: delegate.defaultMergedResolver,
1160 },
1161 });
1162 wrappingTypeName = nextWrappingTypeName;
1163 wrappingFieldName = this.wrappingFieldNames[wrapIndex];
1164 }
1165 const wrappingRootField = this.outerTypeName === ((_a = originalWrappingSchema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name) ||
1166 this.outerTypeName === ((_b = originalWrappingSchema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name);
1167 let resolve;
1168 if (transformedSchema) {
1169 if (wrappingRootField) {
1170 const targetSchema = subschemaConfig.schema;
1171 const operation = this.outerTypeName === targetSchema.getQueryType().name ? 'query' : 'mutation';
1172 const createProxyingResolver = (_c = subschemaConfig.createProxyingResolver) !== null && _c !== void 0 ? _c : defaultCreateProxyingResolver;
1173 resolve = createProxyingResolver({
1174 subschemaConfig,
1175 transformedSchema,
1176 operation,
1177 fieldName: wrappingFieldName,
1178 });
1179 }
1180 else {
1181 resolve = delegate.defaultMergedResolver;
1182 }
1183 }
1184 const selectedFieldNames = Object.keys(newTargetFieldConfigMap);
1185 [newSchema] = utils.modifyObjectFields(newSchema, this.outerTypeName, fieldName => selectedFieldNames.includes(fieldName), {
1186 [wrappingFieldName]: {
1187 type: newSchema.getType(wrappingTypeName),
1188 resolve,
1189 },
1190 });
1191 return this.transformer.transformSchema(newSchema, subschemaConfig, transformedSchema);
1192 }
1193 transformRequest(originalRequest, delegationContext, transformationContext) {
1194 transformationContext.nextIndex = 0;
1195 transformationContext.paths = Object.create(null);
1196 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
1197 }
1198 transformResult(originalResult, delegationContext, transformationContext) {
1199 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
1200 }
1201}
1202function collectFields(selectionSet, fragments, fields = [], visitedFragmentNames = {}) {
1203 if (selectionSet != null) {
1204 selectionSet.selections.forEach(selection => {
1205 switch (selection.kind) {
1206 case graphql.Kind.FIELD:
1207 fields.push(selection);
1208 break;
1209 case graphql.Kind.INLINE_FRAGMENT:
1210 collectFields(selection.selectionSet, fragments, fields, visitedFragmentNames);
1211 break;
1212 case graphql.Kind.FRAGMENT_SPREAD: {
1213 const fragmentName = selection.name.value;
1214 if (!visitedFragmentNames[fragmentName]) {
1215 visitedFragmentNames[fragmentName] = true;
1216 collectFields(fragments[fragmentName].selectionSet, fragments, fields, visitedFragmentNames);
1217 }
1218 break;
1219 }
1220 }
1221 });
1222 }
1223 return fields;
1224}
1225function aliasFieldNode(fieldNode, str) {
1226 return {
1227 ...fieldNode,
1228 alias: {
1229 kind: graphql.Kind.NAME,
1230 value: str,
1231 },
1232 };
1233}
1234function hoistFieldNodes({ fieldNode, fieldNames, path, fragments, transformationContext, prefix, index = 0, wrappingPath = [], }) {
1235 const alias = fieldNode.alias != null ? fieldNode.alias.value : fieldNode.name.value;
1236 let newFieldNodes = [];
1237 if (index < path.length) {
1238 const pathSegment = path[index];
1239 collectFields(fieldNode.selectionSet, fragments).forEach((possibleFieldNode) => {
1240 if (possibleFieldNode.name.value === pathSegment) {
1241 const newWrappingPath = wrappingPath.concat([alias]);
1242 newFieldNodes = newFieldNodes.concat(hoistFieldNodes({
1243 fieldNode: possibleFieldNode,
1244 fieldNames,
1245 path,
1246 fragments,
1247 transformationContext,
1248 prefix,
1249 index: index + 1,
1250 wrappingPath: newWrappingPath,
1251 }));
1252 }
1253 });
1254 }
1255 else {
1256 collectFields(fieldNode.selectionSet, fragments).forEach((possibleFieldNode) => {
1257 if (!fieldNames || fieldNames.includes(possibleFieldNode.name.value)) {
1258 const nextIndex = transformationContext.nextIndex;
1259 transformationContext.nextIndex++;
1260 const indexingAlias = `__${prefix}${nextIndex}__`;
1261 transformationContext.paths[indexingAlias] = {
1262 pathToField: wrappingPath.concat([alias]),
1263 alias: possibleFieldNode.alias != null ? possibleFieldNode.alias.value : possibleFieldNode.name.value,
1264 };
1265 newFieldNodes.push(aliasFieldNode(possibleFieldNode, indexingAlias));
1266 }
1267 });
1268 }
1269 return newFieldNodes;
1270}
1271function dehoistValue(originalValue, context) {
1272 if (originalValue == null) {
1273 return originalValue;
1274 }
1275 const newValue = Object.create(null);
1276 Object.keys(originalValue).forEach(alias => {
1277 let obj = newValue;
1278 const path = context.paths[alias];
1279 if (path == null) {
1280 newValue[alias] = originalValue[alias];
1281 return;
1282 }
1283 const pathToField = path.pathToField;
1284 const fieldAlias = path.alias;
1285 pathToField.forEach(key => {
1286 obj = obj[key] = obj[key] || Object.create(null);
1287 });
1288 obj[fieldAlias] = originalValue[alias];
1289 });
1290 return newValue;
1291}
1292function dehoistErrors(errors, context) {
1293 if (errors === undefined) {
1294 return undefined;
1295 }
1296 return errors.map(error => {
1297 const originalPath = error.path;
1298 if (originalPath == null) {
1299 return error;
1300 }
1301 let newPath = [];
1302 originalPath.forEach(pathSegment => {
1303 if (typeof pathSegment !== 'string') {
1304 newPath.push(pathSegment);
1305 return;
1306 }
1307 const path = context.paths[pathSegment];
1308 if (path == null) {
1309 newPath.push(pathSegment);
1310 return;
1311 }
1312 newPath = newPath.concat(path.pathToField, [path.alias]);
1313 });
1314 return utils.relocatedError(error, newPath);
1315 });
1316}
1317
1318class WrapType {
1319 constructor(outerTypeName, innerTypeName, fieldName) {
1320 this.transformer = new WrapFields(outerTypeName, [fieldName], [innerTypeName]);
1321 }
1322 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1323 return this.transformer.transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema);
1324 }
1325 transformRequest(originalRequest, delegationContext, transformationContext) {
1326 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
1327 }
1328 transformResult(originalResult, delegationContext, transformationContext) {
1329 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
1330 }
1331}
1332
1333class HoistField {
1334 constructor(typeName, pathConfig, newFieldName, alias = '__gqtlw__') {
1335 this.typeName = typeName;
1336 this.newFieldName = newFieldName;
1337 const path = pathConfig.map(segment => (typeof segment === 'string' ? segment : segment.fieldName));
1338 this.argFilters = pathConfig.map((segment, index) => {
1339 if (typeof segment === 'string' || segment.argFilter == null) {
1340 return index === pathConfig.length - 1 ? () => true : () => false;
1341 }
1342 return segment.argFilter;
1343 });
1344 const pathToField = path.slice();
1345 const oldFieldName = pathToField.pop();
1346 this.oldFieldName = oldFieldName;
1347 this.pathToField = pathToField;
1348 const argLevels = Object.create(null);
1349 this.transformer = new MapFields({
1350 [typeName]: {
1351 [newFieldName]: fieldNode => wrapFieldNode(renameFieldNode(fieldNode, oldFieldName), pathToField, alias, argLevels),
1352 },
1353 }, {
1354 [typeName]: value => unwrapValue(value, alias),
1355 }, errors => unwrapErrors(errors, alias));
1356 this.argLevels = argLevels;
1357 }
1358 transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) {
1359 var _a, _b, _c;
1360 const argsMap = Object.create(null);
1361 const innerType = this.pathToField.reduce((acc, pathSegment, index) => {
1362 const field = acc.getFields()[pathSegment];
1363 field.args.forEach(arg => {
1364 if (this.argFilters[index](arg)) {
1365 argsMap[arg.name] = arg;
1366 this.argLevels[arg.name] = index;
1367 }
1368 });
1369 return graphql.getNullableType(field.type);
1370 }, originalWrappingSchema.getType(this.typeName));
1371 let [newSchema, targetFieldConfigMap] = utils.removeObjectFields(originalWrappingSchema, innerType.name, fieldName => fieldName === this.oldFieldName);
1372 const targetField = targetFieldConfigMap[this.oldFieldName];
1373 let resolve;
1374 if (transformedSchema) {
1375 const hoistingToRootField = this.typeName === ((_a = originalWrappingSchema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name) ||
1376 this.typeName === ((_b = originalWrappingSchema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name);
1377 if (hoistingToRootField) {
1378 const targetSchema = subschemaConfig.schema;
1379 const operation = this.typeName === targetSchema.getQueryType().name ? 'query' : 'mutation';
1380 const createProxyingResolver = (_c = subschemaConfig.createProxyingResolver) !== null && _c !== void 0 ? _c : defaultCreateProxyingResolver;
1381 resolve = createProxyingResolver({
1382 subschemaConfig,
1383 transformedSchema,
1384 operation,
1385 fieldName: this.newFieldName,
1386 });
1387 }
1388 else {
1389 resolve = delegate.defaultMergedResolver;
1390 }
1391 }
1392 const newTargetField = {
1393 ...targetField,
1394 resolve,
1395 };
1396 const level = this.pathToField.length;
1397 Object.keys(targetField.args).forEach(argName => {
1398 const argConfig = targetField.args[argName];
1399 const arg = {
1400 ...argConfig,
1401 name: argName,
1402 description: argConfig.description,
1403 defaultValue: argConfig.defaultValue,
1404 extensions: argConfig.extensions,
1405 astNode: argConfig.astNode,
1406 };
1407 if (this.argFilters[level](arg)) {
1408 argsMap[argName] = arg;
1409 this.argLevels[arg.name] = level;
1410 }
1411 });
1412 newTargetField.args = argsMap;
1413 newSchema = utils.appendObjectFields(newSchema, this.typeName, {
1414 [this.newFieldName]: newTargetField,
1415 });
1416 return this.transformer.transformSchema(newSchema, subschemaConfig, transformedSchema);
1417 }
1418 transformRequest(originalRequest, delegationContext, transformationContext) {
1419 return this.transformer.transformRequest(originalRequest, delegationContext, transformationContext);
1420 }
1421 transformResult(originalResult, delegationContext, transformationContext) {
1422 return this.transformer.transformResult(originalResult, delegationContext, transformationContext);
1423 }
1424}
1425function wrapFieldNode(fieldNode, path, alias, argLevels) {
1426 return path.reduceRight((acc, fieldName, index) => ({
1427 kind: graphql.Kind.FIELD,
1428 alias: {
1429 kind: graphql.Kind.NAME,
1430 value: alias,
1431 },
1432 name: {
1433 kind: graphql.Kind.NAME,
1434 value: fieldName,
1435 },
1436 selectionSet: {
1437 kind: graphql.Kind.SELECTION_SET,
1438 selections: [acc],
1439 },
1440 arguments: fieldNode.arguments.filter(arg => argLevels[arg.name.value] === index),
1441 }), {
1442 ...fieldNode,
1443 arguments: fieldNode.arguments.filter(arg => argLevels[arg.name.value] === path.length),
1444 });
1445}
1446function renameFieldNode(fieldNode, name) {
1447 return {
1448 ...fieldNode,
1449 alias: {
1450 kind: graphql.Kind.NAME,
1451 value: fieldNode.alias != null ? fieldNode.alias.value : fieldNode.name.value,
1452 },
1453 name: {
1454 kind: graphql.Kind.NAME,
1455 value: name,
1456 },
1457 };
1458}
1459function unwrapValue(originalValue, alias) {
1460 let newValue = originalValue;
1461 let object = newValue[alias];
1462 while (object != null) {
1463 newValue = object;
1464 object = newValue[alias];
1465 }
1466 delete originalValue[alias];
1467 Object.assign(originalValue, newValue);
1468 return originalValue;
1469}
1470function unwrapErrors(errors, alias) {
1471 if (errors === undefined) {
1472 return undefined;
1473 }
1474 return errors.map(error => {
1475 const originalPath = error.path;
1476 if (originalPath == null) {
1477 return error;
1478 }
1479 const newPath = originalPath.filter(pathSegment => pathSegment !== alias);
1480 return utils.relocatedError(error, newPath);
1481 });
1482}
1483
1484class WrapQuery {
1485 constructor(path, wrapper, extractor) {
1486 this.path = path;
1487 this.wrapper = wrapper;
1488 this.extractor = extractor;
1489 }
1490 transformRequest(originalRequest, _delegationContext, _transformationContext) {
1491 const fieldPath = [];
1492 const ourPath = JSON.stringify(this.path);
1493 const document = graphql.visit(originalRequest.document, {
1494 [graphql.Kind.FIELD]: {
1495 enter: (node) => {
1496 fieldPath.push(node.name.value);
1497 if (ourPath === JSON.stringify(fieldPath)) {
1498 const wrapResult = this.wrapper(node.selectionSet);
1499 // Selection can be either a single selection or a selection set. If it's just one selection,
1500 // let's wrap it in a selection set. Otherwise, keep it as is.
1501 const selectionSet = wrapResult != null && wrapResult.kind === graphql.Kind.SELECTION_SET
1502 ? wrapResult
1503 : {
1504 kind: graphql.Kind.SELECTION_SET,
1505 selections: [wrapResult],
1506 };
1507 return {
1508 ...node,
1509 selectionSet,
1510 };
1511 }
1512 },
1513 leave: () => {
1514 fieldPath.pop();
1515 },
1516 },
1517 });
1518 return {
1519 ...originalRequest,
1520 document,
1521 };
1522 }
1523 transformResult(originalResult, _delegationContext, _transformationContext) {
1524 const rootData = originalResult.data;
1525 if (rootData != null) {
1526 let data = rootData;
1527 const path = [...this.path];
1528 while (path.length > 1) {
1529 const next = path.shift();
1530 if (data[next]) {
1531 data = data[next];
1532 }
1533 }
1534 data[path[0]] = this.extractor(data[path[0]]);
1535 }
1536 return {
1537 data: rootData,
1538 errors: originalResult.errors,
1539 };
1540 }
1541}
1542
1543class ExtractField {
1544 constructor({ from, to }) {
1545 this.from = from;
1546 this.to = to;
1547 }
1548 transformRequest(originalRequest, _delegationContext, _transformationContext) {
1549 let fromSelection;
1550 const ourPathFrom = JSON.stringify(this.from);
1551 const ourPathTo = JSON.stringify(this.to);
1552 let fieldPath = [];
1553 graphql.visit(originalRequest.document, {
1554 [graphql.Kind.FIELD]: {
1555 enter: (node) => {
1556 fieldPath.push(node.name.value);
1557 if (ourPathFrom === JSON.stringify(fieldPath)) {
1558 fromSelection = node.selectionSet;
1559 return graphql.BREAK;
1560 }
1561 },
1562 leave: () => {
1563 fieldPath.pop();
1564 },
1565 },
1566 });
1567 fieldPath = [];
1568 const document = graphql.visit(originalRequest.document, {
1569 [graphql.Kind.FIELD]: {
1570 enter: (node) => {
1571 fieldPath.push(node.name.value);
1572 if (ourPathTo === JSON.stringify(fieldPath) && fromSelection != null) {
1573 return {
1574 ...node,
1575 selectionSet: fromSelection,
1576 };
1577 }
1578 },
1579 leave: () => {
1580 fieldPath.pop();
1581 },
1582 },
1583 });
1584 return {
1585 ...originalRequest,
1586 document,
1587 };
1588 }
1589}
1590
1591function makeRemoteExecutableSchema({ schema: schemaOrTypeDefs, executor, subscriber, createResolver = defaultCreateRemoteResolver, buildSchemaOptions, }) {
1592 const targetSchema = typeof schemaOrTypeDefs === 'string' ? graphql.buildSchema(schemaOrTypeDefs, buildSchemaOptions) : schemaOrTypeDefs;
1593 return wrapSchema({
1594 schema: targetSchema,
1595 createProxyingResolver: () => createResolver(executor, subscriber),
1596 });
1597}
1598function defaultCreateRemoteResolver(executor, subscriber) {
1599 return (_parent, _args, context, info) => delegate.delegateToSchema({
1600 schema: { schema: info.schema, executor, subscriber },
1601 context,
1602 info,
1603 });
1604}
1605
1606var cleanInternalStack = function (stack) { return stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); };
1607
1608/**
1609Escape RegExp special characters.
1610You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
1611@example
1612```
1613import escapeStringRegexp = require('escape-string-regexp');
1614const escapedString = escapeStringRegexp('How much $ for a 🦄?');
1615//=> 'How much \\$ for a 🦄\\?'
1616new RegExp(escapedString);
1617```
1618*/
1619var escapeStringRegexp = function (string) {
1620 if (typeof string !== 'string') {
1621 throw new TypeError('Expected a string');
1622 }
1623 // Escape characters with special meaning either inside or outside character sets.
1624 // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
1625 return string
1626 .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
1627 .replace(/-/g, '\\x2d');
1628};
1629
1630var extractPathRegex = /\s+at.*[(\s](.*)\)?/;
1631var pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/;
1632/**
1633Clean up error stack traces. Removes the mostly unhelpful internal Node.js entries.
1634@param stack - The `stack` property of an `Error`.
1635@example
1636```
1637import cleanStack = require('clean-stack');
1638const error = new Error('Missing unicorn');
1639console.log(error.stack);
1640// Error: Missing unicorn
1641// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15)
1642// at Module._compile (module.js:409:26)
1643// at Object.Module._extensions..js (module.js:416:10)
1644// at Module.load (module.js:343:32)
1645// at Function.Module._load (module.js:300:12)
1646// at Function.Module.runMain (module.js:441:10)
1647// at startup (node.js:139:18)
1648console.log(cleanStack(error.stack));
1649// Error: Missing unicorn
1650// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15)
1651```
1652*/
1653var cleanStack = function (stack, basePath) {
1654 var basePathRegex = basePath && new RegExp("(at | \\()" + escapeStringRegexp(basePath), 'g');
1655 return stack.replace(/\\/g, '/')
1656 .split('\n')
1657 .filter(function (line) {
1658 var pathMatches = line.match(extractPathRegex);
1659 if (pathMatches === null || !pathMatches[1]) {
1660 return true;
1661 }
1662 var match = pathMatches[1];
1663 // Electron
1664 if (match.includes('.app/Contents/Resources/electron.asar') ||
1665 match.includes('.app/Contents/Resources/default_app.asar')) {
1666 return false;
1667 }
1668 return !pathRegex.test(match);
1669 })
1670 .filter(function (line) { return line.trim() !== ''; })
1671 .map(function (line) {
1672 if (basePathRegex) {
1673 line = line.replace(basePathRegex, '$1');
1674 }
1675 return line;
1676 })
1677 .join('\n');
1678};
1679
1680/**
1681Indent each line in a string.
1682@param string - The string to indent.
1683@param count - How many times you want `options.indent` repeated. Default: `1`.
1684@example
1685```
1686import indentString = require('indent-string');
1687indentString('Unicorns\nRainbows', 4);
1688//=> ' Unicorns\n Rainbows'
1689indentString('Unicorns\nRainbows', 4, {indent: '♥'});
1690//=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
1691```
1692*/
1693var indentString = function (string, count, options) {
1694 if (count === void 0) { count = 1; }
1695 options = Object.assign({
1696 indent: ' ',
1697 includeEmptyLines: false,
1698 }, options);
1699 if (typeof string !== 'string') {
1700 throw new TypeError("Expected `input` to be a `string`, got `" + typeof string + "`");
1701 }
1702 if (typeof count !== 'number') {
1703 throw new TypeError("Expected `count` to be a `number`, got `" + typeof count + "`");
1704 }
1705 if (count < 0) {
1706 throw new RangeError("Expected `count` to be at least 0, got `" + count + "`");
1707 }
1708 if (typeof options.indent !== 'string') {
1709 throw new TypeError("Expected `options.indent` to be a `string`, got `" + typeof options.indent + "`");
1710 }
1711 if (count === 0) {
1712 return string;
1713 }
1714 var regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
1715 return string.replace(regex, options.indent.repeat(count));
1716};
1717
1718var AggregateError = /** @class */ (function (_super) {
1719 tslib.__extends(AggregateError, _super);
1720 function AggregateError(errors) {
1721 var _this = this;
1722 if (!Array.isArray(errors)) {
1723 throw new TypeError("Expected input to be an Array, got " + typeof errors);
1724 }
1725 var normalizedErrors = errors.map(function (error) {
1726 if (error instanceof Error) {
1727 return error;
1728 }
1729 if (error !== null && typeof error === 'object') {
1730 // Handle plain error objects with message property and/or possibly other metadata
1731 return Object.assign(new Error(error.message), error);
1732 }
1733 return new Error(error);
1734 });
1735 var message = normalizedErrors
1736 .map(function (error) {
1737 // The `stack` property is not standardized, so we can't assume it exists
1738 return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error);
1739 })
1740 .join('\n');
1741 message = '\n' + indentString(message, 4);
1742 _this = _super.call(this, message) || this;
1743 _this.name = 'AggregateError';
1744 Object.defineProperty(_this, Symbol.iterator, {
1745 get: function () { return function () { return normalizedErrors[Symbol.iterator](); }; },
1746 });
1747 return _this;
1748 }
1749 return AggregateError;
1750}(Error));
1751
1752function getSchemaFromIntrospection(introspectionResult) {
1753 var _a, _b;
1754 if ((_a = introspectionResult === null || introspectionResult === void 0 ? void 0 : introspectionResult.data) === null || _a === void 0 ? void 0 : _a.__schema) {
1755 return graphql.buildClientSchema(introspectionResult.data);
1756 }
1757 else if ((_b = introspectionResult === null || introspectionResult === void 0 ? void 0 : introspectionResult.errors) === null || _b === void 0 ? void 0 : _b.length) {
1758 if (introspectionResult.errors.length > 1) {
1759 const combinedError = new AggregateError(introspectionResult.errors);
1760 throw combinedError;
1761 }
1762 const error = introspectionResult.errors[0];
1763 throw error.originalError || error;
1764 }
1765 else {
1766 throw new Error('Could not obtain introspection result, received: ' + JSON.stringify(introspectionResult));
1767 }
1768}
1769function introspectSchema(executor, context, options) {
1770 const parsedIntrospectionQuery = graphql.parse(graphql.getIntrospectionQuery(options));
1771 const introspectionResult = executor({
1772 document: parsedIntrospectionQuery,
1773 context,
1774 });
1775 if (isPromise(introspectionResult)) {
1776 return introspectionResult.then(introspection => getSchemaFromIntrospection(introspection));
1777 }
1778 return getSchemaFromIntrospection(introspectionResult);
1779}
1780// Keep for backwards compability. Will be removed on next release.
1781function introspectSchemaSync(executor, context, options) {
1782 return introspectSchema(executor, context, options);
1783}
1784
1785exports.ExtractField = ExtractField;
1786exports.FilterInputObjectFields = FilterInputObjectFields;
1787exports.FilterInterfaceFields = FilterInterfaceFields;
1788exports.FilterObjectFieldDirectives = FilterObjectFieldDirectives;
1789exports.FilterObjectFields = FilterObjectFields;
1790exports.FilterRootFields = FilterRootFields;
1791exports.FilterTypes = FilterTypes;
1792exports.HoistField = HoistField;
1793exports.MapFields = MapFields;
1794exports.MapLeafValues = MapLeafValues;
1795exports.PruneSchema = PruneTypes;
1796exports.RemoveObjectFieldDeprecations = RemoveObjectFieldDeprecations;
1797exports.RemoveObjectFieldDirectives = RemoveObjectFieldDirectives;
1798exports.RemoveObjectFieldsWithDeprecation = RemoveObjectFieldsWithDeprecation;
1799exports.RemoveObjectFieldsWithDirective = RemoveObjectFieldsWithDirective;
1800exports.RenameInputObjectFields = RenameInputObjectFields;
1801exports.RenameInterfaceFields = RenameInterfaceFields;
1802exports.RenameObjectFields = RenameObjectFields;
1803exports.RenameRootFields = RenameRootFields;
1804exports.RenameRootTypes = RenameRootTypes;
1805exports.RenameTypes = RenameTypes;
1806exports.TransformCompositeFields = TransformCompositeFields;
1807exports.TransformEnumValues = TransformEnumValues;
1808exports.TransformInputObjectFields = TransformInputObjectFields;
1809exports.TransformInterfaceFields = TransformInterfaceFields;
1810exports.TransformObjectFields = TransformObjectFields;
1811exports.TransformQuery = TransformQuery;
1812exports.TransformRootFields = TransformRootFields;
1813exports.WrapFields = WrapFields;
1814exports.WrapQuery = WrapQuery;
1815exports.WrapType = WrapType;
1816exports.defaultCreateProxyingResolver = defaultCreateProxyingResolver;
1817exports.defaultCreateRemoteResolver = defaultCreateRemoteResolver;
1818exports.generateProxyingResolvers = generateProxyingResolvers;
1819exports.introspectSchema = introspectSchema;
1820exports.introspectSchemaSync = introspectSchemaSync;
1821exports.makeRemoteExecutableSchema = makeRemoteExecutableSchema;
1822exports.wrapSchema = wrapSchema;
1823//# sourceMappingURL=index.cjs.js.map