All files / generators/cdk-lib generator.ts

100% Statements 62/62
100% Branches 2/2
100% Functions 8/8
100% Lines 61/61

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 2351x                         1x 1x 1x 1x 1x     1x 1x     1x         19x   19x                                                 19x 3x     19x     1x       19x 19x   19x   19x 19x                       19x                                                     19x   79x   19x     1x       19x   19x   19x 19x 19x     19x     1x       19x   19x     1x                                     1x       19x   19x       19x 19x 19x 19x 19x     1x         19x   19x                   1x       19x 19x             19x   19x           19x   19x 19x 19x 19x   19x   19x 2x     19x     1x  
import {
  formatFiles,
  generateFiles,
  GeneratorCallback,
  joinPathFragments,
  offsetFromRoot,
  readJson,
  readProjectConfiguration,
  runTasksInSerial,
  Tree,
  updateProjectConfiguration,
  writeJson,
} from '@nx/devkit';
import { Linter } from '@nx/eslint';
import { getRelativePathToRootTsConfig, libraryGenerator } from '@nx/js';
import { ProjectType } from '@nx/workspace';
import { resolve } from 'node:path';
import normalizeProjectOptions, {
  NormalizedProjectOptionsLibrary,
} from '../../utils/normalize-project-options';
import { getVersions, Versions } from '../../utils/versions';
import initGenerator from '../init/generator';
import { CdkLibSchema } from './schema';
 
const addJsLibrary = async (
  tree: Tree,
  options: CdkLibSchema,
  projectOptions: NormalizedProjectOptionsLibrary,
): Promise<GeneratorCallback> => {
  const { projectName, projectRoot, importPath } = projectOptions;
 
  const libOptions: Parameters<typeof libraryGenerator>[1] = {
    name: projectName,
    directory: projectRoot,
    projectNameAndRootFormat: 'as-provided',
    skipFormat: true,
    tags: 'cdk-lib',
    skipTsConfig: false,
    skipPackageJson: false,
    includeBabelRc: false,
    unitTestRunner: 'jest',
    linter: Linter.EsLint,
    testEnvironment: 'node',
    importPath,
    js: false,
    pascalCaseFiles: false,
    strict: false,
    setParserOptionsProject: false,
    config: 'project',
    bundler: 'esbuild',
    skipTypeCheck: false,
    minimal: false,
    rootProject: false,
    simpleName: false,
  };
 
  if (options.publishable) {
    libOptions.publishable = options.publishable;
  }
 
  return await libraryGenerator(tree, libOptions);
};
 
const changeProjectConfiguration = (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsLibrary,
): void => {
  const { projectName, projectRoot } = projectOptions;
  const config = readProjectConfiguration(tree, projectName);
 
  config.sourceRoot = joinPathFragments(projectRoot, 'cdk');
 
  const configTargets = config.targets as NonNullable<typeof config.targets>;
  configTargets['build-declarations'] = {
    executor: '@nx/js:tsc',
    options: {
      cache: false,
      clean: true,
      main: joinPathFragments(projectRoot, 'cdk', 'index.ts'),
      outputPath: joinPathFragments('dist', projectRoot),
      tsConfig: joinPathFragments(projectRoot, 'tsconfig.cdk.dts.json'),
    },
    dependsOn: ['^build-declarations'],
  };
 
  configTargets['build'] = {
    executor: '@nx/esbuild:esbuild',
    outputs: ['{options.outputPath}'],
    options: {
      assets: [joinPathFragments(projectRoot, '*.md')],
      bundle: true,
      // handled by build-declarations
      deleteOutputPath: false,
      format: ['cjs'],
      main: joinPathFragments(projectRoot, 'cdk', 'index.ts'),
      minify: true,
      outputPath: joinPathFragments('dist', projectRoot),
      platform: 'node',
      esbuildOptions: {
        outExtension: {
          '.js': '.js',
        },
        sourcemap: 'inline',
        sourcesContent: true,
      },
      target: 'node20',
      thirdParty: false,
      tsConfig: joinPathFragments(projectRoot, 'tsconfig.cdk.json'),
    },
    dependsOn: ['build-declarations'],
  };
 
  config.targets = Object.keys(configTargets)
    .sort()
    .reduce((acc, key) => ({ ...acc, ...{ [key]: configTargets[key] } }), {});
 
  updateProjectConfiguration(tree, projectName, config);
};
 
const changeSrcDirectory = (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsLibrary,
): void => {
  const { projectRoot, importPath } = projectOptions;
 
  tree.delete(joinPathFragments(projectRoot, 'src'));
 
  const tsConfigBaseFilePath = 'tsconfig.base.json';
  const tsConfigBase = readJson(tree, tsConfigBaseFilePath);
  tsConfigBase.compilerOptions.paths[importPath] = [
    joinPathFragments(projectRoot, 'cdk', 'index.ts'),
  ];
  writeJson(tree, tsConfigBaseFilePath, tsConfigBase);
};
 
const removeTsconfigLibJson = (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsLibrary,
): void => {
  const { projectRoot } = projectOptions;
 
  tree.delete(joinPathFragments(projectRoot, 'tsconfig.lib.json'));
};
 
const jestConfigSnippet = `,
  collectCoverageFrom: [
    'cdk/**/*.ts',
    '!cdk/index.ts',
    '!jest.config.ts',
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  coverageReporters: ['lcov', 'text'],
  resetMocks: true,
};
`;
 
const changeJestConfig = (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsLibrary,
): void => {
  const { projectRoot } = projectOptions;
 
  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 addFiles = (
  tree: Tree,
  projectOptions: NormalizedProjectOptionsLibrary,
  versions: Versions,
): void => {
  const { projectName, projectRoot, importPath } = projectOptions;
 
  generateFiles(tree, resolve(__dirname, 'files'), projectRoot, {
    projectName,
    importPath,
    versions,
    offset: offsetFromRoot(projectRoot),
    rootTsConfigPath: getRelativePathToRootTsConfig(tree, projectRoot),
    tmpl: '',
  });
};
 
export const cdkLibGenerator = async (
  tree: Tree,
  options: CdkLibSchema,
): Promise<GeneratorCallback> => {
  const versions = getVersions();
  const projectOptions = normalizeProjectOptions(tree, {
    name: options.name,
    directory: options.directory,
    projectType: ProjectType.Library,
    importPath: options.importPath,
  });
 
  const tasks: GeneratorCallback[] = [];
 
  tasks.push(
    await initGenerator(tree, {
      skipFormat: true,
    }),
  );
 
  tasks.push(await addJsLibrary(tree, options, projectOptions));
 
  changeProjectConfiguration(tree, projectOptions);
  changeSrcDirectory(tree, projectOptions);
  removeTsconfigLibJson(tree, projectOptions);
  changeJestConfig(tree, projectOptions);
 
  addFiles(tree, projectOptions, versions);
 
  if (!options.skipFormat) {
    await formatFiles(tree);
  }
 
  return runTasksInSerial(...tasks);
};
 
export default cdkLibGenerator;