All files nx-monorepo.ts

92.3% Statements 48/52
80% Branches 20/25
93.33% Functions 14/15
92.15% Lines 47/51

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274      1x 1x 1x 1x 1x         1x         1x             1x             1x                                                                                                                   1x 4x 4x     4x                       4x     4x     4x 4x   4x   4x               4x         4x                                                                               1x     1x             18x 18x             5x     5x                   5x   6x           5x   6x   6x                               4x 1x       4x   4x     3x               1x 1x 1x 1x 1x 10x           1x   1x           4x         4x    
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
 
import * as fs from "fs";
import * as path from "path";
import { IgnoreFile, JsonFile, Project, TextFile, YamlFile } from "projen";
import { NodePackageManager, NodeProject } from "projen/lib/javascript";
import {
  TypeScriptProject,
  TypeScriptProjectOptions,
} from "projen/lib/typescript";
 
const NX_MONOREPO_PLUGIN_PATH: string = ".nx/plugins/nx-monorepo-plugin.js";
 
/**
 * Supported enums for a TargetDependency.
 */
export enum TargetDependencyProject {
  /**
   * Only rely on the package where the target is called.
   *
   * This is usually done for test like targets where you only want to run unit
   * tests on the target packages without testing all dependent packages.
   */
  SELF = "self",
  /**
   * Target relies on executing the target against all dependencies first.
   *
   * This is usually done for build like targets where you want to build all
   * dependant projects first.
   */
  DEPENDENCIES = "dependencies",
}
 
/**
 * Represents an NX Target Dependency.
 */
export interface TargetDependency {
  /**
   * Projen target i.e: build, test, etc
   */
  readonly target: string;
 
  /**
   * Target dependencies.
   */
  readonly projects: TargetDependencyProject;
}
 
/**
 * Configuration for nx targetDependencies.
 */
export type TargetDependencies = { [target: string]: TargetDependency[] };
 
/**
 * Configuration options for the NxMonorepoProject.
 */
export interface NxMonorepoProjectOptions extends TypeScriptProjectOptions {
  /**
   * Configuration for NX TargetDependencies.
   *
   * @link https://nx.dev/configuration/packagejson#target-dependencies
   * @default {}
   */
  readonly targetDependencies?: TargetDependencies;
 
  /**
   * List of patterns to include in the .nxignore file.
   *
   * @link https://nx.dev/configuration/packagejson#nxignore
   * @default []
   */
  readonly nxIgnorePatterns?: string[];
 
  /**
   * List of package globs to exclude from hoisting in the workspace.
   *
   * @link https://classic.yarnpkg.com/blog/2018/02/15/nohoist/
   * @default []
   */
  readonly noHoistGlobs?: string[];
}
 
/**
 * This project type will bootstrap a NX based monorepo with support for polygot
 * builds, build caching, dependency graph visualization and much more.
 *
 * @pjid nx-monorepo
 */
export class NxMonorepoProject extends TypeScriptProject {
  private readonly implicitDependencies: { [pkg: string]: string[] } = {};
  private readonly noHoistGlobs?: string[] = [];
 
  constructor(options: NxMonorepoProjectOptions) {
    super({
      ...options,
      github: false,
      jest: false,
      package: false,
      prettier: true,
      projenrcTs: true,
      release: false,
      sampleCode: false,
      defaultReleaseBranch: "mainline",
    });
 
    this.noHoistGlobs = options.noHoistGlobs;
 
    // Never publish a monorepo root package.
    this.package.addField("private", true);
 
    // No need to compile or test a monorepo root package.
    this.compileTask.reset();
    this.testTask.reset();
 
    this.addDevDeps("@nrwl/cli", "@nrwl/workspace");
 
    new IgnoreFile(this, ".nxignore").exclude(
      "test-reports",
      "target",
      ".env",
      ".pytest_cache",
      ...(options.nxIgnorePatterns || [])
    );
 
    new TextFile(this, NX_MONOREPO_PLUGIN_PATH, {
      readonly: true,
      lines: fs.readFileSync(getPluginPath()).toString("utf-8").split("\n"),
    });
 
    new JsonFile(this, "nx.json", {
      obj: {
        extends: "@nrwl/workspace/presets/npm.json",
        plugins: [`./${NX_MONOREPO_PLUGIN_PATH}`],
        npmScope: "monorepo",
        tasksRunnerOptions: {
          default: {
            runner: "@nrwl/workspace/tasks-runners/default",
            options: {
              useDaemonProcess: false,
              cacheableOperations: ["build", "test"],
            },
          },
        },
        implicitDependencies: this.implicitDependencies,
        targetDependencies: {
          build: [
            {
              target: "build",
              projects: "dependencies",
            },
          ],
          ...(options.targetDependencies || {}),
        },
        affected: {
          defaultBase: "mainline",
        },
      },
    });
  }
 
  /**
   * Create an implicit dependency between two Project's. This is typically
   * used in polygot repos where a Typescript project wants a build dependency
   * on a Python project as an example.
   *
   * @param dependent project you want to have the dependency.
   * @param dependee project you wish to depend on.
   */
  public addImplicitDependency(dependent: Project, dependee: Project) {
    Iif (this.implicitDependencies[dependent.name]) {
      this.implicitDependencies[dependent.name].push(dependee.name);
    } else {
      this.implicitDependencies[dependent.name] = [dependee.name];
    }
  }
 
  // Remove this hack once subProjects is made public in Projen
  protected get subProjects(): Project[] {
    // @ts-ignore
    const subProjects: Project[] = this.subprojects || [];
    return subProjects.sort((a, b) => a.name.localeCompare(b.name));
  }
 
  /**
   * @inheritDoc
   */
  preSynthesize() {
    super.preSynthesize();
 
    // Add workspaces for each subproject
    Iif (this.package.packageManager === NodePackageManager.PNPM) {
      new YamlFile(this, "pnpm-workspace.yaml", {
        readonly: true,
        obj: {
          packages: this.subProjects.map((subProject) =>
            path.relative(this.outdir, subProject.outdir)
          ),
        },
      });
    } else {
      this.package.addField("workspaces", {
        packages: this.subProjects.map((subProject) =>
          path.relative(this.outdir, subProject.outdir)
        ),
        nohoist: this.noHoistGlobs,
      });
    }
 
    this.subProjects.forEach((subProject: any) => {
      // Disable default task on subprojects as this isn't supported in a monorepo
      subProject.defaultTask?.reset();
 
      Iif (
        (subProject instanceof NodeProject || subProject.package) &&
        subProject.package.packageManager !== this.package.packageManager
      ) {
        throw new Error(
          `${subProject.name} packageManager does not match the monorepo packageManager: ${this.package.packageManager}.`
        );
      }
    });
  }
 
  /**
   * @inheritDoc
   */
  synth() {
    // Check to see if a new subProject was added
    const newSubProject = this.subProjects.find(
      (subProject) => !fs.existsSync(subProject.outdir)
    );
 
    // Need to synth before generating the package.json otherwise the subdirectory won't exist
    newSubProject && super.synth();
 
    this.subProjects
      .filter(
        (subProject) =>
          !subProject.tryFindObjectFile("package.json") ||
          (fs.existsSync(`${subProject.outdir}/package.json`) &&
            JSON.parse(
              fs.readFileSync(`${subProject.outdir}/package.json`).toString()
            ).__pdk__)
      )
      .forEach((subProject) => {
        // generate a package.json if not found
        const manifest: any = {};
        manifest.name = subProject.name;
        manifest.private = true;
        manifest.__pdk__ = true;
        manifest.scripts = subProject.tasks.all.reduce(
          (p, c) => ({
            [c.name]: `npx projen ${c.name}`,
            ...p,
          }),
          {}
        );
        manifest.version = "0.0.0";
 
        new JsonFile(subProject, "package.json", {
          obj: manifest,
          readonly: true,
        });
      });
 
    super.synth();
  }
}
 
function getPluginPath() {
  return path.join(__dirname, "plugin/nx-monorepo-plugin.js");
}