import fs from 'fs'; import path from 'path'; import { executeCodegen } from '@graphql-codegen/cli'; import nearOperationFilePreset from '@graphql-codegen/near-operation-file-preset'; type CodegenOptions = { typesOutputPath?: string | string[]; watchForFileChangesInPaths?: string[]; }; const content = `/* * This file is auto-generated by Graphweaver. * Please do not edit it directly. */`; export const codeGenerator = async (schema: string, options?: CodegenOptions) => { const extensions = '/**/!(*.generated).{ts,tsx}'; try { const files = await executeCodegen({ cwd: process.cwd(), pluginLoader: async (plugin: string) => import(plugin), schema, ignoreNoDocuments: true, noSilentErrors: true, documents: [ path.join('./src', extensions), ...(options?.watchForFileChangesInPaths?.map((clientPath) => path.join(clientPath, extensions) ) || []), ], generates: { 'src/types.generated.ts': { config: { skipDocumentsValidation: { skipDuplicateValidation: true, // A flag to disable the validation for duplicate query and mutation names (we don't need this as we are using near-operation-file) }, noSilentErrors: true, }, plugins: [ { add: { content, }, }, 'typescript', ], }, 'src/': { preset: nearOperationFilePreset, presetConfig: { extension: '.generated.ts', baseTypesPath: 'types.generated.ts', }, plugins: [ { add: { content, }, }, 'typescript-operations', 'typescript-react-apollo', ], }, }, }); const typesOutputPaths = formatListOfTypeOutputPaths(options?.typesOutputPath); // Write the files to disk const writeOperations = files.result.flatMap((file) => [ fs.promises.writeFile(path.join(file.filename), file.content, 'utf8'), // We save the types to two locations: src and .graphweaver / outdir ...(file.filename === 'src/types.generated.ts' ? typesOutputPaths.map((outputPath: string) => fs.promises.writeFile(outputPath, file.content, 'utf8') ) : []), ]); // Write the files to disk await Promise.all(writeOperations); } catch (err: any) { const defaultStateMessage = `Unable to find any GraphQL type definitions for the following pointers:`; if (err.message && err.message.includes(defaultStateMessage)) { // do nothing for now and silently fail } else { throw err; } } }; const formatListOfTypeOutputPaths = (typesOutputPath?: string | string[]) => { const typesOutput = ['./src/frontend/types.generated.ts']; // If the typesOutputPath is a string or an array of strings, add it to the typesOutput array if (typesOutputPath && typeof typesOutputPath === 'string') { typesOutput.push(typesOutputPath); } if (typesOutputPath && Array.isArray(typesOutputPath)) { typesOutput.push(...typesOutputPath); } // Ensure that all paths have a filename and add one if it does not exist typesOutput.forEach((path, index) => { if (!path.includes('.ts')) { typesOutput[index] = `${path}/types.generated.ts`; } }); // Ensure that the typesOutput directories exist console.log('Generating types in the following paths:'); for (const outputPath of typesOutput) { const dirPath = path.dirname(path.join(process.cwd(), outputPath)); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath, { recursive: true }); } console.log(dirPath); } return typesOutput; };