All files / builder/application mini-program-application-analysis.service.ts

92.81% Statements 142/153
78.26% Branches 36/46
87.87% Functions 29/33
92.76% Lines 141/152

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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365    1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x                   1x 11x 10x 10x             10x 10x 10x 10x 10x   10x 10x 10x       10x         10x                     10x 10x   10x   10x 10x 10x 10x 10x 10x 221x 221x     10x 221x 221x   10x 10x   10x   10x 221x 221x   10x 10x 221x 221x   10x 10x 221x 221x     10x 10x               10x 221x 221x   30x       30x     221x 100x                 221x             10x 10x           10x 10x           10x 10x             10x                   10x 10x 10x 10x     10x 10x 10x 10x         10x 10x 10x 10x 2x             8x   10x       773x     773x 1916x 1916x 1916x 1143x   773x 9770x   773x 773x 773x   773x 453x     453x   320x     320x   773x 773x 773x   773x         773x       773x 773x             773x     773x       10x 10x 10x 5757x 2590x   5757x               6647x       6647x   6647x 6647x                 10x         10x 10x                               10x             3863x 12877x               12877x 6647x   12877x             10x 10x     10x     10x             10x 10x   32x   32x 16696x 703x       32x        
import type { NgtscProgram, ParsedConfiguration } from '@angular/compiler-cli';
import type { NgCompiler } from '@angular/compiler-cli/src/ngtsc/core';
import { join, normalize, resolve } from '@angular-devkit/core';
import { externalizePath } from '@ngtools/webpack/src/ivy/paths';
import { createHash } from 'crypto';
import { createCssSelectorForTs } from 'cyia-code-util';
import * as path from 'path';
import { Inject, Injectable, Injector } from 'static-injector';
import ts from 'typescript';
import type { CompilerOptions } from 'typescript';
import { Compilation, Compiler } from 'webpack';
import { LIBRARY_OUTPUT_ROOTDIR } from '../library';
import { MiniProgramCompilerService } from '../mini-program-compiler';
import { BuildPlatform } from '../platform/platform';
import { angularCompilerCliPromise } from '../util/load_esm';
import {
  OLD_BUILDER,
  PAGE_PATTERN_TOKEN,
  TS_CONFIG_TOKEN,
  TS_SYSTEM,
  WEBPACK_COMPILATION,
  WEBPACK_COMPILER,
} from './token';
import type { PagePattern } from './type';
 
@Injectable()
export class MiniProgramApplicationAnalysisService {
  private dependencyUseModule = new Map<string, string[]>();
  private cleanDependencyFileCacheSet = new Set<string>();
  builder!: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;
  private ngTscProgram!: NgtscProgram;
  private tsProgram!: ts.Program;
  private ngCompiler!: NgCompiler;
  private typeChecker!: ts.TypeChecker;
  constructor(
    private injector: Injector,
    @Inject(WEBPACK_COMPILATION) private compilation: Compilation,
    @Inject(TS_SYSTEM) private system: ts.System,
    @Inject(WEBPACK_COMPILER) private compiler: Compiler,
    @Inject(TS_CONFIG_TOKEN) private tsConfig: string,
    @Inject(OLD_BUILDER)
    private oldBuilder: ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined,
    @Inject(PAGE_PATTERN_TOKEN) private pagePatternList: PagePattern[],
    private buildPlatform: BuildPlatform
  ) {}
 
  async exportComponentBuildMetaMap() {
    const injector = Injector.create({
      providers: [
        {
          provide: MiniProgramCompilerService,
          useFactory: (injector: Injector, buildPlatform: BuildPlatform) => {
            return new MiniProgramCompilerService(
              this.ngTscProgram,
              injector,
              buildPlatform
            );
          },
          deps: [Injector, BuildPlatform],
        },
      ],
      parent: this.injector,
    });
    const miniProgramCompilerService = injector.get(MiniProgramCompilerService);
    miniProgramCompilerService.init();
    const metaMap =
      await miniProgramCompilerService.exportComponentBuildMetaMap();
 
    const selfMetaCollection = metaMap.otherMetaCollectionGroup['$self'];
    const selfTemplate: Record<string, string> = {};
    Eif (selfMetaCollection) {
      const importSelfTemplatePath = `/self-template/self${this.buildPlatform.fileExtname.contentTemplate}`;
      const importSelfTemplate = `<import src="${importSelfTemplatePath}"/>`;
      metaMap.outputContent.forEach((value, key) => {
        value = `${importSelfTemplate}${value}`;
        metaMap.outputContent.set(key, value);
      });
 
      metaMap.useComponentPath.forEach((value, key) => {
        value.libraryPath.push(...selfMetaCollection.libraryPath);
        value.localPath.push(...selfMetaCollection.localPath);
      });
      selfTemplate[importSelfTemplatePath] = selfMetaCollection.templateList
        .map((item) => item.content)
        .join('');
      delete metaMap.otherMetaCollectionGroup['$self'];
    }
    metaMap.useComponentPath.forEach((value, key) => {
      value.libraryPath = Array.from(new Set(value.libraryPath));
      value.localPath = Array.from(new Set(value.localPath));
    });
    const styleMap = new Map<string, string[]>();
    metaMap.style.forEach((value, key) => {
      const entryPattern = this.getComponentPagePattern(key);
      styleMap.set(entryPattern.outputFiles.style, value);
    });
    const contentMap = new Map<string, string>();
    metaMap.outputContent.forEach((value, key) => {
      const entryPattern = this.getComponentPagePattern(key);
      contentMap.set(entryPattern.outputFiles.content, value);
    });
 
    metaMap.style = styleMap;
    const config = new Map<
      string,
      {
        component: true | undefined;
        usingComponents: { selector: string; path: string }[];
        existConfig: string;
      }
    >();
    metaMap.useComponentPath.forEach((value, key) => {
      const entryPattern = this.getComponentPagePattern(key);
      const list = [
        ...value.libraryPath.map((item) => {
          item.path = resolve(
            normalize('/'),
            join(normalize(LIBRARY_OUTPUT_ROOTDIR), item.path)
          );
          return item;
        }),
      ];
      list.push(
        ...value.localPath.map((item) => ({
          selector: item.selector,
          path: resolve(
            normalize('/'),
            normalize(this.getComponentPagePattern(item.path).outputFiles.path)
          ),
          className: item.className,
        }))
      );
      config.set(entryPattern.outputFiles.config, {
        component: entryPattern.type === 'component' || undefined,
        usingComponents: list,
        existConfig: entryPattern.inputFiles.config,
      });
    });
 
    for (const key in metaMap.otherMetaCollectionGroup) {
      Eif (
        Object.prototype.hasOwnProperty.call(
          metaMap.otherMetaCollectionGroup,
          key
        )
      ) {
        const element = metaMap.otherMetaCollectionGroup[key];
        element.libraryPath.forEach((item) => {
          item.path = resolve(
            normalize('/'),
            join(normalize(LIBRARY_OUTPUT_ROOTDIR), item.path)
          );
        });
        element.localPath.forEach((item) => {
          item.path = resolve(
            normalize('/'),
            normalize(this.getComponentPagePattern(item.path).outputFiles.path)
          );
        });
      }
    }
    return {
      style: styleMap,
      outputContent: contentMap,
      config: config,
      otherMetaCollectionGroup: metaMap.otherMetaCollectionGroup,
      selfTemplate,
    };
  }
 
  private initHost(config: ParsedConfiguration) {
    const host = ts.createIncrementalCompilerHost(config.options, this.system);
    this.augmentResolveModuleNames(host, config.options);
    this.addCleanDependency(host);
    return host;
  }
  private async initTscProgram() {
    const { readConfiguration, NgtscProgram } = await angularCompilerCliPromise;
    const config = readConfiguration(this.tsConfig, undefined);
    const host = this.initHost(config);
    this.ngTscProgram = new NgtscProgram(
      config.rootNames,
      config.options,
      host
    );
    this.tsProgram = this.ngTscProgram.getTsProgram();
    this.typeChecker = this.tsProgram.getTypeChecker();
    this.augmentProgramWithVersioning(this.tsProgram);
    if (this.compiler.watchMode) {
      this.builder = this.oldBuilder =
        ts.createEmitAndSemanticDiagnosticsBuilderProgram(
          this.tsProgram,
          host,
          this.oldBuilder
        );
    } else {
      this.builder = ts.createAbstractBuilder(this.tsProgram, host);
    }
    this.ngCompiler = this.ngTscProgram.compiler;
  }
  /** 获得组件/页面的入口 */
  private getComponentPagePattern(fileName: string) {
    const findList = [fileName];
    let maybeEntryPath: PagePattern | undefined;
 
    while (findList.length) {
      const module = findList.shift();
      const moduleList = this.dependencyUseModule.get(path.normalize(module!));
      if (moduleList && moduleList.length) {
        findList.push(...moduleList);
      } else {
        maybeEntryPath = this.pagePatternList.find(
          (item) => path.normalize(item.src) === path.normalize(module!)
        );
        Eif (maybeEntryPath) {
          const sourceFile = this.tsProgram.getSourceFile(maybeEntryPath.src)!;
          const selector = createCssSelectorForTs(sourceFile);
          let importComponent: ts.Expression;
          if (maybeEntryPath.type === 'page') {
            const node = selector.queryOne(
              `CallExpression[expression=pageStartup]`
            ) as ts.CallExpression;
            importComponent = node.arguments[1];
          } else {
            const node = selector.queryOne(
              `CallExpression[expression=componentRegistry]`
            ) as ts.CallExpression;
            importComponent = node.arguments[0];
          }
          const symbol = this.typeChecker.getSymbolAtLocation(importComponent);
          const node = symbol?.getDeclarations()?.[0];
          const importDeclaration = node?.parent.parent
            .parent as ts.ImportDeclaration;
          const relativeImportComponentPath = importDeclaration.moduleSpecifier
            .getText()
            .slice(1, -1);
 
          const importComponentPath =
            path.resolve(
              path.dirname(maybeEntryPath.src),
              path.normalize(relativeImportComponentPath)
            ) + '.ts';
          Eif (importComponentPath === path.normalize(fileName)) {
            break;
          }
 
          maybeEntryPath = undefined;
        }
      }
    }
    Iif (!maybeEntryPath) {
      throw new Error(`没有找到组件[${fileName}]对应的入口点`);
    }
    return maybeEntryPath;
  }
 
  private addCleanDependency(host: ts.CompilerHost) {
    const oldReadFile = host.readFile;
    const _this = this;
    host.readFile = function (fileName) {
      if (fileName.includes('node_modules')) {
        _this.cleanDependencyFileCacheSet.add(externalizePath(fileName));
      }
      return oldReadFile.call(this, fileName);
    };
  }
  private saveModuleDependency(
    filePath: string,
    moduleName: string,
    module: ts.ResolvedModule
  ) {
    Iif (!module) {
      throw new Error(`模块未被解析,文件名${filePath},模块名${moduleName}`);
    }
    const useList =
      this.dependencyUseModule.get(path.normalize(module.resolvedFileName)) ||
      [];
    useList.push(filePath);
    this.dependencyUseModule.set(
      path.normalize(module.resolvedFileName),
      useList
    );
  }
  private augmentResolveModuleNames(
    host: ts.CompilerHost,
    compilerOptions: CompilerOptions
  ) {
    const moduleResolutionCache = ts.createModuleResolutionCache(
      host.getCurrentDirectory(),
      host.getCanonicalFileName.bind(host),
      compilerOptions
    );
    const oldResolveModuleNames = host.resolveModuleNames;
    Iif (oldResolveModuleNames) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      host.resolveModuleNames = (moduleNames: string[], ...args: any[]) => {
        return moduleNames.map((name) => {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const result = (oldResolveModuleNames! as any).call(
            host,
            [name],
            ...args
          );
          this.saveModuleDependency(args[0], name, result);
 
          return result;
        });
      };
    } else {
      host.resolveModuleNames = (
        moduleNames: string[],
        containingFile: string,
        _reusedNames: string[] | undefined,
        redirectedReference: ts.ResolvedProjectReference | undefined,
        options: ts.CompilerOptions
      ) => {
        return moduleNames.map((name) => {
          const result = ts.resolveModuleName(
            name,
            containingFile,
            options,
            host,
            moduleResolutionCache,
            redirectedReference
          ).resolvedModule;
          if (!containingFile.includes('node_modules')) {
            this.saveModuleDependency(containingFile, name, result!);
          }
          return result;
        });
      };
    }
  }
 
  async analyzeAsync() {
    await this.initTscProgram();
    await this.ngCompiler.analyzeAsync();
  }
  getBuilder() {
    return this.builder;
  }
  cleanDependencyFileCache() {
    this.cleanDependencyFileCacheSet.forEach((filePath) => {
      try {
        this.compiler.inputFileSystem.purge!(filePath);
      } catch (error) {}
    });
  }
  private augmentProgramWithVersioning(program: ts.Program): void {
    const baseGetSourceFiles = program.getSourceFiles;
    program.getSourceFiles = function (...parameters) {
      const files: readonly (ts.SourceFile & { version?: string })[] =
        baseGetSourceFiles(...parameters);
 
      for (const file of files) {
        if (file.version === undefined) {
          file.version = createHash('sha256').update(file.text).digest('hex');
        }
      }
 
      return files;
    };
  }
}