UNPKG

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