UNPKG

@graphql-tools/stitch

Version:

A set of utils for faster development of GraphQL tools

4,404 lines • 147 kB
import { isExternalObject, extractUnavailableFieldsFromSelectionSet, getVariableValues, handleOverrideByDelegation, subtractSelectionSets, extractUnavailableFields, leftOverByDelegationPlan, delegateToSchema, isSubschemaConfig, defaultMergedResolver, Subschema } from '@graphql-tools/delegate';
import { mergeType, mergeInputType, mergeInterface, mergeUnion, mergeEnum, mergeScalar, mergeTypeDefs, mergeResolvers, mergeExtensions, applyExtensions } from '@graphql-tools/merge';
import { extendResolversFromInterfaces, addResolversToSchema, assertResolversPresent, makeExecutableSchema } from '@graphql-tools/schema';
import { mergeDeep, collectSubFields, memoize3, memoize2, memoize1, parseSelectionSet, collectFields, isSome, createNamedStub, createStub, getRootTypeMap, getRootTypes, inspect, rewireTypes, getOperationASTFromRequest, getDefinedRootType, asGetArgumentValuesVariables } from '@graphql-tools/utils';
import { handleMaybePromise } from '@whatwg-node/promise-helpers';
import { getNamedType, Kind, isAbstractType, isObjectType, isInterfaceType, TypeNameMetaFieldDef, isUnionType, GraphQLList, isLeafType, isInputObjectType, print, visit, TypeInfo, visitWithTypeInfo, isNonNullType, isEnumType, isScalarType, isListType, getNullableType, isNullableType, GraphQLObjectType, GraphQLInputObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLScalarType, GraphQLDirective, valueFromASTUntyped, getDirectiveValues, GraphQLDeprecatedDirective, DirectiveLocation, isNamedType, isIntrospectionType, isDirective, isSpecifiedScalarType, GraphQLSchema, concatAST, extendSchema, specifiedDirectives, isSpecifiedDirective, getArgumentValues } from 'graphql';
import { batchDelegateToSchema } from '@graphql-tools/batch-delegate';
import { wrapSchema } from '@graphql-tools/wrap';
import { getFragmentsFromDocument } from '@graphql-tools/executor';

function valueSatisfiesSelectionSet$1(value, selectionSet) {
  if (Array.isArray(value)) {
    return value.every(
      (item) => valueSatisfiesSelectionSet$1(item, selectionSet)
    );
  }
  if (value == null || typeof value !== "object") {
    return false;
  }
  const objectValue = value;
  return selectionSet.selections.every((selection) => {
    if (selection.kind === Kind.INLINE_FRAGMENT) {
      return valueSatisfiesSelectionSet$1(value, selection.selectionSet);
    }
    if (selection.kind !== Kind.FIELD) {
      return false;
    }
    const responseKey = selection.alias?.value || selection.name.value;
    return objectValue[responseKey] !== void 0 && (selection.selectionSet == null || valueSatisfiesSelectionSet$1(
      objectValue[responseKey],
      selection.selectionSet
    ));
  });
}
function resolveLocalFieldResult(result, context, info, stitchingInfo = info.schema.extensions?.["stitchingInfo"], providedFields) {
  if (stitchingInfo == null || result == null) {
    return result;
  }
  return resolveOne(result, context, info, stitchingInfo, providedFields);
}
function getMissingSelections(value, selections, fragments = {}) {
  if (value == null || typeof value !== "object") {
    return [...selections];
  }
  const objectValue = value;
  const missing = [];
  for (const selection of selections) {
    if (selection.kind === Kind.INLINE_FRAGMENT) {
      const sub = getMissingSelections(
        value,
        selection.selectionSet.selections,
        fragments
      );
      if (sub.length) {
        missing.push({
          ...selection,
          selectionSet: { kind: Kind.SELECTION_SET, selections: sub }
        });
      }
      continue;
    }
    if (selection.kind === Kind.FRAGMENT_SPREAD) {
      const fragment = fragments[selection.name.value];
      if (fragment == null) {
        missing.push(selection);
        continue;
      }
      const sub = getMissingSelections(
        value,
        fragment.selectionSet.selections,
        fragments
      );
      if (sub.length) {
        missing.push({
          kind: Kind.INLINE_FRAGMENT,
          typeCondition: fragment.typeCondition,
          directives: [
            ...fragment.directives ?? [],
            ...selection.directives ?? []
          ],
          selectionSet: { kind: Kind.SELECTION_SET, selections: sub }
        });
      }
      continue;
    }
    const fieldValue = objectValue[selection.name.value];
    if (fieldValue === void 0 || fieldValue === null && selection.selectionSet != null) {
      missing.push(selection);
      continue;
    }
    if (selection.selectionSet != null) {
      if (Array.isArray(fieldValue)) {
        const anyMissing = fieldValue.some(
          (item) => getMissingSelections(
            item,
            selection.selectionSet.selections,
            fragments
          ).length > 0
        );
        if (anyMissing) {
          missing.push(selection);
        }
      } else {
        const sub = getMissingSelections(
          fieldValue,
          selection.selectionSet.selections,
          fragments
        );
        if (sub.length) {
          missing.push({
            ...selection,
            selectionSet: { kind: Kind.SELECTION_SET, selections: sub }
          });
        }
      }
    }
  }
  return missing;
}
function resolveOne(value, context, info, stitchingInfo, providedFields) {
  if (Array.isArray(value)) {
    return value.map(
      (item) => resolveOne(item, context, info, stitchingInfo, providedFields)
    );
  }
  if (value == null || typeof value !== "object" || value instanceof Error || isExternalObject(value)) {
    return value;
  }
  const objectValue = value;
  const returnType = getNamedType(info.returnType);
  const typeName = typeof objectValue["__typename"] === "string" ? objectValue["__typename"] : returnType.name;
  const mergedTypeInfo = stitchingInfo.mergedTypes[typeName];
  if (mergedTypeInfo == null) {
    return value;
  }
  let selections = info.fieldNodes.flatMap(
    (fieldNode) => fieldNode.selectionSet?.selections ?? []
  );
  if (providedFields?.size) {
    selections = selections.filter(
      (selection) => selection.kind !== Kind.FIELD || !providedFields.has(selection.name.value)
    );
  }
  const missingSelections = getMissingSelections(
    value,
    selections,
    info.fragments
  );
  if (!missingSelections.length) {
    return value;
  }
  const selectionSet = {
    kind: Kind.SELECTION_SET,
    selections: missingSelections
  };
  const candidates = [];
  for (const [subschema, keySelectionSet] of mergedTypeInfo.selectionSets) {
    candidates.push([subschema, [keySelectionSet]]);
  }
  if (mergedTypeInfo.entryPointSelectionSets) {
    for (const [
      subschema,
      keySelectionSets
    ] of mergedTypeInfo.entryPointSelectionSets) {
      candidates.push([subschema, keySelectionSets]);
    }
  }
  candidates.sort(
    ([a], [b]) => Number(Boolean(a.merge?.[typeName]?.fields)) - Number(Boolean(b.merge?.[typeName]?.fields))
  );
  for (const [subschema, keySelectionSets] of candidates) {
    if (!keySelectionSets.some((ks) => valueSatisfiesSelectionSet$1(value, ks))) {
      continue;
    }
    const resolver = mergedTypeInfo.resolvers.get(subschema);
    if (resolver == null) {
      continue;
    }
    if (objectValue["__typename"] == null && !isAbstractType(returnType)) {
      objectValue["__typename"] = typeName;
    }
    return handleMaybePromise(
      () => resolver(
        value,
        context,
        info,
        subschema,
        selectionSet,
        void 0,
        returnType,
        false
      ),
      // value comes first so the delegation result wins on overlaps, while
      // payload fields outside the delegated selection (like the key) survive;
      // respectNonEnumerableSymbols keeps the external object annotation intact
      (resolved) => mergeDeep([value, resolved], false, false, false, true)
    );
  }
  return value;
}

function selectionRequiresOnSubschema(stitchingInfo, subschema, typeName, selectionSet) {
  const fieldSels = stitchingInfo?.mergedTypes[typeName]?.fieldSelectionSets.get(subschema);
  if (fieldSels == null) {
    return false;
  }
  for (const sel of selectionSet.selections) {
    if (sel.kind === Kind.FIELD && fieldSels[sel.name.value] != null) {
      return true;
    }
  }
  return false;
}
function optimizeDelegationMap(delegationMap, typeName, fragments, stitchingInfo) {
  for (const [subschema, selectionSet] of delegationMap) {
    for (const [subschema2, selectionSet2] of delegationMap) {
      if (subschema === subschema2) {
        continue;
      }
      if (selectionRequiresOnSubschema(
        stitchingInfo,
        subschema2,
        typeName,
        selectionSet
      )) {
        continue;
      }
      const unavailableFields = extractUnavailableFieldsFromSelectionSet(
        subschema2.transformedSchema,
        subschema2.transformedSchema.getType(typeName),
        selectionSet,
        () => true,
        fragments
      );
      if (!unavailableFields.length) {
        delegationMap.set(subschema2, {
          kind: Kind.SELECTION_SET,
          selections: [...selectionSet2.selections, ...selectionSet.selections]
        });
        delegationMap.delete(subschema);
      }
    }
  }
  return delegationMap;
}
function fieldArgsKey(field) {
  if (!field.arguments?.length) {
    return "";
  }
  return JSON.stringify(field.arguments.map((a) => [a.name.value, a.value]));
}
function fieldResponseKey(field) {
  return field.alias?.value ?? field.name.value;
}
function selectionsCompatibleForUnion(a, b) {
  const aFields = /* @__PURE__ */ new Map();
  for (const sel of a.selections) {
    if (sel.kind === Kind.FIELD) {
      aFields.set(fieldResponseKey(sel), sel);
    }
  }
  for (const sel of b.selections) {
    if (sel.kind !== Kind.FIELD) {
      continue;
    }
    const key = fieldResponseKey(sel);
    const prior = aFields.get(key);
    if (!prior) {
      continue;
    }
    if (prior.name.value !== sel.name.value || fieldArgsKey(prior) !== fieldArgsKey(sel)) {
      return false;
    }
    if (prior.selectionSet && sel.selectionSet) {
      if (!selectionsCompatibleForUnion(prior.selectionSet, sel.selectionSet)) {
        return false;
      }
    } else if (prior.selectionSet || sel.selectionSet) {
      return false;
    }
  }
  return true;
}
function unionSelectionSets(a, b) {
  const byKey = /* @__PURE__ */ new Map();
  const add = (sel) => {
    if (sel.kind === Kind.FIELD) {
      const key = `f:${fieldResponseKey(sel)}`;
      const prior = byKey.get(key);
      if (!prior || prior.kind !== Kind.FIELD) {
        byKey.set(key, sel);
        return;
      }
      if (prior.selectionSet && sel.selectionSet) {
        byKey.set(key, {
          ...prior,
          selectionSet: unionSelectionSets(
            prior.selectionSet,
            sel.selectionSet
          )
        });
      }
      return;
    }
    byKey.set(JSON.stringify(sel), sel);
  };
  for (const sel of a.selections) {
    add(sel);
  }
  for (const sel of b.selections) {
    add(sel);
  }
  return { kind: Kind.SELECTION_SET, selections: [...byKey.values()] };
}
function collectSelectedFieldNames(selectionSet) {
  const names = /* @__PURE__ */ new Set();
  for (const sel of selectionSet.selections) {
    if (sel.kind === Kind.FIELD) {
      names.add(sel.name.value);
    }
  }
  return names;
}
function findMergeFieldConfig(stitchingInfo, subschema, typeName, fieldName) {
  const direct = subschema.merge?.[typeName]?.fields?.[fieldName];
  if (direct?.selectionSet || direct?.computed) {
    return direct;
  }
  if (!stitchingInfo) {
    return direct;
  }
  for (const s of stitchingInfo.subschemaMap.values()) {
    if (subschema.name && s.name !== subschema.name) {
      continue;
    }
    const field = s.merge?.[typeName]?.fields?.[fieldName];
    if (field?.selectionSet || field?.computed) {
      return field;
    }
  }
  return void 0;
}
function requiresDepsForField(stitchingInfo, subschema, typeName, fieldName) {
  if (fieldName === "__typename") {
    return [];
  }
  const mergeField = findMergeFieldConfig(
    stitchingInfo,
    subschema,
    typeName,
    fieldName
  );
  if (!mergeField?.selectionSet && !mergeField?.computed) {
    return [];
  }
  return stitchingInfo?.fieldNodesByField?.[typeName]?.[fieldName] ?? [];
}
function selectionRequiresCount(stitchingInfo, subschema, typeName, selectionSet) {
  let n = 0;
  for (const sel of selectionSet.selections) {
    if (sel.kind !== Kind.FIELD) {
      continue;
    }
    n += requiresDepsForField(
      stitchingInfo,
      subschema,
      typeName,
      sel.name.value
    ).length;
  }
  return n;
}
function requiresArgsCompatibleForMaps(stitchingInfo, typeName, a, b) {
  const byName = /* @__PURE__ */ new Map();
  for (const entry of [a, b]) {
    for (const sel of entry.selectionSet.selections) {
      if (sel.kind !== Kind.FIELD) {
        continue;
      }
      for (const dep of requiresDepsForField(
        stitchingInfo,
        entry.subschema,
        typeName,
        sel.name.value
      )) {
        const args = fieldArgsKey(dep);
        const prev = byName.get(dep.name.value);
        if (prev != null && prev !== args) {
          return false;
        }
        byName.set(dep.name.value, args);
      }
    }
  }
  return true;
}
function hasCircularSelectedRequires(stitchingInfo, subschema, typeName, selected) {
  for (const name of selected) {
    const deps = requiresDepsForField(stitchingInfo, subschema, typeName, name);
    for (const dep of deps) {
      if (dep.name.value === name || !selected.has(dep.name.value)) {
        continue;
      }
      const depMerge = findMergeFieldConfig(
        stitchingInfo,
        subschema,
        typeName,
        dep.name.value
      );
      if (depMerge?.selectionSet || depMerge?.computed) {
        return true;
      }
    }
  }
  return false;
}
function cloneDelegationMap(map) {
  return new Map(map);
}
function coalesceAdjacentDelegationMaps(delegationMaps, typeName, stitchingInfo) {
  if (delegationMaps.length < 2 || stitchingInfo == null) {
    return delegationMaps;
  }
  const out = [];
  for (const map of delegationMaps) {
    const prev = out[out.length - 1];
    if (!prev) {
      out.push(cloneDelegationMap(map));
      continue;
    }
    const next = cloneDelegationMap(map);
    let moved = false;
    for (const [nextSub, nextSel] of [...next.entries()]) {
      if (!nextSub.name) {
        continue;
      }
      const nextReq = selectionRequiresCount(
        stitchingInfo,
        nextSub,
        typeName,
        nextSel
      );
      if (nextReq === 0) {
        continue;
      }
      const nextHasForeignSubgraph = [...next.keys()].some(
        (s) => s.name !== nextSub.name
      );
      if (nextHasForeignSubgraph) {
        continue;
      }
      for (const [prevSub, prevSel] of [...prev.entries()]) {
        if (prevSub.name !== nextSub.name) {
          continue;
        }
        const prevReq = selectionRequiresCount(
          stitchingInfo,
          prevSub,
          typeName,
          prevSel
        );
        if (prevReq !== 0) {
          continue;
        }
        const prevEntry = { subschema: prevSub, selectionSet: prevSel };
        const nextEntry = { subschema: nextSub, selectionSet: nextSel };
        if (!requiresArgsCompatibleForMaps(
          stitchingInfo,
          typeName,
          prevEntry,
          nextEntry
        ) || !selectionsCompatibleForUnion(prevSel, nextSel)) {
          continue;
        }
        const selectionSet = unionSelectionSets(prevSel, nextSel);
        const selected = collectSelectedFieldNames(selectionSet);
        if (hasCircularSelectedRequires(
          stitchingInfo,
          nextSub,
          typeName,
          selected
        )) {
          continue;
        }
        next.set(nextSub, selectionSet);
        prev.delete(prevSub);
        moved = true;
      }
    }
    if (prev.size === 0) {
      out.pop();
    }
    out.push(next);
    if (!moved && prev.size > 0) ;
  }
  return out;
}

function getFieldsNotInSubschema(schema, stitchingInfo, gatewayType, subschemaType, fieldNodes, fragments, variableValues, subschema, providedSelectionNode, context, info) {
  const sourceSchema = subschema.transformedSchema;
  const normalizedVariableValues = getVariableValues(variableValues);
  let { fields: subFieldNodesByResponseKey } = collectSubFields(
    schema,
    fragments,
    normalizedVariableValues,
    gatewayType,
    fieldNodes
  );
  let mapChanged = false;
  const fieldsNotInSchema = /* @__PURE__ */ new Set();
  if (isAbstractType(gatewayType)) {
    fieldsNotInSchema.add({
      kind: Kind.FIELD,
      name: {
        kind: Kind.NAME,
        value: "__typename"
      }
    });
    for (const possibleType of schema.getPossibleTypes(gatewayType)) {
      const { fields: subFieldNodesOfPossibleType } = collectSubFields(
        schema,
        fragments,
        normalizedVariableValues,
        possibleType,
        fieldNodes
      );
      for (const [responseKey, subFieldNodes] of subFieldNodesOfPossibleType) {
        if (!mapChanged) {
          subFieldNodesByResponseKey = new Map(subFieldNodesByResponseKey);
          mapChanged = true;
        }
        const existingSubFieldNodes = subFieldNodesByResponseKey.get(responseKey);
        if (existingSubFieldNodes) {
          existingSubFieldNodes.push(...subFieldNodes);
        } else {
          subFieldNodesByResponseKey.set(responseKey, subFieldNodes);
        }
      }
    }
  }
  const fieldNodesByField = stitchingInfo?.fieldNodesByField;
  const fields = isObjectType(subschemaType) || isInterfaceType(subschemaType) ? subschemaType.getFields() : /* @__PURE__ */ Object.create(null);
  const fieldNodesByFieldForType = fieldNodesByField?.[gatewayType.name];
  for (const [, subFieldNodes] of subFieldNodesByResponseKey) {
    let fieldNotInSchema = false;
    const fieldName = subFieldNodes[0]?.name.value;
    let field = fieldName === "__typename" ? TypeNameMetaFieldDef : fields[fieldName];
    if (context != null && info != null) {
      const overrideHandler = subschema?.merge?.[gatewayType.name]?.fields?.[fieldName]?.override;
      if (overrideHandler != null) {
        const overridden = handleOverrideByDelegation(
          info,
          context,
          overrideHandler
        );
        if (!overridden) {
          field = void 0;
        }
      }
    }
    if (!field) {
      if (providedSelectionNode) {
        const subFieldSelection = {
          kind: Kind.SELECTION_SET,
          selections: subFieldNodes
        };
        const flattenedProvided = flattenSelectionsForType(
          providedSelectionNode,
          // @provides flattening is only meaningful for object parents;
          // unions never carry provided selections themselves.
          gatewayType,
          schema
        );
        const subtracted = subtractSelectionSets(
          subFieldSelection,
          flattenedProvided,
          fragments
        );
        if (subtracted?.selections?.length) {
          fieldNotInSchema = true;
          for (const subFieldNode of subtracted.selections) {
            fieldsNotInSchema.add(subFieldNode);
          }
        }
      } else {
        fieldNotInSchema = true;
        for (const subFieldNode of subFieldNodes) {
          fieldsNotInSchema.add(subFieldNode);
        }
      }
    } else if (
      // https://github.com/graphql-hive/gateway/pull/1423
      typeof globalThis === "undefined" || // @ts-expect-error
      !globalThis["__DO_NOT_USE__stitching_disable_extract_unavailable_fields_for_fields_not_in_schema__"]
    ) {
      const providedTypeFieldPairs = providedSelectionNode ? collectProvidedTypeFieldPairs(
        providedSelectionNode,
        gatewayType,
        schema
      ) : null;
      for (const subFieldNode of subFieldNodes) {
        const unavailableFields = extractUnavailableFields(
          sourceSchema,
          field,
          subFieldNode,
          (fieldType, selection) => {
            const nestedMerged = stitchingInfo.mergedTypes[fieldType.name];
            if (nestedMerged?.resolvers.get(subschema) && mergedTypeHasOwnerForField(
              nestedMerged,
              fieldType.name,
              selection.name.value
            )) {
              return false;
            }
            if (providedTypeFieldPairs?.has(
              `${fieldType.name}.${selection.name.value}`
            )) {
              return false;
            }
            return true;
          },
          fragments
        );
        if (unavailableFields.length) {
          fieldNotInSchema = true;
          fieldsNotInSchema.add({
            ...subFieldNode,
            selectionSet: {
              kind: Kind.SELECTION_SET,
              selections: unavailableFields
            }
          });
        }
      }
    }
    const isComputedField = subschema.merge?.[gatewayType.name]?.fields?.[fieldName]?.computed;
    let addedSubFieldNodes = false;
    if ((isComputedField || fieldNotInSchema) && fieldNodesByFieldForType) {
      const visitedFieldNames = /* @__PURE__ */ new Set();
      addMissingRequiredFields({
        fieldName,
        fields,
        fieldsNotInSchema,
        visitedFieldNames,
        onAdd: () => {
          if (!addedSubFieldNodes) {
            for (const subFieldNode of subFieldNodes) {
              fieldsNotInSchema.add(subFieldNode);
            }
            addedSubFieldNodes = true;
          }
        },
        fieldNodesByField: fieldNodesByFieldForType
      });
    }
  }
  return Array.from(fieldsNotInSchema);
}
function mergedTypeHasOwnerForField(mergedTypeInfo, typeName, fieldName) {
  for (const [targetSubschema] of mergedTypeInfo.resolvers) {
    const schema = targetSubschema.transformedSchema;
    const type = schema?.getType(typeName);
    if ((isObjectType(type) || isInterfaceType(type)) && type.getFields()[fieldName] != null) {
      return true;
    }
  }
  return false;
}
function addMissingRequiredFields({
  fieldName,
  fields,
  fieldsNotInSchema,
  onAdd,
  fieldNodesByField,
  visitedFieldNames
}) {
  if (visitedFieldNames.has(fieldName)) {
    return;
  }
  visitedFieldNames.add(fieldName);
  const fieldNodesForField = fieldNodesByField?.[fieldName];
  if (fieldNodesForField) {
    for (const fieldNode of fieldNodesForField) {
      if (fieldNode.name.value !== "__typename" && !fields[fieldNode.name.value]) {
        onAdd();
        fieldsNotInSchema.add(fieldNode);
        addMissingRequiredFields({
          fieldName: fieldNode.name.value,
          fields,
          fieldsNotInSchema,
          onAdd,
          fieldNodesByField,
          visitedFieldNames
        });
      }
    }
  }
}
function collectProvidedTypeFieldPairs(selectionSet, parentType, schema) {
  const pairs = /* @__PURE__ */ new Set();
  for (const sel of selectionSet.selections) {
    if (sel.kind === Kind.FIELD) {
      pairs.add(`${parentType.name}.${sel.name.value}`);
      if (sel.selectionSet) {
        const fieldDef = parentType.getFields()[sel.name.value];
        if (fieldDef) {
          const namedType = getNamedType(fieldDef.type);
          if (isObjectType(namedType)) {
            for (const p of collectProvidedTypeFieldPairs(
              sel.selectionSet,
              namedType,
              schema
            )) {
              pairs.add(p);
            }
          }
        }
      }
    } else if (sel.kind === Kind.INLINE_FRAGMENT && sel.selectionSet) {
      const condType = sel.typeCondition ? schema.getType(
        sel.typeCondition.name.value
      ) : parentType;
      if (condType && isObjectType(condType)) {
        for (const p of collectProvidedTypeFieldPairs(
          sel.selectionSet,
          condType,
          schema
        )) {
          pairs.add(p);
        }
      }
    }
  }
  return pairs;
}
const flattenSelectionsForTypeImpl = (selectionSet, gatewayType, schema) => {
  let changed = false;
  const flat = [];
  for (const selection of selectionSet.selections) {
    if (selection.kind === Kind.INLINE_FRAGMENT) {
      const condName = selection.typeCondition?.name.value;
      const condType = condName ? schema.getType(condName) : gatewayType;
      const matchesGatewayType = condType != null && (condType.name === gatewayType.name || isAbstractType(condType) && schema.isSubType(condType, gatewayType));
      if (matchesGatewayType) {
        changed = true;
        const inner = flattenSelectionsForType(
          selection.selectionSet,
          gatewayType,
          schema
        );
        for (const innerSel of inner.selections) {
          flat.push(innerSel);
        }
        continue;
      }
    }
    flat.push(selection);
  }
  if (!changed) {
    return selectionSet;
  }
  return {
    kind: Kind.SELECTION_SET,
    selections: flat
  };
};
const flattenSelectionsForType = memoize3(flattenSelectionsForTypeImpl);

function memoizeDelegationPlanBuilder(fn, seedKeyForParent) {
  const cache1 = /* @__PURE__ */ new WeakMap();
  return function memoized(schema, sourceSubschema, variableValues, fragments, fieldNodes, context, info, parent) {
    let cache2 = cache1.get(schema);
    if (!cache2) {
      cache2 = /* @__PURE__ */ new WeakMap();
      cache1.set(schema, cache2);
    }
    let cache3 = cache2.get(sourceSubschema);
    if (!cache3) {
      cache3 = /* @__PURE__ */ new WeakMap();
      cache2.set(sourceSubschema, cache3);
    }
    let cache4 = cache3.get(variableValues);
    if (!cache4) {
      cache4 = /* @__PURE__ */ new WeakMap();
      cache3.set(variableValues, cache4);
    }
    let cache5 = cache4.get(fragments);
    if (!cache5) {
      cache5 = /* @__PURE__ */ new WeakMap();
      cache4.set(fragments, cache5);
    }
    let seedCache = cache5.get(
      fieldNodes
    );
    if (!seedCache) {
      seedCache = /* @__PURE__ */ new Map();
      cache5.set(fieldNodes, seedCache);
    }
    const seedKey = seedKeyForParent(parent);
    const cached = seedCache.get(seedKey);
    if (cached !== void 0) {
      return cached;
    }
    const value = fn(
      schema,
      sourceSubschema,
      variableValues,
      fragments,
      fieldNodes,
      context,
      info,
      parent
    );
    seedCache.set(seedKey, value);
    return value;
  };
}
function parentFieldPresenceKey(parent, depth = 0) {
  if (parent == null || typeof parent !== "object" || depth > 4) {
    return "";
  }
  const keys = [];
  for (const key of Object.keys(parent)) {
    if (key.startsWith("_") && key !== "__typename") {
      continue;
    }
    keys.push(key);
  }
  keys.sort();
  const parts = [];
  for (const key of keys) {
    const value = parent[key];
    if (value != null && typeof value === "object") {
      if (Array.isArray(value)) {
        let childKey = "";
        for (const item of value) {
          if (item != null && typeof item === "object") {
            childKey = parentFieldPresenceKey(item, depth + 1);
            break;
          }
        }
        parts.push(childKey ? `${key}:[${childKey}]` : key);
      } else {
        const childKey = parentFieldPresenceKey(value, depth + 1);
        parts.push(childKey ? `${key}:{${childKey}}` : key);
      }
    } else {
      parts.push(key);
    }
  }
  return parts.join(",");
}

function calculateDelegationStage(mergedTypeInfo, sourceSubschemas, targetSubschemas, fieldNodes, fragments, context, info, stitchingInfo, initialSourceSubschemas = sourceSubschemas, fetchedFieldsByType = /* @__PURE__ */ new Map()) {
  const {
    selectionSets,
    entryPointSelectionSets,
    fieldSelectionSets,
    uniqueFields,
    nonUniqueFields
  } = mergedTypeInfo;
  const proxiableSubschemas = [];
  const nonProxiableSubschemas = [];
  for (const t of targetSubschemas) {
    const entrySels = entryPointSelectionSets?.get(t);
    if (entrySels != null && entrySels.length > 0) {
      const anyAvailable = entrySels.some(
        (selectionSet2) => subschemaTypesContainSelectionSet(
          mergedTypeInfo,
          sourceSubschemas,
          selectionSet2
        )
      );
      if (anyAvailable) {
        proxiableSubschemas.push(t);
      } else {
        nonProxiableSubschemas.push(t);
      }
      continue;
    }
    const selectionSet = selectionSets.get(t);
    if (selectionSet != null && !subschemaTypesContainSelectionSet(
      mergedTypeInfo,
      sourceSubschemas,
      selectionSet
    )) {
      nonProxiableSubschemas.push(t);
    } else {
      proxiableSubschemas.push(t);
    }
  }
  const unproxiableFieldNodes = [];
  function fieldRequiresSatisfied(target, fieldName) {
    const fieldSelectionSet = fieldSelectionSets.get(target)?.[fieldName];
    if (fieldSelectionSet == null) {
      return true;
    }
    return selectionSetAvailableCloneLess(
      mergedTypeInfo,
      initialSourceSubschemas,
      fetchedFieldsByType,
      fieldSelectionSet,
      mergedTypeInfo.typeName
    );
  }
  function deferField(fieldNode, target) {
    unproxiableFieldNodes.push(fieldNode);
    if (target != null && !nonProxiableSubschemas.includes(target)) {
      nonProxiableSubschemas.push(target);
    }
  }
  const delegationMap = /* @__PURE__ */ new Map();
  function scheduleRequiresFetch(target, fieldName) {
    const req = fieldSelectionSets.get(target)?.[fieldName];
    if (req == null) {
      return;
    }
    for (const selection of req.selections) {
      if (selection.kind !== Kind.FIELD) {
        continue;
      }
      const depName = selection.name.value;
      if (depName === "__typename") {
        continue;
      }
      if (fetchedFieldsByType.get(mergedTypeInfo.typeName)?.has(depName)) {
        continue;
      }
      const onInitialSource = initialSourceSubschemas.some((s) => {
        const t = s.transformedSchema.getType(mergedTypeInfo.typeName);
        return (isObjectType(t) || isInterfaceType(t)) && t.getFields()[depName] != null;
      });
      if (!onInitialSource) {
        continue;
      }
      if (selectionSetAvailableCloneLess(
        mergedTypeInfo,
        initialSourceSubschemas,
        fetchedFieldsByType,
        { kind: Kind.SELECTION_SET, selections: [selection] },
        mergedTypeInfo.typeName
      )) {
        continue;
      }
      const unique = uniqueFields[depName];
      const nonUnique = nonUniqueFields[depName];
      const candidates = [];
      if (unique != null) {
        candidates.push(unique);
      } else if (nonUnique != null) {
        candidates.push(...nonUnique);
      }
      const provider = candidates.find(
        (s) => s !== target && proxiableSubschemas.includes(s)
      ) ?? candidates.find((s) => proxiableSubschemas.includes(s)) ?? candidates.find((s) => s !== target) ?? candidates[0];
      if (provider == null) {
        continue;
      }
      const entrySels = entryPointSelectionSets?.get(provider);
      if (entrySels != null && entrySels.length > 0) {
        if (!entrySels.some(
          (selectionSet) => subschemaTypesContainSelectionSet(
            mergedTypeInfo,
            sourceSubschemas,
            selectionSet
          )
        )) {
          continue;
        }
      } else {
        const typeSelectionSet = selectionSets.get(provider);
        if (typeSelectionSet != null && !subschemaTypesContainSelectionSet(
          mergedTypeInfo,
          sourceSubschemas,
          typeSelectionSet
        )) {
          continue;
        }
      }
      const existing = delegationMap.get(provider);
      if (existing != null) {
        existing.selections.push(selection);
      } else {
        delegationMap.set(provider, {
          kind: Kind.SELECTION_SET,
          selections: [selection]
        });
      }
    }
  }
  let overriddenOverall = false;
  for (const fieldNode of fieldNodes) {
    const fieldName = fieldNode.name.value;
    if (fieldName === "__typename") {
      continue;
    }
    const sourcesWithUnsatisfiedDependencies = initialSourceSubschemas.filter(
      (s) => {
        const req = fieldSelectionSets.get(s)?.[fieldName];
        if (req == null) {
          return false;
        }
        return !selectionSetAvailableCloneLess(
          mergedTypeInfo,
          initialSourceSubschemas,
          fetchedFieldsByType,
          req,
          mergedTypeInfo.typeName
        );
      }
    );
    if (sourcesWithUnsatisfiedDependencies.length === sourceSubschemas.length) {
      unproxiableFieldNodes.push(fieldNode);
      for (const source of sourcesWithUnsatisfiedDependencies) {
        if (!nonProxiableSubschemas.includes(source)) {
          nonProxiableSubschemas.push(source);
        }
      }
      continue;
    }
    const uniqueSubschema = uniqueFields[fieldName];
    if (uniqueSubschema != null) {
      if (!proxiableSubschemas.includes(uniqueSubschema)) {
        deferField(fieldNode, uniqueSubschema);
        continue;
      }
      if (!fieldRequiresSatisfied(uniqueSubschema, fieldName)) {
        scheduleRequiresFetch(uniqueSubschema, fieldName);
        deferField(fieldNode, uniqueSubschema);
        continue;
      }
      const existingSubschema2 = delegationMap.get(uniqueSubschema)?.selections;
      if (existingSubschema2 != null) {
        existingSubschema2.push(fieldNode);
      } else {
        delegationMap.set(uniqueSubschema, {
          kind: Kind.SELECTION_SET,
          selections: [fieldNode]
        });
      }
      continue;
    }
    let nonUniqueSubschemas = nonUniqueFields[fieldNode.name.value];
    if (nonUniqueSubschemas == null) {
      unproxiableFieldNodes.push(fieldNode);
      continue;
    }
    nonUniqueSubschemas = nonUniqueSubschemas.filter(
      (s) => proxiableSubschemas.includes(s) && fieldRequiresSatisfied(s, fieldName)
    );
    if (!nonUniqueSubschemas.length) {
      const requireDeferred = nonUniqueFields[fieldNode.name.value].filter(
        (s) => proxiableSubschemas.includes(s)
      );
      if (requireDeferred.length) {
        for (const t of requireDeferred) {
          scheduleRequiresFetch(t, fieldName);
          if (!nonProxiableSubschemas.includes(t)) {
            nonProxiableSubschemas.push(t);
          }
        }
      }
      unproxiableFieldNodes.push(fieldNode);
      continue;
    }
    let existingSubschema = nonUniqueSubschemas.find(
      (s) => delegationMap.has(s)
    );
    let overridden = false;
    for (const nonUniqueSubschema of nonUniqueSubschemas) {
      if (context != null && info != null) {
        const overrideHandler = nonUniqueSubschema.merge?.[mergedTypeInfo.typeName]?.fields?.[fieldNode.name.value]?.override;
        if (overrideHandler != null) {
          const overriddenBySubschema = handleOverrideByDelegation(
            info,
            context,
            overrideHandler
          );
          if (overriddenBySubschema) {
            let subschemaSelections = delegationMap.get(nonUniqueSubschema);
            if (subschemaSelections == null) {
              subschemaSelections = {
                kind: Kind.SELECTION_SET,
                selections: []
              };
              delegationMap.set(nonUniqueSubschema, subschemaSelections);
            }
            subschemaSelections.selections.push(fieldNode);
            overridden = true;
            break;
          } else {
            existingSubschema = void 0;
            overriddenOverall = true;
          }
        }
      }
    }
    if (existingSubschema != null) {
      if (!overridden) {
        delegationMap.get(existingSubschema).selections.push(fieldNode);
      }
    } else {
      let bestUniqueSubschema = nonUniqueSubschemas[0];
      let bestScore = Infinity;
      for (const nonUniqueSubschema of nonUniqueSubschemas) {
        const typeInSubschema = nonUniqueSubschema.transformedSchema.getType(
          mergedTypeInfo.typeName
        );
        const fields = typeInSubschema.getFields();
        const field = fields[fieldNode.name.value];
        if (field != null) {
          if (context != null && info != null) {
            const overrideHandler = nonUniqueSubschema.merge?.[mergedTypeInfo.typeName]?.fields?.[fieldNode.name.value]?.override;
            if (overrideHandler != null) {
              const overridden2 = handleOverrideByDelegation(
                info,
                context,
                overrideHandler
              );
              if (overridden2) {
                bestUniqueSubschema = nonUniqueSubschema;
                break;
              } else {
                continue;
              }
            }
          }
          const unavailableFields = extractUnavailableFields(
            nonUniqueSubschema.transformedSchema,
            field,
            fieldNode,
            (fieldType) => {
              if (!nonUniqueSubschema.merge?.[fieldType.name]) {
                let nonUniqueSubschemaSelections = (
                  // We have to cast it to `SelectionNode[]` because it is Readonly<SelectionNode[]> and it doesn't allow us to push new elements.
                  delegationMap.get(nonUniqueSubschema)?.selections
                );
                if (nonUniqueSubschemaSelections == null) {
                  nonUniqueSubschemaSelections = [];
                  delegationMap.set(nonUniqueSubschema, {
                    kind: Kind.SELECTION_SET,
                    selections: nonUniqueSubschemaSelections
                  });
                }
                nonUniqueSubschemaSelections.push(fieldNode);
                return false;
              }
              return true;
            }
          );
          const currentScore = calculateSelectionScore(
            unavailableFields,
            fragments
          );
          if (currentScore < bestScore) {
            bestScore = currentScore;
            bestUniqueSubschema = nonUniqueSubschema;
          }
        }
      }
      let existingSelections = delegationMap.get(bestUniqueSubschema);
      if (existingSelections != null) {
        existingSelections.selections.push(fieldNode);
      } else {
        delegationMap.set(bestUniqueSubschema, {
          kind: Kind.SELECTION_SET,
          selections: [fieldNode]
        });
      }
    }
  }
  if (delegationMap.size > 1 && !overriddenOverall) {
    optimizeDelegationMap(
      delegationMap,
      mergedTypeInfo.typeName,
      fragments,
      stitchingInfo
    );
  }
  return {
    delegationMap,
    proxiableSubschemas,
    nonProxiableSubschemas,
    unproxiableFieldNodes
  };
}
const calculateSelectionScore = memoize2(
  function calculateSelectionScore2(selections, fragments) {
    let score = 0;
    for (const selectionNode of selections) {
      switch (selectionNode.kind) {
        case Kind.FIELD:
          score++;
          if (selectionNode.selectionSet?.selections) {
            score += calculateSelectionScore2(
              selectionNode.selectionSet.selections,
              fragments
            );
          }
          break;
        case Kind.INLINE_FRAGMENT:
          score += calculateSelectionScore2(
            selectionNode.selectionSet.selections,
            fragments
          );
          break;
        case Kind.FRAGMENT_SPREAD:
          const fragment = fragments?.[selectionNode.name.value];
          if (fragment) {
            score += calculateSelectionScore2(
              fragment.selectionSet.selections,
              fragments
            );
          }
          break;
      }
    }
    return score;
  }
);
function getStitchingInfo(schema) {
  const stitchingInfo = schema.extensions?.["stitchingInfo"];
  if (!stitchingInfo) {
    throw new Error(`Schema is not a stitched schema.`);
  }
  return stitchingInfo;
}
function createDelegationPlanBuilder(mergedTypeInfo) {
  mergedTypeInfo.nonMemoizedDelegationPlanBuilder = function delegationPlanBuilder(schema, sourceSubschema, variableValues, fragments, fieldNodes, context, info, parent) {
    const stitchingInfo = getStitchingInfo(schema);
    const targetSubschemas = mergedTypeInfo?.targetSubschemas.get(sourceSubschema);
    if (!targetSubschemas || !targetSubschemas.length) {
      return [];
    }
    const typeName = mergedTypeInfo.typeName;
    const typeInSubschema = sourceSubschema.transformedSchema.getType(
      typeName
    );
    let providedSelectionNode;
    const parentFieldName = fieldNodes[0]?.name.value;
    if (info?.parentType && parentFieldName) {
      const providedSelectionsByField = stitchingInfo.mergedTypes[info.parentType.name]?.providedSelectionsByField?.get(sourceSubschema);
      providedSelectionNode = providedSelectionsByField?.[parentFieldName];
    }
    const fieldsNotInSubschema = getFieldsNotInSubschema(
      schema,
      stitchingInfo,
      schema.getType(typeName),
      mergedTypeInfo.typeMaps.get(sourceSubschema)?.[typeName],
      fieldNodes,
      fragments,
      variableValues,
      sourceSubschema,
      providedSelectionNode,
      context,
      info
    );
    if (!fieldsNotInSubschema.length) {
      return [];
    }
    let delegationMaps = [];
    let sourceSubschemas = createSubschemas(sourceSubschema);
    const initialSourceSubschemas = sourceSubschemas;
    const fetchedFieldsByType = /* @__PURE__ */ new Map();
    if (parent != null) {
      seedFetchedFieldsFromParent(
        fetchedFieldsByType,
        typeName,
        parent,
        mergedTypeInfo,
        schema
      );
    }
    let delegationStage = calculateDelegationStage(
      mergedTypeInfo,
      sourceSubschemas,
      targetSubschemas,
      fieldsNotInSubschema,
      fragments,
      context,
      info,
      stitchingInfo,
      initialSourceSubschemas,
      fetchedFieldsByType
    );
    let { delegationMap } = delegationStage;
    while (delegationMap.size) {
      delegationMaps.push(delegationMap);
      recordFetchedFields(
        fetchedFieldsByType,
        mergedTypeInfo.typeName,
        delegationMap,
        fragments,
        mergedTypeInfo,
        stitchingInfo
      );
      const {
        proxiableSubschemas,
        nonProxiableSubschemas,
        unproxiableFieldNodes
      } = delegationStage;
      sourceSubschemas = combineSubschemas(
        sourceSubschemas,
        proxiableSubschemas
      );
      delegationStage = calculateDelegationStage(
        mergedTypeInfo,
        sourceSubschemas,
        nonProxiableSubschemas,
        unproxiableFieldNodes,
        fragments,
        context,
        info,
        stitchingInfo,
        initialSourceSubschemas,
        fetchedFieldsByType
      );
      delegationMap = delegationStage.delegationMap;
    }
    if (isAbstractType(typeInSubschema) && fieldsNotInSubschema.some(
      (fieldNode) => fieldNode.name.value === "__typename"
    )) {
      const fragmentSelections = [];
      for (const fieldNode of fieldNodes) {
        if (fieldNode.selectionSet) {
          for (const selection of fieldNode.selectionSet.selections) {
            if (selection.kind === Kind.INLINE_FRAGMENT || selection.kind === Kind.FRAGMENT_SPREAD) {
              fragmentSelections.push(selection);
            }
          }
        }
      }
      const implementedSubschemas = targetSubschemas.filter((subschema) => {
        const typeInTargetSubschema = mergedTypeInfo.typeMaps.get(subschema)?.[typeName];
        return isAbstractType(typeInTargetSubschema) && subschema.transformedSchema.getPossibleTypes(typeInTargetSubschema).length;
      });
      let added = false;
      for (const implementedSubgraphs of implementedSubschemas) {
        for (const delegationMap2 of delegationMaps) {
          const existingSelections = delegationMap2.get(implementedSubgraphs)?.selections;
          if (existingSelections) {
            existingSelections.push({
              kind: Kind.FIELD,
              name: {
                kind: Kind.NAME,
                value: "__typename"
              }
            });
            existingSelections.push(...fragmentSelections);
            added = true;
            break;
          }
          if (added) {
            break;
          }
        }
      }
      if (!added) {
        const subschemaWithTypeName = implementedSubschemas[0];
        if (subschemaWithTypeName) {
          const delegationStageToFetchTypeName = /* @__PURE__ */ new Map();
          delegationStageToFetchTypeName.set(subschemaWithTypeName, {
            kind: Kind.SELECTION_SET,
            selections: [
              {
                kind: Kind.FIELD,
                name: {
                  kind: Kind.NAME,
                  value: "__typename"
                }
              },
              ...fragmentSelections
            ]
          });
          delegationMaps.push(delegationStageToFetchTypeName);
        }
      }
    }
    delegationMaps = coalesceAdjacentDelegationMaps(
      delegationMaps,
      typeName,
      stitchingInfo
    );
    if (delegationStage.unproxiableFieldNodes.length && delegationStage.nonProxiableSubschemas.length) {
      leftOverByDelegationPlan.set(delegationMaps, {
        unproxiableFieldNodes: delegationStage.unproxiableFieldNodes,
        nonProxiableSubschemas: delegationStage.nonProxiableSubschemas,
        missingFieldsParentMap: /* @__PURE__ */ new Map(),
        missingFieldsParentDeferredMap: /* @__PURE__ */ new Map()
      });
    }
    return delegationMaps;
  };
  const dependsOnParent = mergedTypePlanDependsOnParent(mergedTypeInfo);
  return memoizeDelegationPlanBuilder(
    mergedTypeInfo.nonMemoizedDelegationPlanBuilder,
    dependsOnParent ? parentFieldPresenceKey : () => ""
  );
}
function mergedTypePlanDependsOnParent(mergedTypeInfo) {
  for (const fieldMap of mergedTypeInfo.fieldSelectionSets.values()) {
    if (fieldMap != null && Object.keys(fieldMap).length > 0) {
      return true;
    }
  }
  return false;
}
function seedFetchedFieldsFromParent(fetchedFieldsByType, typeName, parent, mergedTypeInfo, schema) {
  if (parent == null || typeof parent !== "object") {
    return;
  }
  const concrete = typeof parent.__typename === "string" ? parent.__typename : void 0;
  const typeNames = /* @__PURE__ */ new Set([typeName]);
  if (concrete) {
    typeNames.add(concrete);
    const concreteType = schema.getType(concrete);
    if (isObjectType(concreteType)) {
      for (const iface of concreteType.getInterfaces()) {
        typeNames.add(iface.name);
      }
    }
  }
  for (const tn of typeNames) {
    let set = fetchedFieldsByType.get(tn);
    if (!set) {
      set = /* @__PURE__ */ new Set();
      fetchedFieldsByType.set(tn, set);
    }
    for (const key of Object.keys(parent)) {
      if (key.startsWith("_") && key !== "__typename") {
        continue;
      }
      set.add(key);
    }
  }
  for (const key of Object.keys(parent)) {
    if (key.startsWith("_") && key !== "__typename") {
      continue;
    }
    const value = parent[key];
    if (value == null || typeof value !== "object") {
      continue;
    }
    const declared = resolveSeedFieldTypeName(
      typeName,
      key,
      mergedTypeInfo,
      schema
    );
    if (Array.isArray(value)) {
      for (const item of value) {
        if (item != null && typeof item === "object") {
          const itemType = (typeof item.__typename === "string" ? item.__typename : void 0) ?? declared;
          if (itemType) {
            seedFetchedFieldsFromParent(
              fetchedFieldsByType,
              itemType,
              item,
              mergedTypeInfo,
              schema
            );
          }
        }
      }
    } else {
      const childType = (typeof value.__typename === "string" ? value.__typename : void 0) ?? declared;
      if (childType) {
        seedFetchedFieldsFromParent(
          fetchedFieldsByType,
          childType,
          value,
          mergedTypeInfo,
          schema
        );
      }
      if (declared && declared !== childType) {
        seedFetchedFieldsFromParent(
          fetchedFieldsByType,
          declared,
          value,
          mergedTypeInfo,
          schema
        );
      }
    }
  }
}
function resolveSeedFieldTypeName(typeName, fieldName, mergedTypeInfo, schema) {
  const fromSchema = schema.getType(typeName);
  if (isObjectType(fromSchema) || isInterfaceType(fromSchema)) {
    const field = fromSchema.getFields()[fieldName];
    if (field) {
      return getNamedType(field.type).name;
    }
  }
  for (const typeMap of mergedTypeInfo.typeMaps.values()) {
    const t = typeMap[typeName];
    if (!isObjectType(t) && !isInterfaceType(t)) {
      continue;
    }
    const field = t.getFields()[fieldName];
    if (field) {
      return getNamedType(field.type).name;
    }
  }
  return void 0;
}
const createSubschemas = memoize1(function createSubschemas2(sourceSubschema) {
  return [sourceSubschema];
});
const combineSubschemas = memoize2(function combineSubschemas2(sourceSubschemas, additionalSubschemas) {
  return sourceSubschemas.concat(additionalSubschemas);
});
const subschemaTypesContainSelectionSet = memoize3(
  function subschemaTypesContainSelectionSet2(mergedTypeInfo, sourceSubchemas, selectionSet) {
    return typesContainSelectionSet(
      sourceSubchemas.map(
        (sourceSubschema) => sourceSubschema.transformedSchema.getType(
          mergedTypeInfo.typeName
        )
      ),
      selectionSet
    );
  }
);
function getFieldsFromCompositeType(type) {
  if (isObjectType(type) || isInterfaceType(type)) {
    return type.getFields();
  }
  if (isUnionType(type)) {
    const fields = /* @__PURE__ */ Object.create(null);
    for (const member of type.getTypes()) {
      Object.assign(fields, member.getFields());
    }
    return fields;
  }
  return /* @__PURE__ */ Object.create(null);
}
function typesContainSelectionSet(types, selectionSet) {
  const fieldMaps = types.map((type) => getFieldsFromCompositeType(type));
  for (const selection of selectionSet.selections) {
    if (selection.kind === Kind.FIELD) {
      const fields = fieldMaps.map((fieldMap) => fieldMap[selection.name.value]).filter((field) => field != null);
      if (!fields.length) {
        return false;
      }
      if (selection.selectionSet != null) {
        return typesContainSelectionSet(
          fields.map(
            (field) => getNamedType(field.type)
          ),
          selection.selectionSet
        );
      }
    } else if (selection.kind === Kind.INLINE_FRAGMENT && selection.typeCondition?.name.value === types[0]?.name) {
      return typesContainSelectionSet(types, selection.selectionSet);
    }
  }
  return true;
}
function selectionSetAvailableCloneLess(mergedTypeInfo, initialSourceSubschemas, fetchedFieldsByType, selectionSet, typeName) {
  const useInitialSchema = typeName === mergedTypeInfo.typeName;
  const initialFieldMaps = useInitialSchema ? initialSourceSubschemas.map((s) => {
    const t = s.transformedSchema.getType(typeName);
    return isObjectType(t) || isInterfaceType(t) ? t.getFields() : null;
  }) : [];
  const fetched = fetchedFieldsByType.get(typeName);
  for (const selection of selectionSet.selections) {
    if (selection.kind !== Kind.FIELD) {
      if (selection.kind === Kind.INLINE_FRAGMENT && (selection.typeCondition == null || selection.typeCondition.name.value === typeName)) {
        if (!selectionSetAvailableCloneLess(
          mergedTypeInfo,
          initialSourceSubschemas,
          fetchedFieldsByType,
          selection.selectionSet,
          typeName
        )) {
          return false;
        }
      }
      continue;
    }
    const fieldName = selection.name.value;
    if (fieldName === "__typename") {
      continue;
    }
    const onInitial = initialFieldMaps.some((fm, i) => {
      if (fm?.[fieldName] == null) {
        return false;
      }
      const source = initialSourceSubschemas[i];
      const mergeFields = source?.merge?.[typeName]?.fields;
      if (mergeFields?.[fieldName]?.computed) {
        return false;
      }
      return true;
    });
    const onFetched = fetched?.has(fieldName) === true;
    if (!onInitial && !onFetched) {
      return false;
    }
    if (selection.selectionSet != null) {
      let nestedTypeName;
      for (const s of initialSourceSubschemas) {
        const t = s.transformedSchema.getType(typeName);
        if (!isObjectType(t) && !isInterfaceType(t)) {
          continue;
        }
        const field = t.getFields()[fieldName];
        if (field) {
          nestedTypeName = getNamedType(field.type).name;
          break;
        }
      }
      if (!nestedTypeName) {
        for (const typeMap of mergedTypeInfo.typeMaps.values()) {
          const t = typeMap[typeName];
          if (!isObjectType(t) && !isInterfaceType(t)) {
            continue;
          }
          const field = t.getFields()[fieldName];
          if (field) {
            nestedTypeName = getNamedType(field.type).name;
            break;
          }
        }
      }
      if (nestedTypeName && !selectionSetAvailableCloneLess(
        mergedTypeInfo,
        initialSourceSubschemas,
        fetchedFieldsByType,
        selection.selectionSet,
        nestedTypeName
      )) {
        return false;
      }
    }
  }
  return true;
}
function recordFetchedFields(fetchedFieldsByType, typeName, delegationMap, fragments, mergedTypeInfo, stitchingInfo) {
  for (const [subschema, selectionSet] of delegationMap) {
    collectFetchedFieldsDeep(
      fetchedFieldsByType,
      typeName,
      selectionSet,
      fragments,
      mergedTypeInfo,
      subschema,
      stitchingInfo
    );
  }
}
function subschemaOwnsField(stitchingInfo, typeName, fieldName, subschema) {
  if (fieldName === "__typename") {
    return true;
  }
  const mti = stitchingInfo.mergedTypes[typeName];
  if (mti == null) {
    const t2 = subschema.transformedSchema.getType(typeName);
    return (isObjectType(t2) || isInterfaceType(t2)) && t2.getFields()[fieldName] != null;
  }
  const unique = mti.uniqueFields[fieldName];
  if (unique != null) {
    return unique === subschema;
  }
  const nonUnique = mti.nonUniqueFields[fieldName];
  if (nonUnique != null) {
    return nonUnique.includes(subschema);
  }
  const t = subschema.transformedSchema.getType(typeName);
  return (isObjectType(t) || isInterfaceType(t)) && t.getFields()[fieldName] != null;
}
function collectFetchedFieldsDeep(fetchedFieldsByType, typeName, selectionSet, fragments, mergedTypeInfo, subschema, stitchingInfo) {
  let set = fetchedFieldsByType.get(typeName);
  if (!set) {
    set = /* @__PURE__ */ new Set();
    fetchedFieldsByType.set(typeName, set);
  }
  for (const selection of selectionSet.selections) {
    if (selection.kind === Kind.FIELD) {
      const fieldName = selection.name.value;
      const owned = subschemaOwnsField(
        stitchingInfo,
        typeName,
        fieldName,
        subschema
      );
      if (owned) {
        set.add(fieldName);
      }
      if (selection.selectionSet == null || fieldName === "__typename") {
        continue;
      }
      const nestedTypeName = resolveSeedFieldTypeName(
        typeName,
        fieldName,
        mergedTypeInfo,
        subschema.transformedSchema
      );
      if (nestedTypeName) {
        collectFetchedFieldsDeep(
          fetchedFieldsByType,
          nestedTypeName,
          selection.selectionSet,
          fragments,
          mergedTypeInfo,
          subschema,
          stitchingInfo
        );
      }
    } else if (selection.kind === Kind.INLINE_FRAGMENT) {
      collectFetchedFieldsDeep(
        fetchedFieldsByType,
        selection.typeCondition?.name.value ?? typeName,
        selection.selectionSet,
        fragments,
        mergedTypeInfo,
        subschema,
        stitchingInfo
      );
    } else if (selection.kind === Kind.FRAGMENT_SPREAD) {
      const frag = fragments[selection.name.value];
      if (frag) {
        collectFetchedFieldsDeep(
          fetchedFieldsByType,
          frag.typeCondition.name.value,
          frag.selectionSet,
          fragments,
          mergedTypeInfo,
          subschema,
          stitchingInfo
        );
      }
    }
  }
}

function entryPointAppliesToParent(entryPoint, parent) {
  if (parent == null || entryPoint.selectionSet == null) {
    return parent != null;
  }
  const selectionSet = typeof entryPoint.selectionSet === "string" ? parseSelectionSet(entryPoint.selectionSet, { noLocation: true }) : entryPoint.selectionSet;
  return valueSatisfiesSelectionSet(parent, selectionSet);
}
function valueSatisfiesSelectionSet(value, selectionSet) {
  if (value == null || typeof value !== "object") {
    return false;
  }
  if (Array.isArray(value)) {
    if (!value.length) {
      return false;
    }
    return value.every(
      (item) => item == null || valueSatisfiesSelectionSet(item, selectionSet)
    );
  }
  for (const sel of selectionSet.selections) {
    if (sel.kind === Kind.FIELD) {
      if (sel.name.value === "__typename") {
        continue;
      }
      const child = value[sel.name.value];
      if (child === void 0) {
        return false;
      }
      if (sel.selectionSet != null) {
        if (!valueSatisfiesSelectionSet(child, sel.selectionSet)) {
          return false;
        }
      }
      continue;
    }
    if (sel.kind === Kind.INLINE_FRAGMENT && sel.selectionSet != null) {
      if (!valueSatisfiesSelectionSet(value, sel.selectionSet)) {
        return false;
      }
    }
  }
  return true;
}

function getMergeOperation(info, subschema, fieldName) {
  if (info.operation.operation !== "mutation" || fieldName == null) {
    return "query";
  }
  const schema = subschema.transformedSchema;
  if (schema.getMutationType()?.getFields()[fieldName] != null) {
    return "mutation";
  }
  return "query";
}
function overlayMergedTypeEntryPoint(mergedTypeConfig, entryPoint) {
  const {
    entryPoints: _entryPoints,
    fields: _fields,
    canonical: _canonical,
    ...parentDefaults
  } = mergedTypeConfig;
  return {
    ...parentDefaults,
    ...entryPoint
  };
}
function createMultiEntryMergedTypeResolver(mergedTypeConfig, mergedType) {
  const entryPoints = mergedTypeConfig.entryPoints;
  if (entryPoints == null || entryPoints.length < 2) {
    return mergedTypeConfig.resolve ?? createMergedTypeResolver(mergedTypeConfig, mergedType);
  }
  const prepared = entryPoints.map((ep) => {
    const overlay = overlayMergedTypeEntryPoint(mergedTypeConfig, ep);
    return {
      entryPoint: overlay,
      resolver: overlay.resolve ?? createMergedTypeResolver(overlay, mergedType)
    };
  });
  if (prepared.every((p) => p.resolver == null)) {
    return void 0;
  }
  return function multiEntryMergedTypeResolver(originalResult, context, info, subschema, selectionSet, _key, type, skipTypeMerging = true) {
    const tryAt = (i) => {
      if (i >= prepared.length) {
        return originalResult;
      }
      const { entryPoint: ep, resolver } = prepared[i];
      if (resolver == null || !entryPointAppliesToParent(ep, originalResult)) {
        return tryAt(i + 1);
      }
      if (ep.key == null) {
        return resolver(
          originalResult,
          context,
          info,
          subschema,
          selectionSet,
          void 0,
          type,
          skipTypeMerging
        );
      }
      return handleMaybePromise(
        () => ep.key(originalResult),
        (key) => {
          if (key == null) {
            return tryAt(i + 1);
          }
          return resolver(
            originalResult,
            context,
            info,
            subschema,
            selectionSet,
            key,
            type,
            skipTypeMerging
          );
        }
      );
    };
    return tryAt(0);
  };
}
function createMergedTypeResolver(mergedTypeResolverOptions, mergedType) {
  const { fieldName, argsFromKeys, valuesFromResults, args } = mergedTypeResolverOptions;
  function getType(info) {
    if (!mergedType) {
      return getNamedType(info.returnType);
    }
    if (typeof mergedType === "string") {
      return info.schema.getType(mergedType);
    }
    return mergedType;
  }
  if (argsFromKeys != null) {
    return function mergedBatchedTypeResolver(_originalResult, context, info, subschema, selectionSet, key, type = getType(info), skipTypeMerging = true) {
      return batchDelegateToSchema({
        schema: subschema,
        operation: getMergeOperation(info, subschema, fieldName),
        fieldName,
        returnType: new GraphQLList(type),
        key,
        argsFromKeys,
        valuesFromResults,
        selectionSet,
        context,
        info,
        skipTypeMerging,
        dataLoaderOptions: mergedTypeResolverOptions.dataLoaderOptions
      });
    };
  }
  if (args != null) {
    return function mergedTypeResolver(originalResult, context, info, subschema, selectionSet, _key, type = getType(info), skipTypeMerging = true) {
      return delegateToSchema({
        schema: subschema,
        operation: getMergeOperation(info, subschema, fieldName),
        fieldName,
        returnType: type,
        args: args(originalResult),
        selectionSet,
        context,
        info,
        skipTypeMerging
      });
    };
  }
  return void 0;
}

function createStitchingInfo(subschemaMap, typeCandidates, mergeTypes) {
  const mergedTypes = createMergedTypes(typeCandidates, mergeTypes);
  return {
    subschemaMap,
    fieldNodesByType: /* @__PURE__ */ Object.create(null),
    fieldNodesByField: /* @__PURE__ */ Object.create(null),
    dynamicSelectionSetsByField: /* @__PURE__ */ Object.create(null),
    mergedTypes
  };
}
function createMergedTypes(typeCandidates, mergeTypes) {
  const mergedTypes = /* @__PURE__ */ Object.create(
    null
  );
  const typeInterfacesMap = /* @__PURE__ */ Object.create(null);
  for (const typeName in typeCandidates) {
    if (typeCandidates[typeName]) {
      for (const { type } of typeCandidates[typeName]) {
        if ("getInterfaces" in type) {
          const interfaces = type.getInterfaces();
          for (const iface of interfaces) {
            const interfaceName = iface.name;
            let implementingTypes = typeInterfacesMap[typeName];
            if (implementingTypes == null) {
              implementingTypes = /* @__PURE__ */ new Set();
              typeInterfacesMap[typeName] = implementingTypes;
            }
            implementingTypes.add(interfaceName);
          }
        }
      }
    }
  }
  for (const typeName in typeCandidates) {
    let hasOverrides = false;
    const typeCandidatesOfTypeName = typeCandidates[typeName];
    if (!typeCandidatesOfTypeName) {
      throw new Error(`Invalid type candidates for type name ${typeName}`);
    }
    const typeCandidate = typeCandidatesOfTypeName[0];
    if (isObjectType(typeCandidate?.type) || isInterfaceType(typeCandidate?.type) || isUnionType(typeCandidate?.type)) {
      const typeCandidatesWithMergedTypeConfig = typeCandidatesOfTypeName.filter(
        (typeCandidate2) => typeCandidate2.transformedSubschema != null && typeCandidate2.transformedSubschema.merge != null && typeName in typeCandidate2.transformedSubschema.merge
      );
      if (mergeTypes === true || typeof mergeTypes === "function" && mergeTypes(typeCandidatesOfTypeName, typeName) || Array.isArray(mergeTypes) && mergeTypes.includes(typeName) || typeCandidatesWithMergedTypeConfig.length) {
        const targetSubschemas = [];
        const typeMaps = /* @__PURE__ */ new Map();
        const supportedBySubschemas = /* @__PURE__ */ Object.create({});
        const selectionSets = /* @__PURE__ */ new Map();
        const entryPointSelectionSets = /* @__PURE__ */ new Map();
        const fieldSelectionSets = /* @__PURE__ */ new Map();
        const resolvers = /* @__PURE__ */ new Map();
        const providedSelectionsByField = /* @__PURE__ */ new Map();
        for (const typeCandidate2 of typeCandidatesOfTypeName) {
          const subschema = typeCandidate2.transformedSubschema;
          if (subschema == null) {
            continue;
          }
          typeMaps.set(subschema, subschema.transformedSchema.getTypeMap());
          let mergedTypeConfig2 = subschema?.merge?.[typeName];
          if (!mergedTypeConfig2) {
            for (const interfaceName of typeInterfacesMap[typeName] ?? []) {
              mergedTypeConfig2 = subschema?.merge?.[interfaceName];
              if (mergedTypeConfig2) {
                break;
              }
            }
          }
          if (mergedTypeConfig2 == null) {
            continue;
          }
          const multiEntryPoints = mergedTypeConfig2.entryPoints != null && mergedTypeConfig2.entryPoints.length >= 2 ? mergedTypeConfig2.entryPoints : null;
          if (multiEntryPoints) {
            const epSels = [];
            for (const ep of multiEntryPoints) {
              if (ep.selectionSet) {
                epSels.push(
                  parseSelectionSet(ep.selectionSet, { noLocation: true })
                );
              }
            }
            if (epSels.length) {
              entryPointSelectionSets.set(subschema, epSels);
            }
          } else if (mergedTypeConfig2.selectionSet) {
            const selectionSet = parseSelectionSet(
              mergedTypeConfig2.selectionSet,
              {
                noLocation: true
              }
            );
            selectionSets.set(subschema, selectionSet);
          }
          if (mergedTypeConfig2.fields) {
            const parsedFieldSelectionSets = /* @__PURE__ */ Object.create(null);
            for (const fieldName in mergedTypeConfig2.fields) {
              if (mergedTypeConfig2.fields[fieldName]?.override) {
                hasOverrides = true;
              }
              if (mergedTypeConfig2.fields[fieldName]?.selectionSet) {
                const rawFieldSelectionSet = mergedTypeConfig2.fields[fieldName].selectionSet;
                parsedFieldSelectionSets[fieldName] = rawFieldSelectionSet ? parseSelectionSet(rawFieldSelectionSet, {
                  noLocation: true
                }) : void 0;
              }
              let providedSelectionSet = mergedTypeConfig2.fields[fieldName]?.provides;
              if (providedSelectionSet) {
                providedSelectionSet = visit(providedSelectionSet, {
                  [Kind.SELECTION_SET](node) {
                    const typeNameField = node.selections.find(
                      (selection) => selection.kind === Kind.FIELD && selection.name.value === "__typename"
                    );
                    if (typeNameField) {
                      return node;
                    }
                    return {
                      ...node,
                      selections: [
                        ...node.selections,
                        {
                          kind: Kind.FIELD,
                          name: {
                            kind: Kind.NAME,
                            value: "__typename"
                          }
                        }
                      ]
                    };
                  }
                });
                let providedSelectionsForSubschema = providedSelectionsByField.get(subschema);
                if (providedSelectionsForSubschema == null) {
                  providedSelectionsForSubschema = /* @__PURE__ */ Object.create({});
                  providedSelectionsByField.set(
                    subschema,
                    providedSelectionsForSubschema
                  );
                }
                providedSelectionsForSubschema[fieldName] = providedSelectionSet;
              }
            }
            fieldSelectionSets.set(subschema, parsedFieldSelectionSets);
          }
          const type = subschema.transformedSchema.getType(typeName);
          const resolver = mergedTypeConfig2.resolve ?? (multiEntryPoints ? createMultiEntryMergedTypeResolver(mergedTypeConfig2, type) : createMergedTypeResolver(mergedTypeConfig2, type));
          if (resolver == null) {
            continue;
          }
          const keyFn = multiEntryPoints ? void 0 : mergedTypeConfig2.key;
          resolvers.set(
            subschema,
            keyFn ? function batchMergedTypeResolverWrapper(originalResult, context, info, subschema2, selectionSet, keyOrType, type2, skipTypeMerging) {
              return handleMaybePromise(
                () => keyFn(originalResult),
                (key) => resolver(
                  originalResult,
                  context,
                  info,
                  subschema2,
                  selectionSet,
                  key,
                  keyOrType ?? type2,
                  skipTypeMerging
                )
              );
            } : resolver
          );
          targetSubschemas.push(subschema);
          if (isObjectType(type) || isInterfaceType(type)) {
            const fieldMap = type.getFields();
            const keySelectionSets = entryPointSelectionSets.get(subschema) ?? (selectionSets.has(subschema) ? [selectionSets.get(subschema)] : []);
            for (const fieldName in fieldMap) {
              const field = fieldMap[fieldName];
              const fieldType = getNamedType(field?.type);
              if (isLeafType(fieldType) && keySelectionSets.length > 0 && keySelectionSets.every(
                (selectionSet) => selectionSetContainsTopLevelField(selectionSet, fieldName)
              )) {
                continue;
              }
              if (!supportedBySubschemas[fieldName]) {
                supportedBySubschemas[fieldName] = [];
              }
              supportedBySubschemas[fieldName]?.push(subschema);
            }
          }
        }
        const sourceSubschemas = typeCandidates[typeName]?.map((typeCandidate2) => typeCandidate2?.transformedSubschema).filter(isSome);
        const targetSubschemasBySubschema = /* @__PURE__ */ new Map();
        if (sourceSubschemas) {
          for (const subschema of sourceSubschemas) {
            const ownsComputedOrRequires = fieldSelectionSets.get(subschema) != null && Object.keys(fieldSelectionSets.get(subschema)).length > 0;
            const filteredSubschemas = ownsComputedOrRequires ? targetSubschemas : targetSubschemas.filter((s) => s !== subschema);
            if (filteredSubschemas.length) {
              targetSubschemasBySubschema.set(subschema, filteredSubschemas);
            }
          }
        }
        const mergedTypeConfig = {
          typeName,
          targetSubschemas: targetSubschemasBySubschema,
          typeMaps,
          selectionSets,
          entryPointSelectionSets,
          fieldSelectionSets,
          uniqueFields: /* @__PURE__ */ Object.create({}),
          nonUniqueFields: /* @__PURE__ */ Object.create({}),
          resolvers,
          providedSelectionsByField
        };
        mergedTypes[typeName] = mergedTypeConfig;
        mergedTypeConfig.delegationPlanBuilder = createDelegationPlanBuilder(
          mergedTypeConfig
        );
        if (hasOverrides) {
          mergedTypeConfig.delegationPlanBuilder = mergedTypeConfig.nonMemoizedDelegationPlanBuilder;
        }
        for (const fieldName in supportedBySubschemas) {
          if (supportedBySubschemas[fieldName]?.length === 1 && supportedBySubschemas[fieldName][0]) {
            mergedTypeConfig.uniqueFields[fieldName] = supportedBySubschemas[fieldName][0];
          } else if (supportedBySubschemas[fieldName]) {
            mergedTypeConfig.nonUniqueFields[fieldName] = supportedBySubschemas[fieldName];
          }
        }
      }
    }
  }
  return mergedTypes;
}
function completeStitchingInfo(stitchingInfo, resolvers, schema) {
  const {
    fieldNodesByType,
    fieldNodesByField,
    dynamicSelectionSetsByField,
    mergedTypes
  } = stitchingInfo;
  const rootTypes = [schema.getQueryType(), schema.getMutationType()];
  for (const rootType of rootTypes) {
    if (rootType) {
      const rootTypeFields = rootType.getFields();
      fieldloop: for (const fieldName in rootTypeFields) {
        const field = rootTypeFields[fieldName];
        if (field != null) {
          const fieldType = getNamedType(field.type);
          if (rootType.name === fieldType.name) {
            fieldNodesByType[rootType.name] ||= [
              parseSelectionSet("{ __typename }", { noLocation: true }).selections[0]
            ];
            break fieldloop;
          }
        }
      }
    }
  }
  const typenameFieldNode = parseSelectionSet("{ __typename }", {
    noLocation: true
  }).selections[0];
  for (const typeName in mergedTypes) {
    const mergedTypeInfo = mergedTypes[typeName];
    if (mergedTypeInfo == null || mergedTypeInfo.resolvers.size === 0 || mergedTypeInfo.selectionSets.size > 0 || (mergedTypeInfo.entryPointSelectionSets?.size ?? 0) > 0) {
      continue;
    }
    const existing = fieldNodesByType[typeName];
    if (existing == null) {
      fieldNodesByType[typeName] = [typenameFieldNode];
    } else if (!existing.some((fieldNode) => fieldNode.name.value === "__typename")) {
      existing.push(typenameFieldNode);
    }
  }
  const selectionSetsByField = /* @__PURE__ */ Object.create(null);
  for (const typeName in mergedTypes) {
    const mergedTypeInfo = mergedTypes[typeName];
    if (mergedTypeInfo?.selectionSets == null && mergedTypeInfo?.entryPointSelectionSets == null && mergedTypeInfo?.fieldSelectionSets == null) {
      continue;
    }
    const applyKeySelectionSet = (subschemaConfig, selectionSet) => {
      const schema2 = subschemaConfig.transformedSchema;
      const type = schema2.getType(typeName);
      if (type == null) {
        return;
      }
      if (isObjectType(type) || isInterfaceType(type)) {
        const fields = type.getFields();
        for (const fieldName in fields) {
          const field = fields[fieldName];
          const fieldType = getNamedType(field?.type);
          if (selectionSet && isLeafType(fieldType) && selectionSetContainsTopLevelField(selectionSet, fieldName)) {
            continue;
          }
          updateSelectionSetMap(
            selectionSetsByField,
            typeName,
            fieldName,
            selectionSet,
            true
          );
        }
      }
      if (isAbstractType(type)) {
        updateSelectionSetMap(
          selectionSetsByField,
          typeName,
          "__typename",
          selectionSet
        );
      }
    };
    for (const [
      subschemaConfig,
      selectionSet
    ] of mergedTypeInfo.selectionSets) {
      applyKeySelectionSet(subschemaConfig, selectionSet);
    }
    if (mergedTypeInfo.entryPointSelectionSets) {
      for (const [
        subschemaConfig,
        selectionSets
      ] of mergedTypeInfo.entryPointSelectionSets) {
        for (const selectionSet of selectionSets) {
          applyKeySelectionSet(subschemaConfig, selectionSet);
        }
      }
    }
    for (const [, selectionSetFieldMap] of mergedTypeInfo.fieldSelectionSets) {
      for (const fieldName in selectionSetFieldMap) {
        const selectionSet = selectionSetFieldMap[fieldName];
        if (selectionSet) {
          updateSelectionSetMap(
            selectionSetsByField,
            typeName,
            fieldName,
            selectionSet,
            true
          );
        }
      }
    }
  }
  for (const typeName in resolvers) {
    const type = schema.getType(typeName);
    if (type === void 0 || isLeafType(type) || isInputObjectType(type) || isUnionType(type)) {
      continue;
    }
    const resolver = resolvers[typeName];
    for (const fieldName in resolver) {
      const field = resolver[fieldName];
      if (typeof field.selectionSet === "function") {
        if (!dynamicSelectionSetsByField[typeName]) {
          dynamicSelectionSetsByField[typeName] = /* @__PURE__ */ Object.create(null);
        }
        if (!dynamicSelectionSetsByField[typeName][fieldName]) {
          dynamicSelectionSetsByField[typeName][fieldName] = [];
        }
        dynamicSelectionSetsByField[typeName][fieldName].push(
          field.selectionSet
        );
      } else if (field.selectionSet) {
        const selectionSet = parseSelectionSet(field.selectionSet, {
          noLocation: true
        });
        updateSelectionSetMap(
          selectionSetsByField,
          typeName,
          fieldName,
          selectionSet
        );
      }
    }
  }
  const variableValues = getVariableValues(void 0);
  const fragments = /* @__PURE__ */ Object.create(null);
  const fieldNodeMap = /* @__PURE__ */ Object.create(null);
  for (const typeName in selectionSetsByField) {
    const type = schema.getType(typeName);
    const typeNames = isInterfaceType(type) ? [typeName, ...schema.getPossibleTypes(type).map((t) => t.name)] : [typeName];
    for (const fieldName in selectionSetsByField[typeName]) {
      for (const selectionSet of selectionSetsByField[typeName][fieldName]) {
        const { fields } = collectFields(
          schema,
          fragments,
          variableValues,
          type,
          selectionSet
        );
        for (const [, fieldNodes] of fields) {
          for (const fieldNode of fieldNodes) {
            const key = print(fieldNode);
            fieldNodeMap[key] ??= fieldNode;
            for (const name of typeNames) {
              updateArrayMap(
                fieldNodesByField,
                name,
                fieldName,
                fieldNodeMap[key]
              );
            }
          }
        }
      }
    }
  }
  return stitchingInfo;
}
function updateSelectionSetMap(map, typeName, fieldName, selectionSet, includeTypename) {
  if (includeTypename) {
    const typenameSelectionSet = parseSelectionSet("{ __typename }", {
      noLocation: true
    });
    updateArrayMap(
      map,
      typeName,
      fieldName,
      selectionSet,
      typenameSelectionSet
    );
    return;
  }
  updateArrayMap(map, typeName, fieldName, selectionSet);
}
function updateArrayMap(map, typeName, fieldName, value, initialValue) {
  if (map[typeName] == null) {
    const initialItems = initialValue === void 0 ? [value] : [initialValue, value];
    map[typeName] = {
      [fieldName]: initialItems
    };
  } else if (map[typeName][fieldName] == null) {
    const initialItems = initialValue === void 0 ? [value] : [initialValue, value];
    map[typeName][fieldName] = initialItems;
  } else {
    map[typeName][fieldName].push(value);
  }
}
function addStitchingInfo(stitchedSchema, stitchingInfo) {
  stitchedSchema.extensions = {
    ...stitchedSchema.extensions,
    stitchingInfo
  };
}
function selectionSetContainsTopLevelField(selectionSet, fieldName) {
  return selectionSet.selections.some(
    (selection) => selection.kind === Kind.FIELD && selection.name.value === fieldName
  );
}

class DeferComputedFieldsTransform {
  computedByType;
  keyFieldsByType;
  mergeEntryFieldNames;
  schema;
  constructor(schema, computedByType, keyFieldsByType, mergeEntryFieldNames) {
    this.schema = schema;
    this.computedByType = computedByType;
    this.keyFieldsByType = keyFieldsByType;
    this.mergeEntryFieldNames = mergeEntryFieldNames;
  }
  transformRequest(originalRequest, delegationContext) {
    if (delegationContext.skipTypeMerging && this.mergeEntryFieldNames.has(delegationContext.fieldName)) {
      return originalRequest;
    }
    return {
      ...originalRequest,
      document: stripComputedFields(
        originalRequest.document,
        this.schema,
        this.computedByType,
        this.keyFieldsByType
      )
    };
  }
}
function stripComputedFields(document, schema, computedByType, keyFieldsByType) {
  if (!computedByType.size) {
    return document;
  }
  const typeInfo = new TypeInfo(schema);
  return visit(
    document,
    visitWithTypeInfo(typeInfo, {
      [Kind.SELECTION_SET]: {
        leave(node) {
          const parentType = typeInfo.getParentType();
          if (parentType == null) {
            return node;
          }
          const typeName = getNamedType(parentType).name;
          const computed = computedByType.get(typeName);
          if (!computed?.size) {
            return node;
          }
          const keys = keyFieldsByType.get(typeName);
          const selections = filterComputedSelections(
            node.selections,
            computed,
            keys
          );
          if (selections === node.selections) {
            return node;
          }
          if (!selections.length) {
            return null;
          }
          return {
            kind: Kind.SELECTION_SET,
            selections
          };
        }
      }
    })
  );
}
function mergeSelectionSets(target, source) {
  const next = [...target.selections];
  const indexByKey = /* @__PURE__ */ new Map();
  for (let i = 0; i < next.length; i++) {
    const sel = next[i];
    if (sel.kind === Kind.FIELD && sel.alias == null) {
      indexByKey.set(sel.name.value, i);
    }
  }
  for (const sel of source.selections) {
    if (sel.kind !== Kind.FIELD || sel.alias != null) {
      next.push(sel);
      continue;
    }
    const existingIdx = indexByKey.get(sel.name.value);
    if (existingIdx == null) {
      indexByKey.set(sel.name.value, next.length);
      next.push(sel);
      continue;
    }
    const existing = next[existingIdx];
    if (existing.kind === Kind.FIELD && existing.selectionSet != null && sel.selectionSet != null) {
      next[existingIdx] = {
        ...existing,
        selectionSet: mergeSelectionSets(
          existing.selectionSet,
          sel.selectionSet
        )
      };
    } else if (existing.kind === Kind.FIELD && existing.selectionSet == null && sel.selectionSet != null) {
      next[existingIdx] = sel;
    }
  }
  return { kind: Kind.SELECTION_SET, selections: next };
}
function filterComputedSelections(selections, computed, keyFields) {
  let strippedComputed = false;
  const presentUnaliased = /* @__PURE__ */ new Map();
  const next = [];
  for (const selection of selections) {
    if (selection.kind === Kind.FIELD) {
      if (computed.has(selection.name.value)) {
        strippedComputed = true;
        continue;
      }
      if (selection.alias == null) {
        presentUnaliased.set(selection.name.value, next.length);
      }
    }
    next.push(selection);
  }
  if (!strippedComputed) {
    return selections;
  }
  if (!presentUnaliased.has("__typename")) {
    next.unshift({
      kind: Kind.FIELD,
      name: { kind: Kind.NAME, value: "__typename" }
    });
    for (const [name, idx] of presentUnaliased) {
      presentUnaliased.set(name, idx + 1);
    }
    presentUnaliased.set("__typename", 0);
  }
  if (keyFields) {
    for (const keyField of keyFields) {
      if (computed.has(keyField.name.value)) {
        continue;
      }
      const existingIdx = presentUnaliased.get(keyField.name.value);
      if (existingIdx == null) {
        presentUnaliased.set(keyField.name.value, next.length);
        next.push(keyField);
        continue;
      }
      const existing = next[existingIdx];
      if (existing?.kind === Kind.FIELD && keyField.selectionSet != null && existing.selectionSet != null) {
        next[existingIdx] = {
          ...existing,
          selectionSet: mergeSelectionSets(
            existing.selectionSet,
            keyField.selectionSet
          )
        };
      } else if (existing?.kind === Kind.FIELD && keyField.selectionSet != null && existing.selectionSet == null) {
        next[existingIdx] = keyField;
      }
    }
  }
  return next;
}
function collectKeyFieldNodes(schema, typeName, selectionSetStr) {
  if (!selectionSetStr) {
    return [];
  }
  const type = schema.getType(typeName);
  if (!type || !isObjectType(type)) {
    return [];
  }
  const parsed = parseSelectionSet(selectionSetStr, { noLocation: true });
  const collected = collectFields(
    schema,
    {},
    getVariableValues(void 0),
    type,
    parsed
  );
  const fields = [];
  for (const [, nodes] of collected.fields) {
    const first = nodes[0];
    if (first != null) {
      fields.push(first);
    }
  }
  return fields;
}
function mergeKeyFieldNodes(into, nodes) {
  for (const node of nodes) {
    const existing = into.get(node.name.value);
    if (existing == null) {
      into.set(node.name.value, node);
      continue;
    }
    if (node.selectionSet != null && existing.selectionSet == null) {
      into.set(node.name.value, node);
    }
  }
}
function deferComputedFieldsTransformer(subschemaConfig) {
  if (subschemaConfig.merge == null) {
    return [subschemaConfig];
  }
  const computedByType = /* @__PURE__ */ new Map();
  const keyFieldsByType = /* @__PURE__ */ new Map();
  const mergeEntryFieldNames = /* @__PURE__ */ new Set();
  const schema = subschemaConfig.schema;
  for (const typeName in subschemaConfig.merge) {
    const mergedTypeConfig = subschemaConfig.merge[typeName];
    if (mergedTypeConfig.fieldName) {
      mergeEntryFieldNames.add(mergedTypeConfig.fieldName);
    }
    for (const entry of mergedTypeConfig.entryPoints ?? []) {
      if (entry.fieldName) {
        mergeEntryFieldNames.add(entry.fieldName);
      }
    }
    const keys = /* @__PURE__ */ new Map();
    mergeKeyFieldNodes(
      keys,
      collectKeyFieldNodes(schema, typeName, mergedTypeConfig.selectionSet)
    );
    for (const entry of mergedTypeConfig.entryPoints ?? []) {
      mergeKeyFieldNodes(
        keys,
        collectKeyFieldNodes(schema, typeName, entry.selectionSet)
      );
    }
    if (keys.size) {
      keyFieldsByType.set(typeName, [...keys.values()]);
    }
    if (!mergedTypeConfig.fields) {
      continue;
    }
    let computed;
    for (const fieldName in mergedTypeConfig.fields) {
      const fieldConfig = mergedTypeConfig.fields[fieldName];
      if (fieldConfig?.computed && fieldConfig.selectionSet) {
        computed ||= /* @__PURE__ */ new Set();
        computed.add(fieldName);
      }
    }
    if (computed?.size) {
      computedByType.set(typeName, computed);
    }
  }
  if (!computedByType.size) {
    return [subschemaConfig];
  }
  const transform = new DeferComputedFieldsTransform(
    schema,
    computedByType,
    keyFieldsByType,
    mergeEntryFieldNames
  );
  return [
    {
      ...subschemaConfig,
      transforms: [transform, ...subschemaConfig.transforms ?? []]
    }
  ];
}

function splitMergedTypeEntryPointsTransformer(subschemaConfig) {
  if (!subschemaConfig.merge) return [subschemaConfig];
  let changed = false;
  const merge = {
    ...subschemaConfig.merge
  };
  for (const typeName of Object.keys(merge)) {
    const mergedTypeConfig = merge[typeName];
    if (mergedTypeConfig == null) {
      continue;
    }
    const entryPoints = mergedTypeConfig.entryPoints;
    if (entryPoints == null || entryPoints.length === 0) {
      continue;
    }
    if (mergedTypeConfig.selectionSet != null || mergedTypeConfig.fieldName != null || mergedTypeConfig.resolve != null) {
      throw new Error(
        `Merged type ${typeName} may not define entryPoints in addition to selectionSet, fieldName, or resolve`
      );
    }
    if (entryPoints.length === 1) {
      const [entryPoint] = entryPoints;
      merge[typeName] = {
        ...mergedTypeConfig,
        ...entryPoint
      };
      delete merge[typeName].entryPoints;
      changed = true;
      continue;
    }
    changed = true;
  }
  if (!changed) {
    return [subschemaConfig];
  }
  return [
    {
      ...subschemaConfig,
      merge
    }
  ];
}

function extractDefinitions(ast) {
  const typeDefinitions = [];
  const directiveDefs = [];
  const schemaDefs = [];
  const schemaExtensions = [];
  const extensionDefs = [];
  for (const def of ast.definitions) {
    switch (def.kind) {
      case Kind.OBJECT_TYPE_DEFINITION:
      case Kind.INTERFACE_TYPE_DEFINITION:
      case Kind.INPUT_OBJECT_TYPE_DEFINITION:
      case Kind.UNION_TYPE_DEFINITION:
      case Kind.ENUM_TYPE_DEFINITION:
      case Kind.SCALAR_TYPE_DEFINITION:
        typeDefinitions.push(def);
        break;
      case Kind.DIRECTIVE_DEFINITION:
        directiveDefs.push(def);
        break;
      case Kind.SCHEMA_DEFINITION:
        schemaDefs.push(def);
        break;
      case Kind.SCHEMA_EXTENSION:
        schemaExtensions.push(def);
        break;
      case Kind.OBJECT_TYPE_EXTENSION:
      case Kind.INTERFACE_TYPE_EXTENSION:
      case Kind.INPUT_OBJECT_TYPE_EXTENSION:
      case Kind.UNION_TYPE_EXTENSION:
      case Kind.ENUM_TYPE_EXTENSION:
      case Kind.SCALAR_TYPE_EXTENSION:
        extensionDefs.push(def);
        break;
    }
  }
  return {
    typeDefinitions,
    directiveDefs,
    schemaDefs,
    schemaExtensions,
    extensionDefs
  };
}

var ValidationLevel = /* @__PURE__ */ ((ValidationLevel2) => {
  ValidationLevel2["Error"] = "error";
  ValidationLevel2["Warn"] = "warn";
  ValidationLevel2["Off"] = "off";
  return ValidationLevel2;
})(ValidationLevel || {});

function validateFieldConsistency(finalFieldConfig, candidates, typeMergingOptions) {
  const firstCandidate = candidates[0];
  if (!firstCandidate) {
    throw new Error("First candidate is null");
  }
  const fieldNamespace = `${firstCandidate.type.name}.${firstCandidate.fieldName}`;
  const finalFieldNull = isNonNullType(finalFieldConfig.type);
  validateTypeConsistency(
    finalFieldConfig,
    candidates.map((c) => c.fieldConfig),
    "field",
    fieldNamespace,
    typeMergingOptions
  );
  if (getValidationSettings(fieldNamespace, typeMergingOptions).strictNullComparison && candidates.some((c) => finalFieldNull !== isNonNullType(c.fieldConfig.type))) {
    validationMessage(
      `Nullability of field "${fieldNamespace}" does not match across subschemas. Disable typeMergingOptions.validationSettings.strictNullComparison to permit safe divergences.`,
      fieldNamespace,
      typeMergingOptions
    );
  } else if (finalFieldNull && candidates.some((c) => !isNonNullType(c.fieldConfig.type))) {
    validationMessage(
      `Canonical definition of field "${fieldNamespace}" is not-null while some subschemas permit null. This will be an automatic error in future versions.`,
      fieldNamespace,
      typeMergingOptions
    );
  }
  const argCandidatesMap = /* @__PURE__ */ Object.create(null);
  for (const { fieldConfig } of candidates) {
    if (fieldConfig.args == null) {
      continue;
    }
    for (const argName in fieldConfig.args) {
      const arg = fieldConfig.args[argName];
      if (arg) {
        argCandidatesMap[argName] ||= [];
        argCandidatesMap[argName].push(arg);
      }
    }
  }
  if (Object.values(argCandidatesMap).some(
    (argCandidates) => candidates.length !== argCandidates.length
  )) {
    validationMessage(
      `Canonical definition of field "${fieldNamespace}" implements inconsistent argument names across subschemas. Input may be filtered from some requests.`,
      fieldNamespace,
      typeMergingOptions
    );
  }
  for (const argName in argCandidatesMap) {
    if (finalFieldConfig.args == null) {
      continue;
    }
    const argCandidates = argCandidatesMap[argName];
    if (!argCandidates) {
      throw new Error("argCandidates is null");
    }
    const argNamespace = `${fieldNamespace}.${argName}`;
    const finalArgConfig = finalFieldConfig.args[argName] || argCandidates[argCandidates.length - 1];
    if (!finalArgConfig) {
      throw new Error("finalArgConfig is null");
    }
    const finalArgType = getNamedType(finalArgConfig.type);
    const finalArgNull = isNonNullType(finalArgConfig.type);
    validateTypeConsistency(
      finalArgConfig,
      argCandidates,
      "argument",
      argNamespace,
      typeMergingOptions
    );
    if (getValidationSettings(argNamespace, typeMergingOptions).strictNullComparison && argCandidates.some((c) => finalArgNull !== isNonNullType(c.type))) {
      validationMessage(
        `Nullability of argument "${argNamespace}" does not match across subschemas. Disable typeMergingOptions.validationSettings.strictNullComparison to permit safe divergences.`,
        argNamespace,
        typeMergingOptions
      );
    } else if (!finalArgNull && argCandidates.some((c) => isNonNullType(c.type))) {
      validationMessage(
        `Canonical definition of argument "${argNamespace}" permits null while some subschemas require not-null. This will be an automatic error in future versions.`,
        argNamespace,
        typeMergingOptions
      );
    }
    if (isEnumType(finalArgType)) {
      validateInputEnumConsistency(
        finalArgType,
        argCandidates,
        typeMergingOptions
      );
    }
  }
}
function validateInputObjectConsistency(fieldInclusionMap, candidates, typeMergingOptions) {
  for (const fieldName in fieldInclusionMap) {
    const count = fieldInclusionMap[fieldName];
    if (candidates.length !== count && candidates[0]) {
      const namespace = `${candidates[0].type.name}.${fieldName}`;
      validationMessage(
        `Definition of input field "${namespace}" is not implemented by all subschemas. Input may be filtered from some requests.`,
        namespace,
        typeMergingOptions
      );
    }
  }
}
function validateInputFieldConsistency(finalInputFieldConfig, candidates, typeMergingOptions) {
  const inputFieldNamespace = `${candidates[0]?.type.name}.${candidates[0]?.fieldName}`;
  const inputFieldConfigs = candidates.map((c) => c.inputFieldConfig);
  const finalInputFieldType = getNamedType(finalInputFieldConfig.type);
  const finalInputFieldNull = isNonNullType(finalInputFieldConfig.type);
  validateTypeConsistency(
    finalInputFieldConfig,
    inputFieldConfigs,
    "input field",
    inputFieldNamespace,
    typeMergingOptions
  );
  if (getValidationSettings(inputFieldNamespace, typeMergingOptions).strictNullComparison && candidates.some(
    (c) => finalInputFieldNull !== isNonNullType(c.inputFieldConfig.type)
  )) {
    validationMessage(
      `Nullability of input field "${inputFieldNamespace}" does not match across subschemas. Disable typeMergingOptions.validationSettings.strictNullComparison to permit safe divergences.`,
      inputFieldNamespace,
      typeMergingOptions
    );
  } else if (!finalInputFieldNull && candidates.some((c) => isNonNullType(c.inputFieldConfig.type))) {
    validationMessage(
      `Canonical definition of input field "${inputFieldNamespace}" permits null while some subschemas require not-null. This will be an automatic error in future versions.`,
      inputFieldNamespace,
      typeMergingOptions
    );
  }
  if (isEnumType(finalInputFieldType)) {
    validateInputEnumConsistency(
      finalInputFieldType,
      inputFieldConfigs,
      typeMergingOptions
    );
  }
}
function validateTypeConsistency(finalElementConfig, candidates, definitionType, settingNamespace, typeMergingOptions) {
  const finalNamedType = getNamedType(finalElementConfig.type);
  const finalIsScalar = isScalarType(finalNamedType);
  const finalIsList = hasListType(finalElementConfig.type);
  for (const c of candidates) {
    if (finalIsList !== hasListType(c.type)) {
      throw new Error(
        `Definitions of ${definitionType} "${settingNamespace}" implement inconsistent list types across subschemas and cannot be merged.`
      );
    }
    const currentNamedType = getNamedType(c.type);
    if (finalNamedType.toString() !== currentNamedType.toString()) {
      const proxiableScalar = !!typeMergingOptions?.validationSettings?.proxiableScalars?.[finalNamedType.toString()]?.includes(currentNamedType.toString());
      const bothScalars = finalIsScalar && isScalarType(currentNamedType);
      const permitScalar = proxiableScalar && bothScalars;
      if (proxiableScalar && !bothScalars) {
        throw new Error(
          `Types ${finalNamedType} and ${currentNamedType} are not proxiable scalars.`
        );
      }
      if (!permitScalar) {
        validationMessage(
          `Definitions of ${definitionType} "${settingNamespace}" implement inconsistent named types across subschemas. This will be an automatic error in future versions.`,
          settingNamespace,
          typeMergingOptions
        );
      }
    }
  }
}
function hasListType(type) {
  return isListType(getNullableType(type));
}
function validateInputEnumConsistency(inputEnumType, candidates, typeMergingOptions) {
  const enumValueInclusionMap = /* @__PURE__ */ Object.create(null);
  for (const candidate of candidates) {
    const enumType = getNamedType(candidate.type);
    if (isEnumType(enumType)) {
      for (const { value } of enumType.getValues()) {
        enumValueInclusionMap[value] = enumValueInclusionMap[value] || 0;
        enumValueInclusionMap[value] += 1;
      }
    }
  }
  if (Object.values(enumValueInclusionMap).some(
    (count) => candidates.length !== count
  )) {
    validationMessage(
      `Enum "${inputEnumType.name}" is used as an input with inconsistent values across subschemas. This will be an automatic error in future versions.`,
      inputEnumType.name,
      typeMergingOptions
    );
  }
}
function validationMessage(message, settingNamespace, typeMergingOptions) {
  const override = `typeMergingOptions.validationScopes['${settingNamespace}'].validationLevel`;
  const settings = getValidationSettings(settingNamespace, typeMergingOptions);
  switch (settings.validationLevel ?? ValidationLevel.Warn) {
    case ValidationLevel.Off:
      return;
    case ValidationLevel.Error:
      throw new Error(
        `${message} If this is intentional, you may disable this error by setting ${override} = "warn|off"`
      );
    default:
      console.warn(
        `${message} To disable this warning or elevate it to an error, set ${override} = "error|off"`
      );
  }
}
function getValidationSettings(settingNamespace, typeMergingOptions) {
  return {
    ...typeMergingOptions?.validationSettings ?? {},
    ...typeMergingOptions?.validationScopes?.[settingNamespace] ?? {}
  };
}

function mergeCandidates(typeName, candidates, typeMergingOptions) {
  const initialCandidateType = candidates[0]?.type;
  if (candidates.length === 1 && initialCandidateType?.name === typeName) {
    return initialCandidateType;
  }
  if (candidates.some(
    (candidate) => candidate.type.constructor !== initialCandidateType?.constructor
  )) {
    throw new Error(
      `Cannot merge different type categories into common type ${typeName}.`
    );
  }
  if (isObjectType(initialCandidateType)) {
    return mergeObjectTypeCandidates(typeName, candidates, typeMergingOptions);
  } else if (isInputObjectType(initialCandidateType)) {
    return mergeInputObjectTypeCandidates(
      typeName,
      candidates,
      typeMergingOptions
    );
  } else if (isInterfaceType(initialCandidateType)) {
    return mergeInterfaceTypeCandidates(
      typeName,
      candidates,
      typeMergingOptions
    );
  } else if (isUnionType(initialCandidateType)) {
    return mergeUnionTypeCandidates(typeName, candidates, typeMergingOptions);
  } else if (isEnumType(initialCandidateType)) {
    return mergeEnumTypeCandidates(typeName, candidates, typeMergingOptions);
  } else if (isScalarType(initialCandidateType)) {
    return mergeScalarTypeCandidates(typeName, candidates, typeMergingOptions);
  } else {
    throw new Error(`Type ${typeName} has unknown GraphQL type.`);
  }
}
function mergeObjectTypeCandidates(typeName, candidates, typeMergingOptions) {
  candidates = orderedTypeCandidates(candidates, typeMergingOptions);
  const description = mergeTypeDescriptions(candidates, typeMergingOptions);
  const fields = fieldConfigMapFromTypeCandidates(
    candidates,
    typeMergingOptions
  );
  const typeConfigs = candidates.map(
    (candidate) => candidate.type.toConfig()
  );
  const interfaceMap = typeConfigs.map((typeConfig2) => typeConfig2.interfaces).reduce((acc, interfaces2) => {
    if (interfaces2 != null) {
      for (const iface of interfaces2) {
        acc[iface.name] = iface;
      }
    }
    return acc;
  }, /* @__PURE__ */ Object.create(null));
  const interfaces = Object.values(interfaceMap);
  const astNodes = pluck("astNode", candidates);
  const fieldAstNodes = canonicalFieldNamesForType(candidates).map((fieldName) => fields[fieldName]?.astNode).filter((n) => n != null);
  if (astNodes.length > 1 && fieldAstNodes.length) {
    astNodes.push({
      ...astNodes[astNodes.length - 1],
      fields: JSON.parse(JSON.stringify(fieldAstNodes))
    });
  }
  const astNode = astNodes.slice(1).reduce(
    (acc, astNode2) => mergeType(astNode2, acc, {
      ignoreFieldConflicts: true
    }),
    astNodes[0]
  );
  const extensionASTNodes = pluck(
    "extensionASTNodes",
    candidates
  );
  const extensions = Object.assign(
    {},
    ...pluck("extensions", candidates)
  );
  const typeConfig = {
    name: typeName,
    description,
    fields,
    interfaces,
    astNode,
    extensionASTNodes,
    extensions,
    // @ts-expect-error We know isOneOf exists here
    isOneOf: candidates.every((candidate) => candidate.type.isOneOf)
  };
  return new GraphQLObjectType(typeConfig);
}
function mergeInputObjectTypeCandidates(typeName, candidates, typeMergingOptions) {
  candidates = orderedTypeCandidates(candidates, typeMergingOptions);
  const description = mergeTypeDescriptions(candidates, typeMergingOptions);
  const fields = inputFieldConfigMapFromTypeCandidates(
    candidates,
    typeMergingOptions
  );
  const astNodes = pluck("astNode", candidates);
  const fieldAstNodes = canonicalFieldNamesForType(candidates).map((fieldName) => fields[fieldName]?.astNode).filter((n) => n != null);
  if (astNodes.length > 1 && fieldAstNodes.length) {
    astNodes.push({
      ...astNodes[astNodes.length - 1],
      fields: JSON.parse(JSON.stringify(fieldAstNodes))
    });
  }
  const astNode = astNodes.slice(1).reduce(
    (acc, astNode2) => mergeInputType(astNode2, acc, {
      ignoreFieldConflicts: true
    }),
    astNodes[0]
  );
  const extensionASTNodes = pluck(
    "extensionASTNodes",
    candidates
  );
  const extensions = Object.assign(
    {},
    ...pluck("extensions", candidates)
  );
  const typeConfig = {
    name: typeName,
    description,
    fields,
    astNode,
    extensionASTNodes,
    extensions,
    // @ts-expect-error We know isOneOf exists here
    isOneOf: candidates.every((candidate) => candidate.type.isOneOf)
  };
  return new GraphQLInputObjectType(typeConfig);
}
function pluck(typeProperty, candidates) {
  return candidates.map((candidate) => candidate.type[typeProperty]).filter((value) => value != null);
}
function mergeInterfaceTypeCandidates(typeName, candidates, typeMergingOptions) {
  candidates = orderedTypeCandidates(candidates, typeMergingOptions);
  const description = mergeTypeDescriptions(candidates, typeMergingOptions);
  const fields = fieldConfigMapFromTypeCandidates(
    candidates,
    typeMergingOptions
  );
  const typeConfigs = candidates.map((candidate) => candidate.type.toConfig());
  const interfaceMap = typeConfigs.map(
    (typeConfig2) => "interfaces" in typeConfig2 ? typeConfig2.interfaces : []
  ).reduce((acc, interfaces2) => {
    if (interfaces2 != null) {
      for (const iface of interfaces2) {
        acc[iface.name] = iface;
      }
    }
    return acc;
  }, /* @__PURE__ */ Object.create(null));
  const interfaces = Object.values(interfaceMap);
  const astNodes = pluck("astNode", candidates);
  const fieldAstNodes = canonicalFieldNamesForType(candidates).map((fieldName) => fields[fieldName]?.astNode).filter((n) => n != null);
  if (astNodes.length > 1 && fieldAstNodes.length) {
    astNodes.push({
      ...astNodes[astNodes.length - 1],
      fields: JSON.parse(JSON.stringify(fieldAstNodes))
    });
  }
  const astNode = astNodes.slice(1).reduce(
    (acc, astNode2) => mergeInterface(astNode2, acc, {
      ignoreFieldConflicts: true
    }),
    astNodes[0]
  );
  const extensionASTNodes = pluck(
    "extensionASTNodes",
    candidates
  );
  const extensions = Object.assign(
    {},
    ...pluck("extensions", candidates)
  );
  const typeConfig = {
    name: typeName,
    description,
    fields,
    interfaces,
    astNode,
    extensionASTNodes,
    extensions
  };
  return new GraphQLInterfaceType(typeConfig);
}
function mergeUnionTypeCandidates(typeName, candidates, typeMergingOptions) {
  candidates = orderedTypeCandidates(candidates, typeMergingOptions);
  const description = mergeTypeDescriptions(candidates, typeMergingOptions);
  const typeConfigs = candidates.map((candidate) => {
    if (!isUnionType(candidate.type)) {
      throw new Error(`Expected ${candidate.type} to be a union type!`);
    }
    return candidate.type.toConfig();
  });
  const typeMap = typeConfigs.reduce(
    (acc, typeConfig2) => {
      for (const type of typeConfig2.types) {
        acc[type.name] = type;
      }
      return acc;
    },
    /* @__PURE__ */ Object.create(null)
  );
  const types = Object.values(typeMap);
  const astNodes = pluck("astNode", candidates);
  const astNode = astNodes.slice(1).reduce(
    (acc, astNode2) => mergeUnion(
      astNode2,
      acc
    ),
    astNodes[0]
  );
  const extensionASTNodes = pluck(
    "extensionASTNodes",
    candidates
  );
  const extensions = Object.assign(
    {},
    ...pluck("extensions", candidates)
  );
  const typeConfig = {
    name: typeName,
    description,
    types,
    astNode,
    extensionASTNodes,
    extensions
  };
  return new GraphQLUnionType(typeConfig);
}
function mergeEnumTypeCandidates(typeName, candidates, typeMergingOptions) {
  candidates = orderedTypeCandidates(candidates, typeMergingOptions);
  const description = mergeTypeDescriptions(candidates, typeMergingOptions);
  const values = enumValueConfigMapFromTypeCandidates(
    candidates,
    typeMergingOptions
  );
  const astNodes = pluck("astNode", candidates);
  const astNode = astNodes.slice(1).reduce(
    (acc, astNode2) => mergeEnum(astNode2, acc, {
      consistentEnumMerge: true
    }),
    astNodes[0]
  );
  const extensionASTNodes = pluck(
    "extensionASTNodes",
    candidates
  );
  const extensions = Object.assign(
    {},
    ...pluck("extensions", candidates)
  );
  const typeConfig = {
    name: typeName,
    description,
    values,
    astNode,
    extensionASTNodes,
    extensions
  };
  return new GraphQLEnumType(typeConfig);
}
function enumValueConfigMapFromTypeCandidates(candidates, typeMergingOptions) {
  const enumValueConfigCandidatesMap = /* @__PURE__ */ Object.create(null);
  for (const candidate of candidates) {
    const valueMap = candidate.type.toConfig().values;
    for (const enumValue in valueMap) {
      const enumValueConfig = valueMap[enumValue];
      if (enumValueConfig) {
        const enumValueConfigCandidate = {
          enumValueConfig,
          enumValue,
          type: candidate.type,
          subschema: candidate.subschema,
          transformedSubschema: candidate.transformedSubschema
        };
        if (enumValueConfigCandidatesMap[enumValue]) {
          enumValueConfigCandidatesMap[enumValue].push(
            enumValueConfigCandidate
          );
        } else {
          enumValueConfigCandidatesMap[enumValue] = [enumValueConfigCandidate];
        }
      }
    }
  }
  const enumValueConfigMap = /* @__PURE__ */ Object.create(null);
  for (const enumValue in enumValueConfigCandidatesMap) {
    const enumValueConfigCandidates = enumValueConfigCandidatesMap[enumValue];
    if (enumValueConfigCandidates) {
      const enumValueConfigMerger = typeMergingOptions?.enumValueConfigMerger ?? defaultEnumValueConfigMerger;
      enumValueConfigMap[enumValue] = enumValueConfigMerger(
        enumValueConfigCandidates
      );
    }
  }
  return enumValueConfigMap;
}
function defaultEnumValueConfigMerger(candidates) {
  const preferred = candidates.find(
    ({ type, transformedSubschema }) => isSubschemaConfig(transformedSubschema) && transformedSubschema.merge?.[type.name]?.canonical
  );
  const lastCanonical = candidates[candidates.length - 1];
  if (!lastCanonical) {
    throw new Error("Last canonical is required");
  }
  return (preferred || lastCanonical).enumValueConfig;
}
function mergeScalarTypeCandidates(typeName, candidates, typeMergingOptions) {
  candidates = orderedTypeCandidates(candidates, typeMergingOptions);
  const description = mergeTypeDescriptions(candidates, typeMergingOptions);
  const serializeFns = pluck(
    "serialize",
    candidates
  );
  const serialize = serializeFns[serializeFns.length - 1];
  const parseValueFns = pluck(
    "parseValue",
    candidates
  );
  const parseValue = parseValueFns[parseValueFns.length - 1];
  const parseLiteralFns = pluck(
    "parseLiteral",
    candidates
  );
  const parseLiteral = parseLiteralFns[parseLiteralFns.length - 1];
  const astNodes = pluck("astNode", candidates);
  const astNode = astNodes.slice(1).reduce(
    (acc, astNode2) => mergeScalar(
      astNode2,
      acc
    ),
    astNodes[0]
  );
  const extensionASTNodes = pluck(
    "extensionASTNodes",
    candidates
  );
  const extensions = Object.assign(
    {},
    ...pluck("extensions", candidates)
  );
  let specifiedByURL;
  for (const candidate of candidates) {
    if ("specifiedByURL" in candidate.type && candidate.type.specifiedByURL) {
      specifiedByURL = candidate.type.specifiedByURL;
      break;
    }
  }
  const typeConfig = {
    name: typeName,
    description,
    serialize,
    parseValue,
    parseLiteral,
    astNode,
    extensionASTNodes,
    extensions,
    specifiedByURL
  };
  return new GraphQLScalarType(typeConfig);
}
function orderedTypeCandidates(candidates, typeMergingOptions) {
  const typeCandidateMerger = typeMergingOptions?.typeCandidateMerger ?? defaultTypeCandidateMerger;
  const candidate = typeCandidateMerger(candidates);
  return candidates.filter((c) => c !== candidate).concat([candidate]);
}
function defaultTypeCandidateMerger(candidates) {
  const canonical = candidates.filter(
    ({ type, transformedSubschema }) => isSubschemaConfig(transformedSubschema) ? transformedSubschema.merge?.[type.name]?.canonical : false
  );
  if (canonical.length > 1) {
    if (!canonical[0]) {
      throw new Error(`First canonical is required`);
    }
    throw new Error(
      `Multiple canonical definitions for "${canonical[0].type.name}"`
    );
  } else if (canonical.length) {
    if (!canonical[0]) {
      throw new Error(`First canonical is required`);
    }
    return canonical[0];
  }
  const lastCanonical = candidates[candidates.length - 1];
  if (!lastCanonical) {
    throw new Error(`Last canonical is required`);
  }
  return lastCanonical;
}
function mergeTypeDescriptions(candidates, typeMergingOptions) {
  const typeDescriptionsMerger = typeMergingOptions?.typeDescriptionsMerger ?? defaultTypeDescriptionMerger;
  return typeDescriptionsMerger(candidates);
}
function defaultTypeDescriptionMerger(candidates) {
  const lastCandidate = candidates[candidates.length - 1];
  return lastCandidate?.type.description;
}
function fieldConfigMapFromTypeCandidates(candidates, typeMergingOptions) {
  const fieldConfigCandidatesMap = /* @__PURE__ */ Object.create(null);
  for (const candidate of candidates) {
    const typeConfig = candidate.type.toConfig();
    const fieldConfigMap2 = typeConfig.fields;
    for (const fieldName in fieldConfigMap2) {
      const fieldConfig = fieldConfigMap2[fieldName];
      if (fieldConfig) {
        const fieldConfigCandidate = {
          fieldConfig,
          fieldName,
          type: candidate.type,
          subschema: candidate.subschema,
          transformedSubschema: candidate.transformedSubschema
        };
        if (fieldConfigCandidatesMap[fieldName]) {
          fieldConfigCandidatesMap[fieldName].push(fieldConfigCandidate);
        } else {
          fieldConfigCandidatesMap[fieldName] = [fieldConfigCandidate];
        }
      }
    }
  }
  const fieldConfigMap = /* @__PURE__ */ Object.create(null);
  for (const fieldName in fieldConfigCandidatesMap) {
    const fieldConfigCandidates = fieldConfigCandidatesMap[fieldName];
    if (fieldConfigCandidates) {
      fieldConfigMap[fieldName] = mergeFieldConfigs(
        fieldConfigCandidates,
        typeMergingOptions
      );
    }
  }
  return fieldConfigMap;
}
function mergeFieldConfigs(candidates, typeMergingOptions) {
  const fieldConfigMerger = typeMergingOptions?.fieldConfigMerger ?? getDefaultFieldConfigMerger(
    typeMergingOptions?.useNonNullableFieldOnConflict
  );
  const finalFieldConfig = fieldConfigMerger(candidates);
  validateFieldConsistency(finalFieldConfig, candidates, typeMergingOptions);
  return finalFieldConfig;
}
function getDefaultFieldConfigMerger(useNonNullableFieldOnConflict = false) {
  return function defaultFieldConfigMerger(candidates) {
    const nullables = [];
    const nonNullables = [];
    const canonicalByField = [];
    const canonicalByType = [];
    for (const {
      type,
      fieldName,
      fieldConfig,
      transformedSubschema
    } of candidates) {
      if (!isSubschemaConfig(transformedSubschema)) continue;
      if (transformedSubschema.merge?.[type.name]?.fields?.[fieldName]?.canonical) {
        canonicalByField.push(fieldConfig);
      } else if (transformedSubschema.merge?.[type.name]?.canonical) {
        canonicalByType.push(fieldConfig);
      }
      if (isNullableType(fieldConfig.type)) {
        nullables.push(fieldConfig);
      } else {
        nonNullables.push(fieldConfig);
      }
    }
    const nonNullableFinalField = nonNullables.length > 0 && nullables.length > 0 && useNonNullableFieldOnConflict;
    if (canonicalByField.length > 1 && candidates[0]) {
      throw new Error(
        `Multiple canonical definitions for "${candidates[0].type.name}.${candidates[0].fieldName}"`
      );
    } else if (canonicalByField.length) {
      const finalField2 = canonicalByField[0];
      if (!finalField2) {
        throw new Error("Final field is required");
      }
      if (nonNullableFinalField) {
        return {
          ...finalField2,
          type: getNullableType(finalField2.type)
        };
      }
      return finalField2;
    } else if (canonicalByType.length) {
      const finalField2 = canonicalByType[0];
      if (!finalField2) {
        throw new Error("Final field is required");
      }
      if (nonNullableFinalField) {
        return {
          ...finalField2,
          type: getNullableType(finalField2.type)
        };
      }
      return finalField2;
    }
    const finalField = candidates[candidates.length - 1]?.fieldConfig;
    if (!finalField) {
      throw new Error("Field config is required");
    }
    if (nonNullableFinalField) {
      return {
        ...finalField,
        type: getNullableType(finalField.type)
      };
    }
    return finalField;
  };
}
function inputFieldConfigMapFromTypeCandidates(candidates, typeMergingOptions) {
  const inputFieldConfigCandidatesMap = /* @__PURE__ */ Object.create(null);
  const fieldInclusionMap = /* @__PURE__ */ Object.create(null);
  for (const candidate of candidates) {
    const typeConfig = candidate.type.toConfig();
    const inputFieldConfigMap2 = typeConfig.fields;
    for (const fieldName in inputFieldConfigMap2) {
      const inputFieldConfig = inputFieldConfigMap2[fieldName];
      if (inputFieldConfig == null) {
        throw new Error(`'inputFieldConfig' is required`);
      }
      fieldInclusionMap[fieldName] = fieldInclusionMap[fieldName] || 0;
      fieldInclusionMap[fieldName] += 1;
      const inputFieldConfigCandidate = {
        inputFieldConfig,
        fieldName,
        type: candidate.type,
        subschema: candidate.subschema,
        transformedSubschema: candidate.transformedSubschema
      };
      if (inputFieldConfigCandidatesMap[fieldName]) {
        inputFieldConfigCandidatesMap[fieldName].push(
          inputFieldConfigCandidate
        );
      } else {
        inputFieldConfigCandidatesMap[fieldName] = [inputFieldConfigCandidate];
      }
    }
  }
  validateInputObjectConsistency(
    fieldInclusionMap,
    candidates,
    typeMergingOptions
  );
  const inputFieldConfigMap = /* @__PURE__ */ Object.create(null);
  for (const fieldName in inputFieldConfigCandidatesMap) {
    const inputFieldConfigMerger = typeMergingOptions?.inputFieldConfigMerger ?? defaultInputFieldConfigMerger;
    const inputFieldConfigCandidate = inputFieldConfigCandidatesMap[fieldName];
    if (!inputFieldConfigCandidate) {
      throw new Error("Input field config candidate is required");
    }
    inputFieldConfigMap[fieldName] = inputFieldConfigMerger(
      inputFieldConfigCandidate
    );
    validateInputFieldConsistency(
      inputFieldConfigMap[fieldName],
      inputFieldConfigCandidate,
      typeMergingOptions
    );
  }
  return inputFieldConfigMap;
}
function defaultInputFieldConfigMerger(candidates) {
  const canonicalByField = [];
  const canonicalByType = [];
  for (const {
    type,
    fieldName,
    inputFieldConfig,
    transformedSubschema
  } of candidates) {
    if (!isSubschemaConfig(transformedSubschema)) continue;
    if (transformedSubschema.merge?.[type.name]?.fields?.[fieldName]?.canonical) {
      canonicalByField.push(inputFieldConfig);
    } else if (transformedSubschema.merge?.[type.name]?.canonical) {
      canonicalByType.push(inputFieldConfig);
    }
  }
  if (canonicalByField.length > 1 && candidates[0]) {
    throw new Error(
      `Multiple canonical definitions for "${candidates[0].type.name}.${candidates[0].fieldName}"`
    );
  } else if (canonicalByField.length) {
    return canonicalByField[0];
  } else if (canonicalByType.length) {
    return canonicalByType[0];
  }
  const lastCandidate = candidates[candidates.length - 1];
  if (!lastCandidate) {
    throw new Error("Last candidate is required");
  }
  return lastCandidate.inputFieldConfig;
}
function canonicalFieldNamesForType(candidates) {
  const canonicalFieldNames = /* @__PURE__ */ Object.create(null);
  for (const { type, transformedSubschema } of candidates) {
    if (!isSubschemaConfig(transformedSubschema)) continue;
    const mergeConfig = transformedSubschema.merge?.[type.name];
    if (mergeConfig != null && mergeConfig.fields != null && !mergeConfig.canonical) {
      for (const fieldName in mergeConfig.fields) {
        const mergedFieldConfig = mergeConfig.fields[fieldName];
        if (mergedFieldConfig?.canonical) {
          canonicalFieldNames[fieldName] = true;
        }
      }
    }
  }
  return Object.keys(canonicalFieldNames);
}

function mergeDirectives(directives) {
  if (directives.size === 0) {
    return void 0;
  }
  if (directives.size === 1) {
    const directive = directives.values().next().value;
    return directive;
  }
  let name;
  let description;
  const locations = /* @__PURE__ */ new Set();
  const args = {};
  const extensionsSet = /* @__PURE__ */ new Set();
  let isRepeatable = false;
  for (const directive of directives) {
    name = directive.name;
    if (directive.description) {
      description = directive.description;
    }
    for (const location of directive.locations) {
      locations.add(location);
    }
    for (const arg of directive.args) {
      args[arg.name] = arg;
    }
    isRepeatable = isRepeatable || directive.isRepeatable;
    if (directive.extensions) {
      extensionsSet.add(directive.extensions);
    }
  }
  return new GraphQLDirective({
    name,
    description,
    locations: Array.from(locations),
    args,
    isRepeatable,
    extensions: extensionsSet.size > 0 ? mergeDeep([...extensionsSet]) : void 0
  });
}

function typeFromAST(node) {
  switch (node.kind) {
    case Kind.OBJECT_TYPE_DEFINITION:
      return makeObjectType(node);
    case Kind.INTERFACE_TYPE_DEFINITION:
      return makeInterfaceType(node);
    case Kind.ENUM_TYPE_DEFINITION:
      return makeEnumType(node);
    case Kind.UNION_TYPE_DEFINITION:
      return makeUnionType(node);
    case Kind.SCALAR_TYPE_DEFINITION:
      return makeScalarType(node);
    case Kind.INPUT_OBJECT_TYPE_DEFINITION:
      return makeInputObjectType(node);
    case Kind.DIRECTIVE_DEFINITION:
      return makeDirective(node);
    default:
      return null;
  }
}
function makeObjectType(node) {
  const config = {
    name: node.name.value,
    description: node.description?.value,
    interfaces: () => node.interfaces?.map(
      (iface) => createNamedStub(iface.name.value, "interface")
    ) || [],
    fields: () => node.fields != null ? makeFields(node.fields) : {},
    astNode: node
  };
  return new GraphQLObjectType(config);
}
function makeInterfaceType(node) {
  const config = {
    name: node.name.value,
    description: node.description?.value,
    // graphql expects the thunk to always return a list
    interfaces: () => node.interfaces?.map(
      (iface) => createNamedStub(iface.name.value, "interface")
    ) || [],
    fields: () => node.fields != null ? makeFields(node.fields) : {},
    astNode: node
  };
  return new GraphQLInterfaceType(config);
}
function makeEnumType(node) {
  const values = node.values?.reduce(
    (prev, value) => ({
      ...prev,
      [value.name.value]: {
        description: value.description?.value,
        deprecationReason: getDeprecationReason(value),
        astNode: value
      }
    }),
    {}
  ) ?? {};
  return new GraphQLEnumType({
    name: node.name.value,
    description: node.description?.value,
    values,
    astNode: node
  });
}
function makeUnionType(node) {
  return new GraphQLUnionType({
    name: node.name.value,
    description: node.description?.value,
    types: () => node.types?.map((type) => createNamedStub(type.name.value, "object")) ?? [],
    astNode: node
  });
}
function makeScalarType(node) {
  return new GraphQLScalarType({
    name: node.name.value,
    description: node.description?.value,
    astNode: node
  });
}
function makeInputObjectType(node) {
  return new GraphQLInputObjectType({
    name: node.name.value,
    description: node.description?.value,
    fields: () => node.fields ? makeValues(node.fields) : {},
    astNode: node
  });
}
function makeFields(nodes) {
  return nodes.reduce(
    (prev, node) => ({
      ...prev,
      [node.name.value]: {
        type: createStub(node.type, "output"),
        description: node.description?.value,
        args: makeValues(node.arguments ?? []),
        deprecationReason: getDeprecationReason(node),
        astNode: node
      }
    }),
    {}
  );
}
function makeValues(nodes) {
  return nodes.reduce(
    (prev, node) => ({
      ...prev,
      [node.name.value]: {
        type: createStub(node.type, "input"),
        defaultValue: node.defaultValue !== void 0 ? valueFromASTUntyped(node.defaultValue) : void 0,
        description: node.description?.value,
        astNode: node
      }
    }),
    {}
  );
}
function isLocationValue(value) {
  return value in DirectiveLocation;
}
function makeDirective(node) {
  const locations = [];
  for (const location of node.locations) {
    const locationValue = location.value;
    if (isLocationValue(locationValue)) {
      locations.push(locationValue);
    }
  }
  return new GraphQLDirective({
    name: node.name.value,
    description: node.description != null ? node.description.value : null,
    locations,
    isRepeatable: node.repeatable,
    args: makeValues(node.arguments ?? []),
    astNode: node
  });
}
function getDeprecationReason(node) {
  const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);
  return deprecated?.["reason"];
}

function buildTypeCandidates({
  subschemas,
  originalSubschemaMap,
  types,
  typeDefs,
  parseOptions,
  directiveMap,
  schemaDefs,
  mergeDirectives: isMergeDirectives = true
}) {
  const directiveCandidates = new Map(
    Object.entries(directiveMap).map(([name, directive]) => [
      name,
      /* @__PURE__ */ new Set([directive])
    ])
  );
  const extensions = [];
  const typeCandidates = /* @__PURE__ */ Object.create(null);
  let schemaDef;
  let schemaExtensions = [];
  let document;
  let extraction;
  if (typeDefs && !Array.isArray(typeDefs) || Array.isArray(typeDefs) && typeDefs.length) {
    document = mergeTypeDefs(typeDefs, parseOptions);
    extraction = extractDefinitions(document);
    schemaDef = extraction.schemaDefs[0];
    schemaExtensions = schemaExtensions.concat(extraction.schemaExtensions);
  }
  schemaDefs.schemaDef = schemaDef ?? schemaDefs.schemaDef;
  schemaDefs.schemaExtensions = schemaExtensions;
  const rootTypeNameMap = getRootTypeNameMap(schemaDefs);
  for (const subschema of subschemas) {
    const schema = subschema.transformedSchema = wrapSchema(subschema);
    const rootTypeMap = getRootTypeMap(schema);
    const rootTypes = getRootTypes(schema);
    for (const [operation, rootType] of rootTypeMap.entries()) {
      addTypeCandidate(typeCandidates, rootTypeNameMap[operation], {
        type: rootType,
        subschema: originalSubschemaMap.get(subschema),
        transformedSubschema: subschema
      });
    }
    if (isMergeDirectives) {
      for (const directive of schema.getDirectives()) {
        let directiveCandidatesForName = directiveCandidates.get(
          directive.name
        );
        if (directiveCandidatesForName == null) {
          directiveCandidatesForName = /* @__PURE__ */ new Set();
          directiveCandidates.set(directive.name, directiveCandidatesForName);
        }
        directiveCandidatesForName.add(directive);
      }
    }
    const originalTypeMap = schema.getTypeMap();
    for (const typeName in originalTypeMap) {
      const type = originalTypeMap[typeName];
      if (isNamedType(type) && !isIntrospectionType(type) && !rootTypes.has(type)) {
        addTypeCandidate(typeCandidates, type.name, {
          type,
          subschema: originalSubschemaMap.get(subschema),
          transformedSubschema: subschema
        });
      }
    }
  }
  if (document != null && extraction != null) {
    for (const def of extraction.typeDefinitions) {
      const type = typeFromAST(def);
      if (!isNamedType(type)) {
        throw new Error(`Expected to get named typed but got ${inspect(def)}`);
      }
      if (type != null) {
        addTypeCandidate(typeCandidates, type.name, { type });
      }
    }
    for (const def of extraction.directiveDefs) {
      const directive = typeFromAST(def);
      if (!isDirective(directive)) {
        throw new Error(
          `Expected to get directive type but got ${inspect(def)}`
        );
      }
      let directiveCandidatesForName = directiveCandidates.get(directive.name);
      if (directiveCandidatesForName == null) {
        directiveCandidatesForName = /* @__PURE__ */ new Set();
        directiveCandidates.set(directive.name, directiveCandidatesForName);
      }
      directiveCandidatesForName.add(directive);
    }
    if (extraction.extensionDefs.length > 0) {
      extensions.push({
        ...document,
        definitions: extraction.extensionDefs
      });
    }
  }
  for (const type of types) {
    addTypeCandidate(typeCandidates, type.name, { type });
  }
  for (const [
    directiveName,
    directiveCandidatesForName
  ] of directiveCandidates) {
    directiveMap[directiveName] = mergeDirectives(directiveCandidatesForName);
  }
  return [typeCandidates, rootTypeNameMap, extensions];
}
function getRootTypeNameMap({
  schemaDef,
  schemaExtensions
}) {
  const rootTypeNameMap = {
    query: "Query",
    mutation: "Mutation",
    subscription: "Subscription"
  };
  const allNodes = schemaExtensions.slice();
  if (schemaDef != null) {
    allNodes.unshift(schemaDef);
  }
  for (const node of allNodes) {
    if (node.operationTypes != null) {
      for (const operationType of node.operationTypes) {
        rootTypeNameMap[operationType.operation] = operationType.type.name.value;
      }
    }
  }
  return rootTypeNameMap;
}
function addTypeCandidate(typeCandidates, name, typeCandidate) {
  if (!typeCandidates[name]) {
    typeCandidates[name] = [];
  }
  typeCandidates[name].push(typeCandidate);
}
function buildTypes({
  typeCandidates,
  directives,
  stitchingInfo,
  rootTypeNames,
  onTypeConflict,
  mergeTypes,
  typeMergingOptions
}) {
  const typeMap = /* @__PURE__ */ Object.create(null);
  for (const typeName in typeCandidates) {
    if (rootTypeNames.includes(typeName) || mergeTypes === true && !typeCandidates[typeName]?.some(
      (candidate) => isSpecifiedScalarType(candidate.type)
    ) || typeof mergeTypes === "function" && mergeTypes(typeCandidates[typeName], typeName) || Array.isArray(mergeTypes) && mergeTypes.includes(typeName) || stitchingInfo != null && typeName in stitchingInfo.mergedTypes) {
      typeMap[typeName] = mergeCandidates(
        typeName,
        typeCandidates[typeName],
        typeMergingOptions
      );
    } else {
      const candidateSelector = onTypeConflict != null ? onTypeConflictToCandidateSelector(onTypeConflict) : (cands) => cands[cands.length - 1];
      typeMap[typeName] = candidateSelector(typeCandidates[typeName]).type;
    }
  }
  return rewireTypes(typeMap, directives);
}
function onTypeConflictToCandidateSelector(onTypeConflict) {
  return (cands) => cands.reduce((prev, next) => {
    const type = onTypeConflict(prev.type, next.type, {
      left: {
        subschema: prev.subschema,
        transformedSubschema: prev.transformedSubschema
      },
      right: {
        subschema: next.subschema,
        transformedSubschema: next.transformedSubschema
      }
    });
    if (prev.type === type) {
      return prev;
    } else if (next.type === type) {
      return next;
    }
    return {
      schemaName: "unknown",
      type
    };
  });
}

function stitchSchemas(options) {
  const {
    resolvers = {},
    inheritResolversFromInterfaces = false,
    resolverValidationOptions = {},
    updateResolversInPlace = true,
    schemaExtensions,
    ...rest
  } = options;
  let {
    typeCandidates,
    newTypeMap,
    newDirectives,
    rootTypeNameMap,
    stitchingInfo,
    schemaDefs,
    extensions,
    mergeDirectives
  } = prepareStitchingData(options);
  let schema;
  {
    const finalTypes = Object.values(newTypeMap);
    if (!mergeDirectives) {
      stripCustomDirectiveUsages(finalTypes);
    }
    schema = new GraphQLSchema({
      query: newTypeMap[rootTypeNameMap.query],
      mutation: newTypeMap[rootTypeNameMap.mutation],
      subscription: newTypeMap[rootTypeNameMap.subscription],
      types: finalTypes,
      directives: newDirectives,
      astNode: schemaDefs.schemaDef,
      extensionASTNodes: schemaDefs.schemaExtensions,
      extensions: null,
      assumeValid: rest.assumeValid
    });
  }
  if (extensions.length > 0) {
    const mergedExtensions = concatAST(extensions);
    schema = extendSchema(schema, mergedExtensions);
  }
  const resolverMap = cloneResolverMap(
    mergeResolvers(resolvers),
    schema
  );
  const finalResolvers = inheritResolversFromInterfaces ? extendResolversFromInterfaces(schema, resolverMap) : resolverMap;
  stitchingInfo = completeStitchingInfo(stitchingInfo, finalResolvers, schema);
  addLocalFieldResolvers(schema, finalResolvers, stitchingInfo, typeCandidates);
  schema = addResolversToSchema({
    schema,
    defaultFieldResolver: defaultMergedResolver,
    resolvers: finalResolvers,
    resolverValidationOptions,
    inheritResolversFromInterfaces: false,
    updateResolversInPlace
  });
  const resolverValidationOptionsEntries = Object.entries(
    resolverValidationOptions
  );
  if (resolverValidationOptionsEntries.length > 0 && resolverValidationOptionsEntries.some(([, o]) => o !== "ignore")) {
    assertResolversPresent(schema, resolverValidationOptions);
  }
  addStitchingInfo(schema, stitchingInfo);
  if (schemaExtensions) {
    const mergedSchemaExtensions = Array.isArray(schemaExtensions) ? mergeExtensions(schemaExtensions) : schemaExtensions;
    applyExtensions(schema, mergedSchemaExtensions);
  }
  return schema;
}
function stripCustomDirectiveUsages(types) {
  const isBuiltin = (d) => isSpecifiedDirective(
    // @ts-expect-error it's ok to use just the name, isSpecifiedDirective does the same internally
    { name: d.name.value }
  );
  for (const type of types) {
    if (type.astNode?.directives?.length) {
      type.astNode = {
        ...type.astNode,
        directives: type.astNode.directives.filter(isBuiltin)
      };
    }
    if (isObjectType(type) || isInterfaceType(type)) {
      for (const field of Object.values(type.getFields())) {
        if (field.astNode?.directives?.length) {
          field.astNode = {
            ...field.astNode,
            directives: field.astNode.directives.filter(isBuiltin)
          };
        }
      }
    } else if (isInputObjectType(type)) {
      for (const field of Object.values(type.getFields())) {
        if (field.astNode?.directives?.length) {
          field.astNode = {
            ...field.astNode,
            directives: field.astNode.directives.filter(isBuiltin)
          };
        }
      }
    } else if (isEnumType(type)) {
      for (const value of type.getValues()) {
        if (value.astNode?.directives?.length) {
          value.astNode = {
            ...value.astNode,
            directives: value.astNode.directives.filter(isBuiltin)
          };
        }
      }
    }
  }
}
function isResolverRecord(value) {
  return value != null && typeof value === "object" && !Array.isArray(value);
}
function cloneResolverMap(resolverMap, schema) {
  const cloned = {};
  for (const typeName in resolverMap) {
    const typeResolvers = resolverMap[typeName];
    if (typeResolvers === void 0) {
      continue;
    }
    const type = schema.getType(typeName);
    if (!isResolverRecord(typeResolvers) || !isObjectType(type) && !isInterfaceType(type)) {
      cloned[typeName] = typeResolvers;
      continue;
    }
    const fieldConfigs = typeResolvers;
    const clonedType = {};
    for (const fieldName in fieldConfigs) {
      const field = fieldConfigs[fieldName];
      clonedType[fieldName] = isResolverRecord(field) ? { ...field } : field;
    }
    cloned[typeName] = clonedType;
  }
  return cloned;
}
function addLocalFieldResolvers(schema, resolvers, stitchingInfo, typeCandidates) {
  const subschemaFields = /* @__PURE__ */ new Set();
  const localFields = /* @__PURE__ */ new Map();
  for (const typeName in typeCandidates) {
    for (const candidate of typeCandidates[typeName]) {
      if (!isObjectType(candidate.type) && !isInterfaceType(candidate.type)) {
        continue;
      }
      const fieldNames = Object.keys(candidate.type.getFields());
      if (candidate.transformedSubschema != null || candidate.subschema != null) {
        for (const fieldName of fieldNames) {
          subschemaFields.add(`${typeName}.${fieldName}`);
        }
      } else {
        let fields = localFields.get(typeName);
        if (fields == null) {
          fields = /* @__PURE__ */ new Set();
          localFields.set(typeName, fields);
        }
        for (const fieldName of fieldNames) {
          fields.add(fieldName);
        }
      }
    }
  }
  for (const typeName in resolvers) {
    const typeResolvers = resolvers[typeName];
    if (typeResolvers == null || typeof typeResolvers !== "object") {
      continue;
    }
    let fields = localFields.get(typeName);
    if (fields == null) {
      fields = /* @__PURE__ */ new Set();
      localFields.set(typeName, fields);
    }
    for (const fieldName in typeResolvers) {
      if (fieldName.startsWith("__")) {
        continue;
      }
      fields.add(fieldName);
    }
  }
  for (const [typeName, fieldNames] of localFields) {
    const type = schema.getType(typeName);
    if (!isObjectType(type) && !isInterfaceType(type)) {
      continue;
    }
    const fields = type.getFields();
    for (const fieldName of fieldNames) {
      const field = fields[fieldName];
      const existing = resolvers[typeName]?.[fieldName];
      if (field == null || // subschema-owned fields keep their proxying resolver unless the user overrode it
      existing == null && subschemaFields.has(`${typeName}.${fieldName}`)) {
        continue;
      }
      const namedType = getNamedType(field.type);
      if (stitchingInfo.mergedTypes[namedType.name] == null) {
        continue;
      }
      const namedTypeResolvers = resolvers[namedType.name];
      const providedFields = namedTypeResolvers != null && typeof namedTypeResolvers === "object" ? new Set(
        Object.keys(namedTypeResolvers).filter(
          (fieldName2) => !fieldName2.startsWith("__")
        )
      ) : void 0;
      const originalResolve = typeof existing === "function" ? existing : existing?.resolve;
      const baseResolve = originalResolve ?? defaultMergedResolver;
      const wrappedResolve = (parent, args, context, info) => handleMaybePromise(
        () => baseResolve(parent, args, context, info),
        (result) => resolveLocalFieldResult(
          result,
          context,
          info,
          stitchingInfo,
          providedFields
        )
      );
      if (existing != null && typeof existing === "object") {
        existing.resolve = wrappedResolve;
      } else {
        (resolvers[typeName] ||= {})[fieldName] = wrappedResolve;
      }
    }
  }
}
const subschemaConfigTransformerPresets = [deferComputedFieldsTransformer, splitMergedTypeEntryPointsTransformer];
function applySubschemaConfigTransforms(subschemaConfigTransforms, subschemaOrSubschemaConfig, subschemaMap, originalSubschemaMap) {
  let subschemaConfig;
  if (isSubschemaConfig(subschemaOrSubschemaConfig)) {
    subschemaConfig = subschemaOrSubschemaConfig;
  } else if (subschemaOrSubschemaConfig instanceof GraphQLSchema) {
    subschemaConfig = { schema: subschemaOrSubschemaConfig };
  } else {
    throw new TypeError(
      "Received invalid input." + inspect(subschemaOrSubschemaConfig)
    );
  }
  const transformedSubschemaConfigs = subschemaConfigTransforms.concat(subschemaConfigTransformerPresets).reduce(
    (transformedSubschemaConfigs2, subschemaConfigTransform) => transformedSubschemaConfigs2.flatMap(
      (ssConfig) => subschemaConfigTransform(ssConfig)
    ),
    [subschemaConfig]
  );
  const transformedSubschemas = transformedSubschemaConfigs.map(
    (ssConfig) => new Subschema(ssConfig)
  );
  const baseSubschema = transformedSubschemas[0];
  subschemaMap.set(subschemaOrSubschemaConfig, baseSubschema);
  for (const subschema of transformedSubschemas) {
    originalSubschemaMap.set(subschema, subschemaOrSubschemaConfig);
  }
  return transformedSubschemas;
}
function prepareStitchingData(options) {
  const {
    subschemas = [],
    types = [],
    typeDefs = [],
    onTypeConflict,
    mergeTypes = true,
    typeMergingOptions,
    subschemaConfigTransforms = [],
    ...rest
  } = options;
  const mergeDirectives = rest.mergeDirectives ?? true;
  const transformedSubschemas = [];
  const subschemaMap = /* @__PURE__ */ new Map();
  const originalSubschemaMap = /* @__PURE__ */ new Map();
  for (const subschema of subschemas) {
    for (const transformedSubschemaConfig of applySubschemaConfigTransforms(
      subschemaConfigTransforms,
      subschema,
      subschemaMap,
      originalSubschemaMap
    )) {
      transformedSubschemas.push(transformedSubschemaConfig);
    }
  }
  const directiveMap = /* @__PURE__ */ Object.create(null);
  for (const directive of specifiedDirectives) {
    directiveMap[directive.name] = directive;
  }
  const schemaDefs = /* @__PURE__ */ Object.create(null);
  const [typeCandidates, rootTypeNameMap, extensions] = buildTypeCandidates({
    subschemas: transformedSubschemas,
    originalSubschemaMap,
    types,
    typeDefs: typeDefs || [],
    parseOptions: rest,
    directiveMap,
    schemaDefs,
    mergeDirectives
  });
  const stitchingInfo = createStitchingInfo(
    subschemaMap,
    typeCandidates,
    mergeTypes
  );
  const { typeMap: newTypeMap, directives: newDirectives } = buildTypes({
    typeCandidates,
    directives: Object.values(directiveMap),
    stitchingInfo,
    rootTypeNames: Object.values(rootTypeNameMap),
    onTypeConflict,
    mergeTypes,
    typeMergingOptions
  });
  return {
    typeCandidates,
    newTypeMap,
    newDirectives,
    rootTypeNameMap,
    stitchingInfo,
    schemaDefs,
    extensions,
    mergeDirectives
  };
}

const forwardArgsToSelectionSet = (selectionSet, mapping) => {
  const selectionSetDef = parseSelectionSet(selectionSet, { noLocation: true });
  return (field) => {
    const selections = selectionSetDef.selections.map(
      (selectionNode) => {
        if (selectionNode.kind === Kind.FIELD) {
          if (!mapping) {
            return { ...selectionNode, arguments: field.arguments?.slice() };
          } else if (selectionNode.name.value in mapping) {
            const selectionArgs = mapping[selectionNode.name.value];
            return {
              ...selectionNode,
              arguments: field.arguments?.filter(
                (arg) => !!selectionArgs?.includes(arg.name.value)
              )
            };
          }
        }
        return selectionNode;
      }
    );
    return { ...selectionSetDef, selections };
  };
};

const defaultRelayMergeConfig = {
  selectionSet: `{ id }`,
  fieldName: "node",
  args: ({ id }) => ({ id })
};
function handleRelaySubschemas(subschemas, getTypeNameFromId) {
  const typeNames = [];
  for (const subschema of subschemas) {
    const nodeType = subschema.schema.getType("Node");
    if (nodeType) {
      if (!isInterfaceType(nodeType)) {
        throw new Error(`Node type should be an interface!`);
      }
      const implementations = subschema.schema.getPossibleTypes(nodeType);
      for (const implementedType of implementations) {
        typeNames.push(implementedType.name);
        subschema.merge = subschema.merge || {};
        subschema.merge[implementedType.name] = defaultRelayMergeConfig;
      }
    }
  }
  const relaySubschemaConfig = {
    schema: makeExecutableSchema({
      typeDefs: (
        /* GraphQL */
        `
        type Query {
          node(id: ID!): Node
        }
        interface Node {
          id: ID!
        }
        ${typeNames.map(
          (typeName) => `
          type ${typeName} implements Node {
            id: ID!
          }
        `
        ).join("\n")}
      `
      ),
      resolvers: {
        Query: {
          node: (_, { id }) => ({ id })
        },
        Node: {
          __resolveType: ({ id }, _, info) => {
            if (!getTypeNameFromId) {
              const possibleTypeNames = /* @__PURE__ */ new Set();
              for (const fieldNode of info.fieldNodes) {
                if (fieldNode.selectionSet?.selections) {
                  for (const selection of fieldNode.selectionSet?.selections || []) {
                    switch (selection.kind) {
                      case Kind.FRAGMENT_SPREAD: {
                        const fragment = info.fragments[selection.name.value];
                        if (!fragment) {
                          throw new Error(
                            `Cannot find fragment ${selection.name.value}`
                          );
                        }
                        possibleTypeNames.add(
                          fragment.typeCondition.name.value
                        );
                        break;
                      }
                      case Kind.INLINE_FRAGMENT: {
                        const possibleTypeName = selection.typeCondition?.name.value;
                        if (possibleTypeName) {
                          possibleTypeNames.add(possibleTypeName);
                        }
                        break;
                      }
                    }
                  }
                }
              }
              if (possibleTypeNames.size !== 1) {
                console.warn(
                  `You need to define getTypeNameFromId as a parameter to handleRelaySubschemas or add a fragment for "node" operation with specific single type condition!`
                );
              }
              return [...possibleTypeNames][0] || typeNames[0];
            }
            return getTypeNameFromId(id);
          }
        }
      }
    })
  };
  subschemas.push(relaySubschemaConfig);
  return subschemas;
}

function createStitchingExecutor(stitchedSchema) {
  const subschemas = [
    ...(stitchedSchema.extensions?.["stitchingInfo"]).subschemaMap.values()
  ];
  return async function stitchingExecutor(executorRequest) {
    const fragments = getFragmentsFromDocument(executorRequest.document);
    const operation = getOperationASTFromRequest(executorRequest);
    const rootType = getDefinedRootType(stitchedSchema, operation.operation);
    const { fields } = collectFields(
      stitchedSchema,
      fragments,
      getVariableValues(executorRequest.variables),
      rootType,
      operation.selectionSet
    );
    const variableValues = asGetArgumentValuesVariables(
      executorRequest.variables ?? {}
    );
    const data = {};
    for (const [fieldName, fieldNodes] of fields) {
      const fieldNode = fieldNodes[0];
      if (!fieldNode) {
        continue;
      }
      const fieldInstance = rootType.getFields()[fieldName];
      if (!fieldInstance) {
        continue;
      }
      const responseKey = fieldNode.alias?.value ?? fieldName;
      const subschemaForField = subschemas.find((subschema) => {
        const subschemaSchema = isSubschemaConfig(subschema) ? subschema.schema : subschema;
        const rootType2 = getDefinedRootType(
          subschemaSchema,
          operation.operation
        );
        return rootType2.getFields()[fieldName] != null;
      });
      const args = getArgumentValues(fieldInstance, fieldNode, variableValues);
      const info = {
        schema: stitchedSchema,
        fieldName,
        fieldNodes,
        operation,
        fragments,
        parentType: rootType,
        returnType: fieldInstance.type,
        variableValues,
        rootValue: executorRequest.rootValue,
        path: { typename: void 0, key: responseKey, prev: void 0 },
        getAbortSignal: () => executorRequest.signal,
        getAsyncHelpers: () => ({
          promiseAll: Promise.all.bind(Promise),
          track: () => void 0
        })
      };
      let result = await delegateToSchema({
        schema: subschemaForField || stitchedSchema,
        rootValue: executorRequest.rootValue,
        args,
        context: executorRequest.context,
        info
      });
      if (Array.isArray(result)) {
        result = await Promise.all(result);
      }
      data[responseKey] = result;
    }
    return { data };
  };
}

export { DeferComputedFieldsTransform, ValidationLevel, calculateSelectionScore, createMergedTypeResolver, createMultiEntryMergedTypeResolver, createStitchingExecutor, deferComputedFieldsTransformer, entryPointAppliesToParent, forwardArgsToSelectionSet, getDefaultFieldConfigMerger, handleRelaySubschemas, overlayMergedTypeEntryPoint, splitMergedTypeEntryPointsTransformer, stitchSchemas };