"use strict";

exports.__esModule = true;
exports.writeTypeScriptTypes = writeTypeScriptTypes;
exports.DEFAULT_TYPES_OUTPUT_PATH = void 0;

var fs = _interopRequireWildcard(require("fs-extra"));

var _path = require("path");

var _core = require("@graphql-codegen/core");

var _graphql = require("graphql");

var _codeFileLoader = require("@graphql-tools/code-file-loader");

var _load = require("@graphql-tools/load");

var _utils = require("./utils");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const DEFAULT_TYPES_OUTPUT_PATH = `src/gatsby-types.d.ts`;
exports.DEFAULT_TYPES_OUTPUT_PATH = DEFAULT_TYPES_OUTPUT_PATH;
const NAMESPACE = `Queries`; // These override the defaults from
// https://www.graphql-code-generator.com/plugins/typescript

const DEFAULT_TYPESCRIPT_CONFIG = {
  // <Maybe> Type is enough
  avoidOptionals: true,
  // Types come from the data layer so they can't be modified
  immutableTypes: true,
  // TODO: Better maybeValue
  maybeValue: `T | null`,
  // We'll want to re-export ourselves
  noExport: true,
  // Recommended for .d.ts files
  enumsAsTypes: true,
  scalars: {
    Date: `string`,
    JSON: `Record<string, unknown>`,
    GatsbyImageData: `import('gatsby-plugin-image').IGatsbyImageData`
  },
  // import type {} syntax is nicer
  useTypeImports: true
};
const DEFAULT_TYPESCRIPT_OPERATIONS_CONFIG = { ...DEFAULT_TYPESCRIPT_CONFIG,
  exportFragmentSpreadSubTypes: true
};

async function writeTypeScriptTypes(directory, schema, definitions, graphqlTypegenOptions) {
  const pluginConfig = {
    pluginMap: {
      add: require(`@graphql-codegen/add`),
      typescript: require(`@graphql-codegen/typescript`),
      typescriptOperations: require(`@graphql-codegen/typescript-operations`)
    },
    plugins: [{
      add: {
        placement: `prepend`,
        content: `/* eslint-disable */\n`
      }
    }, {
      add: {
        placement: `prepend`,
        content: `/* THIS FILE IS AUTOGENERATED. CHANGES WILL BE LOST ON SUBSEQUENT RUNS. */\n`
      }
    }, {
      add: {
        placement: `prepend`,
        content: `declare namespace ${NAMESPACE} {\n`
      }
    }, {
      typescript: DEFAULT_TYPESCRIPT_CONFIG
    }, {
      typescriptOperations: DEFAULT_TYPESCRIPT_OPERATIONS_CONFIG
    }, {
      add: {
        placement: `append`,
        content: `\n}\n`
      }
    }]
  };
  const filename = (0, _path.join)(directory, graphqlTypegenOptions.typesOutputPath);
  let gatsbyNodeDocuments = []; // The loadDocuments + CodeFileLoader looks for graphql(``) functions inside the gatsby-node.ts files
  // And then extracts the queries into documents
  // TODO: This codepath can be made obsolete if Gatsby itself already places the queries inside gatsby-node into the `definitions`

  try {
    gatsbyNodeDocuments = await (0, _load.loadDocuments)([`./gatsby-node.ts`, `./plugins/**/gatsby-node.ts`], {
      loaders: [new _codeFileLoader.CodeFileLoader({
        // Configures https://www.graphql-tools.com/docs/graphql-tag-pluck to only check graphql function from Gatsby
        pluckConfig: {
          modules: [{
            name: `gatsby`,
            identifier: `graphql`
          }]
        }
      })],
      sort: true
    });
  } catch (e) {// These files might not exist, so just skip this
  }

  const documents = [...(0, _utils.filterTargetDefinitions)(definitions).values()].sort(_utils.sortDefinitions).map(definitionMeta => {
    return {
      document: {
        kind: _graphql.Kind.DOCUMENT,
        definitions: [definitionMeta.def]
      },
      hash: definitionMeta.hash.toString()
    };
  });
  const codegenOptions = {
    // @ts-ignore - Incorrect types
    schema: undefined,
    schemaAst: (0, _utils.stabilizeSchema)(schema),
    documents: documents.concat(gatsbyNodeDocuments),
    filename,
    config: {
      namingConvention: {
        typeNames: `keep`,
        enumValues: `keep`,
        transformUnderscore: false
      },
      addUnderscoreToArgsType: true,
      skipTypename: true
    }
  };
  const result = await (0, _core.codegen)({ ...pluginConfig,
    ...codegenOptions
  });
  await fs.outputFile(filename, result);
}
//# sourceMappingURL=ts-codegen.js.map