All files / generators/e2e-project generator.ts

100% Statements 65/65
100% Branches 6/6
100% Functions 8/8
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 2612x                             2x 2x 2x 2x 2x 2x     2x 2x 2x   2x   2x       46x                       2x       23x                   2x       23x                   2x         46x   46x                                   46x   23x                 46x     2x       46x   46x                         2x                                     2x       46x   46x           46x                       46x       46x 46x 46x 46x 46x   46x 46x 46x   46x     2x         46x   46x           46x 23x           23x               2x       46x 46x           46x   46x           46x 46x 23x   23x     46x   46x 46x   46x   46x 4x     46x     2x  
import {
  addDependenciesToPackageJson,
  addProjectConfiguration,
  formatFiles,
  generateFiles,
  GeneratorCallback,
  joinPathFragments,
  offsetFromRoot,
  ProjectConfiguration,
  readProjectConfiguration,
  runTasksInSerial,
  Tree,
  updateProjectConfiguration,
  writeJson,
} from '@nx/devkit';
import { Linter, lintProjectGenerator } from '@nx/eslint';
import { configurationGenerator } from '@nx/jest';
import { getRelativePathToRootTsConfig } from '@nx/js';
import { ProjectType } from '@nx/workspace';
import { resolve } from 'node:path';
import normalizeProjectOptions, {
  NormalizedProjectOptionsApplication,
} from '../../utils/normalize-project-options';
import { getVersions, Versions } from '../../utils/versions';
import { AppType } from '../cdk-app/app-type';
import initGenerator from '../init/generator';
import { E2ESchema } from './schema';
import { toValidSsmParameterName } from './to-valid-ssm-parameter-name';
 
const addCommonDependencies = (
  tree: Tree,
  versions: Versions,
): GeneratorCallback => {
  return addDependenciesToPackageJson(
    tree,
    {
      // E2E common
      '@aws-sdk/credential-providers':
        versions['@aws-sdk/credential-providers'],
      '@aws-sdk/client-ssm': versions['@aws-sdk/client-ssm'],
    },
    {},
  );
};
 
const addGenericDependencies = (
  tree: Tree,
  versions: Versions,
): GeneratorCallback => {
  return addDependenciesToPackageJson(
    tree,
    {
      // E2E generic dependencies
      '@aws-sdk/client-sqs': versions['@aws-sdk/client-sqs'],
    },
    {},
  );
};
 
const addLambdaDependencies = (
  tree: Tree,
  versions: Versions,
): GeneratorCallback => {
  return addDependenciesToPackageJson(
    tree,
    {
      // E2E lambda dependencies
      '@aws-sdk/client-lambda': versions['@aws-sdk/client-lambda'],
    },
    {},
  );
};
 
const addConfiguration = (
  tree: Tree,
  options: E2ESchema,
  projectOptions: NormalizedProjectOptionsApplication,
): void => {
  const { projectName, projectRoot } = projectOptions;
 
  const projectConfiguration: ProjectConfiguration = {
    root: projectRoot,
    sourceRoot: joinPathFragments(projectRoot, 'src'),
    implicitDependencies: [options.project],
    projectType: 'application',
    targets: {
      e2e: {
        executor: '@nx/jest:jest',
        outputs: [`{workspaceRoot}/coverage/{projectRoot}`],
        cache: false,
        options: {
          jestConfig: `${projectRoot}/jest.config.ts`,
          passWithNoTests: true,
        },
      },
    },
  };
 
  if (options.type === AppType.lambda) {
    (
      projectConfiguration.targets as NonNullable<
        typeof projectConfiguration.targets
      >
    )['generate-event'] = {
      executor: 'nx-serverless-cdk:generate-event',
      options: {},
    };
  }
 
  addProjectConfiguration(tree, projectName, projectConfiguration);
};
 
const addEslint = async (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsApplication,
): Promise<GeneratorCallback> => {
  const { projectName, projectRoot } = projectOptions;
 
  return await lintProjectGenerator(tree, {
    project: projectName,
    linter: Linter.EsLint,
    eslintFilePatterns: [`${projectRoot}/**/*.ts`],
    tsConfigPaths: [joinPathFragments(projectRoot, 'tsconfig.spec.json')],
    skipFormat: true,
    setParserOptionsProject: false,
    skipPackageJson: false,
    unitTestRunner: 'jest',
    rootProject: false,
  });
};
 
const jestConfigSnippet = `,
  collectCoverageFrom: [
    'src/**/*.ts',
    '!jest.config.ts',
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  coverageReporters: ['lcov', 'text'],
  resetMocks: true,
  testTimeout: 10000,
};
`;
 
const addJest = async (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsApplication,
): Promise<GeneratorCallback> => {
  const { projectName, projectRoot } = projectOptions;
 
  writeJson(
    tree,
    joinPathFragments(projectOptions.projectRoot, 'tsconfig.json'),
    {},
  );
 
  const callback = await configurationGenerator(tree, {
    project: projectName,
    supportTsx: false,
    setupFile: 'none',
    skipSerializers: true,
    testEnvironment: 'node',
    skipFormat: true,
    compiler: 'tsc',
    skipPackageJson: false,
    js: false,
  });
 
  const jestConfig = tree.read(
    `${projectRoot}/jest.config.ts`,
    'utf-8',
  ) as string;
  const lines = jestConfig.split('\n');
  lines.pop();
  lines.pop();
  const extendedJestConfig = lines.join('\n') + jestConfigSnippet;
  tree.write(`${projectRoot}/jest.config.ts`, extendedJestConfig);
 
  const config = readProjectConfiguration(tree, projectName);
  delete config.targets?.['test'];
  updateProjectConfiguration(tree, projectName, config);
 
  return callback;
};
 
const addFiles = (
  tree: Tree,
  options: E2ESchema,
  projectOptions: NormalizedProjectOptionsApplication,
): void => {
  const { projectRoot } = projectOptions;
 
  generateFiles(tree, resolve(__dirname, 'files'), projectRoot, {
    offset: offsetFromRoot(projectRoot),
    rootTsConfigPath: getRelativePathToRootTsConfig(tree, projectRoot),
    tmpl: '',
  });
 
  if (options.type === AppType.generic) {
    generateFiles(tree, resolve(__dirname, 'files-generic'), projectRoot, {
      project: options.project,
      toValidSsmParameterName,
      tmpl: '',
    });
  } else {
    generateFiles(tree, resolve(__dirname, 'files-lambda'), projectRoot, {
      project: options.project,
      toValidSsmParameterName,
      tmpl: '',
    });
  }
};
 
export const e2eProjectGenerator = async (
  tree: Tree,
  options: E2ESchema,
): Promise<GeneratorCallback> => {
  const versions = getVersions();
  const projectOptions = normalizeProjectOptions(tree, {
    name: options.name,
    directory: options.directory,
    projectType: ProjectType.Application,
  });
 
  const tasks: GeneratorCallback[] = [];
 
  tasks.push(
    await initGenerator(tree, {
      skipFormat: true,
    }),
  );
 
  tasks.push(addCommonDependencies(tree, versions));
  if (options.type === AppType.generic) {
    tasks.push(addGenericDependencies(tree, versions));
  } else {
    tasks.push(addLambdaDependencies(tree, versions));
  }
 
  addConfiguration(tree, options, projectOptions);
 
  tasks.push(await addEslint(tree, projectOptions));
  tasks.push(await addJest(tree, projectOptions));
 
  addFiles(tree, options, projectOptions);
 
  if (!options.skipFormat) {
    await formatFiles(tree);
  }
 
  return runTasksInSerial(...tasks);
};
 
export default e2eProjectGenerator;