All files / src/library index.ts

84.12% Statements 53/63
55% Branches 11/20
100% Functions 9/9
83.87% Lines 52/62

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 1631x 1x   1x 1x     1x 1x   1x                     1x   1x   1x     3x 3x 3x                           1x 3x 3x   3x       3x 3x   3x 3x 3x   3x                               3x 3x             3x                     3x           3x   3x 3x   3x 3x     3x               3x       3x 3x 3x 3x   3x         3x 3x 3x     3x 3x           3x 3x   3x       3x 3x   3x 3x         3x      
import { chain, Rule, Tree } from '@angular-devkit/schematics';
import * as ts from 'typescript';
import { workspaces } from '@angular-devkit/core';
import * as strings from '../utils/angular/strings';
import { SchematicsException } from '@angular-devkit/schematics';
 
import { Schema as LibraryOptions, NormalizedSchema as NormalizedLibraryOptions } from './schema';
import { insertImport } from '../utils/angular/ast-utils';
import { addImportToModule, insert } from '../utils/nrwl/ast-utils';
 
import {
  addBackbaseTemplates,
  getLibPath,
  getAppPath,
  readFileOrThrow,
  addProjectToWorkspace,
  getWorkspace,
  projectPrefix,
  nameWithSuffix,
  WorkspaceDefinition,
} from '../utils/backbase/package-utils';
import { libVersions } from '../lib-versions';
 
import { setNpmScope, getNpmScope } from '../utils/backbase/scope-utils';
 
import { updateAddApiExtractorToLibRule } from '../utils/backbase/api-extractor';
 
function normalizeOptions(options: LibraryOptions, host: Tree): NormalizedLibraryOptions {
  const npmScope = getNpmScope(options.npmScope, host);
  setNpmScope(npmScope, host);
  return {
    ...options,
    npmScope,
    name: strings.dasherize(options.name),
    moduleName: nameWithSuffix(options.name),
    path: `libs/${strings.dasherize(options.name)}/src`,
    skipImport: true,
    inlineTemplate: true,
    inlineStyle: true,
    flat: true,
    ...libVersions,
  };
}
 
export default function (options: LibraryOptions): Rule {
  return async (host: Tree) => {
    const libraryOptions = normalizeOptions(options, host);
 
    Iif (/^@.*\/.*/.test(libraryOptions.name)) {
      throw new SchematicsException('Name should not include scope, please use --npmScope option');
    }
 
    const workspace = await getWorkspace(host);
    const projectRoot = `libs/${strings.dasherize(libraryOptions.name)}`;
 
    const projectName = options.project ?? workspace.extensions.defaultProject ?? undefined;
    const prefix = await projectPrefix(host, projectName);
    const libPath = `/${getLibPath(options.name)}`;
 
    return chain([
      addBackbaseTemplates<LibraryOptions>(libraryOptions),
      applyPublicRules(libraryOptions, libPath),
      addToProjectModule(workspace, libraryOptions),
      addLibToWorkspaceFile(workspace, projectRoot, libraryOptions, prefix),
      updateAddApiExtractorToLibRule('/package.json', !!options.public, options.name),
    ]);
  };
}
 
function addLibToWorkspaceFile(
  workspace: WorkspaceDefinition,
  projectRoot: string,
  options: LibraryOptions,
  prefix: string,
): Rule {
  let applicationName = options.project;
  Iif (!applicationName) {
    applicationName = workspace.extensions.defaultProject;
    Iif (!applicationName) {
      throw new Error('No default app found. You must first generate an app');
    }
  }
 
  const test: workspaces.TargetDefinition = {
    builder: '@angular-devkit/build-angular:karma',
    options: {
      main: `${projectRoot}/test.ts`,
      karmaConfig: './karma.conf.js',
      polyfills: `${getAppPath(applicationName)}/polyfills.ts`,
      tsConfig: './tsconfig.spec.json',
      codeCoverage: true,
      codeCoverageExclude: ['test.ts', '**/polyfills.ts'],
    },
  };
  const lint: workspaces.TargetDefinition = {
    builder: '@angular-eslint/builder:lint',
    options: {
      lintFilePatterns: [`${projectRoot}/**/*.ts`, `${projectRoot}/**/*.html`],
    },
  };
  const architect: Record<string, workspaces.TargetDefinition | undefined> = {};
 
  if (!options.skipTest) {
    architect['test'] = test;
  }
  if (!options.skipLint) {
    architect['lint'] = lint;
  }
 
  const project = {
    root: `${projectRoot}`,
    sourceRoot: `${projectRoot}/src`,
    projectType: 'library',
    prefix,
    targets: architect,
  };
 
  return addProjectToWorkspace(workspace, options.name, project);
}
 
function applyPublicRules(options: LibraryOptions, libPath: string): Rule {
  return (tree: Tree): Tree => {
    if (!options.public) {
      tree.delete(`${libPath}/package.json`);
      tree.delete(`${libPath}/api-extractor.json`);
    }
    return tree;
  };
}
 
function addToProjectModule(workspace: WorkspaceDefinition, options: NormalizedLibraryOptions): Rule {
  const className = strings.capitalize(strings.camelize(options.name));
  return (host: Tree): Tree => {
    Iif (options.noProject) {
      return host;
    }
    let project = options.project;
    Iif (!project) {
      project = workspace.extensions.defaultProject;
      Iif (!project) {
        throw new Error('No default app found. You must first generate an app');
      }
    }
    const modulePath = `${getAppPath(project)}/app/app.module.ts`;
    const moduleSource = readFileOrThrow(host, modulePath);
 
    Iif (!moduleSource || !moduleSource.length) {
      console.warn(`Failed to add item imports to the project module. File not found: ${modulePath}`);
      return host;
    }
    let npmScope: string = getNpmScope(options.npmScope, host);
    setNpmScope(npmScope, host);
 
    const sourceFile = ts.createSourceFile(modulePath, moduleSource, ts.ScriptTarget.Latest, true);
    insert(host, modulePath, [
      insertImport(sourceFile, modulePath, `${className}Module`, `@${npmScope}/${options.name}`),
      ...addImportToModule(sourceFile, modulePath, `${className}Module`),
    ]);
 
    return host;
  };
}