1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import fs from 'fs'; 17import path from 'path'; 18import * as ts from 'typescript'; 19import * as crypto from 'crypto'; 20const fse = require('fs-extra'); 21 22import { 23 projectConfig, 24 systemModules, 25 globalProgram, 26 sdkConfigs, 27 sdkConfigPrefix, 28 partialUpdateConfig, 29 resetProjectConfig, 30 resetGlobalProgram 31} from '../main'; 32import { 33 preprocessExtend, 34 preprocessNewExtend 35} from './validate_ui_syntax'; 36import { 37 INNER_COMPONENT_MEMBER_DECORATORS, 38 COMPONENT_DECORATORS_PARAMS, 39 COMPONENT_BUILD_FUNCTION, 40 STYLE_ADD_DOUBLE_DOLLAR, 41 $$, 42 PROPERTIES_ADD_DOUBLE_DOLLAR, 43 DOLLAR_BLOCK_INTERFACE, 44 COMPONENT_EXTEND_DECORATOR, 45 COMPONENT_BUILDER_DECORATOR, 46 ESMODULE, 47 EXTNAME_D_ETS, 48 EXTNAME_JS, 49 FOREACH_LAZYFOREACH, 50 COMPONENT_IF, 51 TS_WATCH_END_MSG, 52 TS_BUILD_INFO_SUFFIX, 53 HOT_RELOAD_BUILD_INFO_SUFFIX, 54 WATCH_COMPILER_BUILD_INFO_SUFFIX, 55 COMPONENT_STYLES_DECORATOR 56} from './pre_define'; 57import { 58 INNER_COMPONENT_NAMES, 59 JS_BIND_COMPONENTS, 60 BUILDIN_STYLE_NAMES 61} from './component_map'; 62import { logger } from './compile_info'; 63import { 64 hasDecorator, 65 isString, 66 generateSourceFilesInHar, 67 startTimeStatisticsLocation, 68 stopTimeStatisticsLocation, 69 resolveModuleNamesTime, 70 CompilationTimeStatistics, 71 storedFileInfo, 72 toUnixPath, 73 isWindows, 74 isMac, 75 tryToLowerCasePath, 76 getRollupCache, 77 setRollupCache 78} from './utils'; 79import { 80 isExtendFunction, 81 isOriginalExtend 82} from './process_ui_syntax'; 83import { visualTransform } from './process_visual'; 84import { tsWatchEmitter } from './fast_build/ets_ui/rollup-plugin-ets-checker'; 85import { 86 doArkTSLinter, 87 ArkTSLinterMode, 88 ArkTSVersion, 89} from './do_arkTS_linter'; 90import { 91 getJsDocNodeCheckConfig, 92 isCardFile, 93 getRealModulePath, 94 getJsDocNodeConditionCheckResult 95} from './fast_build/system_api/api_check_utils'; 96 97export interface LanguageServiceCache { 98 service?: ts.LanguageService; 99 pkgJsonFileHash?: string; 100 targetESVersion?: ts.ScriptTarget; 101 preTsImportSendable?: boolean; 102} 103 104export const SOURCE_FILES: Map<string, ts.SourceFile> = new Map(); 105export let localPackageSet: Set<string> = new Set(); 106 107export function readDeaclareFiles(): string[] { 108 const declarationsFileNames: string[] = []; 109 fs.readdirSync(path.resolve(__dirname, '../declarations')) 110 .forEach((fileName: string) => { 111 if (/\.d\.ts$/.test(fileName)) { 112 declarationsFileNames.push(path.resolve(__dirname, '../declarations', fileName)); 113 } 114 }); 115 return declarationsFileNames; 116} 117 118const buildInfoWriteFile: ts.WriteFileCallback = (fileName: string, data: string) => { 119 if (fileName.includes(TS_BUILD_INFO_SUFFIX)) { 120 const fd: number = fs.openSync(fileName, 'w'); 121 fs.writeSync(fd, data, undefined, 'utf8'); 122 fs.closeSync(fd); 123 } 124}; 125 126// The collection records the file name and the corresponding version, where the version is the hash value of the text in last compilation. 127const filesBuildInfo: Map<string, string> = new Map(); 128 129export const compilerOptions: ts.CompilerOptions = ts.readConfigFile( 130 path.resolve(__dirname, '../tsconfig.json'), ts.sys.readFile).config.compilerOptions; 131function setCompilerOptions(resolveModulePaths: string[]): void { 132 const allPath: Array<string> = ['*']; 133 const basePath: string = path.resolve(projectConfig.projectPath); 134 if (process.env.compileTool === 'rollup' && resolveModulePaths && resolveModulePaths.length) { 135 resolveModulePaths.forEach((item: string) => { 136 if (!(/oh_modules$/.test(item) || /node_modules$/.test(item))) { 137 allPath.push(path.join(path.relative(basePath, item), '*')); 138 } 139 }); 140 } else { 141 if (!projectConfig.aceModuleJsonPath) { 142 allPath.push('../../../../../*'); 143 allPath.push('../../*'); 144 } else { 145 allPath.push('../../../../*'); 146 allPath.push('../*'); 147 } 148 } 149 const suffix: string = projectConfig.hotReload ? HOT_RELOAD_BUILD_INFO_SUFFIX : TS_BUILD_INFO_SUFFIX; 150 const buildInfoPath: string = path.resolve(projectConfig.cachePath, '..', suffix); 151 checkArkTSVersion(); 152 Object.assign(compilerOptions, { 153 'allowJs': getArkTSLinterMode() !== ArkTSLinterMode.NOT_USE ? true : false, 154 'checkJs': getArkTSLinterMode() !== ArkTSLinterMode.NOT_USE ? false : undefined, 155 'emitNodeModulesFiles': true, 156 'importsNotUsedAsValues': ts.ImportsNotUsedAsValues.Preserve, 157 'module': ts.ModuleKind.CommonJS, 158 'moduleResolution': ts.ModuleResolutionKind.NodeJs, 159 'noEmit': true, 160 'target': convertConfigTarget(getTargetESVersion()), 161 'baseUrl': basePath, 162 'paths': { 163 '*': allPath 164 }, 165 'lib': convertConfigLib(getTargetESVersionLib()), 166 'types': projectConfig.compilerTypes, 167 'etsLoaderPath': projectConfig.etsLoaderPath, 168 'needDoArkTsLinter': getArkTSLinterMode() !== ArkTSLinterMode.NOT_USE, 169 'isCompatibleVersion': getArkTSLinterMode() === ArkTSLinterMode.COMPATIBLE_MODE, 170 'skipTscOhModuleCheck': partialUpdateConfig.skipTscOhModuleCheck, 171 'skipArkTSStaticBlocksCheck': partialUpdateConfig.skipArkTSStaticBlocksCheck, 172 // options incremental && tsBuildInfoFile are required for applying incremental ability of typescript 173 'incremental': true, 174 'tsBuildInfoFile': buildInfoPath, 175 'tsImportSendableEnable': tsImportSendable, 176 'skipPathsInKeyForCompilationSettings': reuseLanguageServiceForDepChange, 177 'compatibleSdkVersionStage': projectConfig.compatibleSdkVersionStage, 178 'compatibleSdkVersion': projectConfig.compatibleSdkVersion 179 }); 180 if (projectConfig.compileMode === ESMODULE) { 181 Object.assign(compilerOptions, { 182 'importsNotUsedAsValues': ts.ImportsNotUsedAsValues.Remove, 183 'module': ts.ModuleKind.ES2020 184 }); 185 } 186 if (projectConfig.packageDir === 'oh_modules') { 187 Object.assign(compilerOptions, {'packageManagerType': 'ohpm'}); 188 } 189 readTsBuildInfoFileInCrementalMode(buildInfoPath, projectConfig); 190} 191 192function checkArkTSVersion(): void { 193 const etsCheckerLogger = fastBuildLogger || logger; 194 if (getArkTSVersion() === ArkTSVersion.ArkTS_1_0 && tsImportSendable) { 195 const logMessage: string = 'ArkTS: ArkTSVersion1.0 does not support tsImportSendable in any condition'; 196 etsCheckerLogger.error('\u001b[31m' + logMessage); 197 tsImportSendable = false; 198 } 199} 200 201// Change target to enum's value,e.g: "es2021" => ts.ScriptTarget.ES2021 202function convertConfigTarget(target: number | string): number | string { 203 if ((typeof target === 'number') && (target in ts.ScriptTarget)) { 204 return target; 205 } 206 return ts.convertCompilerOptionsFromJson({ 'target': target }, '').options.target; 207} 208 209// Change lib to libMap's value,e.g: "es2021" => "lib.es2021.d.ts" 210function convertConfigLib(libs: string[]): string[] { 211 let converted: boolean = true; 212 let libMapValues: string[] = Array.from(ts.libMap.values()); 213 for (let i = 0; i < libs.length; i++) { 214 if (!libMapValues.includes(libs[i])) { 215 converted = false; 216 break; 217 } 218 } 219 if (converted) { 220 return libs; 221 } 222 return ts.convertCompilerOptionsFromJson({ 'lib': libs }, '').options.lib; 223} 224 225/** 226 * Read the source code information in the project of the last compilation process, and then use it 227 * to determine whether the file has been modified during this compilation process. 228 */ 229function readTsBuildInfoFileInCrementalMode(buildInfoPath: string, projectConfig: Object): void { 230 if (!fs.existsSync(buildInfoPath) || !(projectConfig.compileHar || projectConfig.compileShared)) { 231 return; 232 } 233 234 type FileInfoType = { 235 version: string; 236 affectsGlobalScope: boolean; 237 }; 238 type ProgramType = { 239 fileNames: string[]; 240 fileInfos: (FileInfoType | string)[]; 241 }; 242 let buildInfoProgram: ProgramType; 243 try { 244 const content: {program: ProgramType} = JSON.parse(fs.readFileSync(buildInfoPath, 'utf-8')); 245 buildInfoProgram = content.program; 246 if (!buildInfoProgram || !buildInfoProgram.fileNames || !buildInfoProgram.fileInfos) { 247 throw new Error('.tsbuildinfo content is invalid'); 248 } 249 } catch (err) { 250 fastBuildLogger.warn('\u001b[33m' + 'ArkTS: Failed to parse .tsbuildinfo file. Error message: ' + err.message.toString()); 251 return; 252 } 253 const buildInfoDirectory: string = path.dirname(buildInfoPath); 254 /** 255 * For the windos and mac platform, the file path in tsbuildinfo is in lowercase, while buildInfoDirectory is the original path (including uppercase). 256 * Therefore, the path needs to be converted to lowercase, and then perform path comparison. 257 */ 258 const isMacOrWin = isWindows() || isMac(); 259 const fileNames: string[] = buildInfoProgram.fileNames; 260 const fileInfos: (FileInfoType | string)[] = buildInfoProgram.fileInfos; 261 fileInfos.forEach((fileInfo, index) => { 262 const version: string = typeof fileInfo === 'string' ? fileInfo : fileInfo.version; 263 const absPath: string = path.resolve(buildInfoDirectory, fileNames[index]); 264 filesBuildInfo.set(isMacOrWin ? tryToLowerCasePath(absPath) : absPath, version); 265 }); 266} 267 268interface extendInfo { 269 start: number, 270 end: number, 271 compName: string 272} 273 274function createHash(str: string): string { 275 const hash = crypto.createHash('sha256'); 276 hash.update(str); 277 return hash.digest('hex'); 278} 279 280export const fileHashScriptVersion: (fileName: string) => string = (fileName: string) => { 281 if (!fs.existsSync(fileName)) { 282 return '0'; 283 } 284 285 let fileContent: string = fs.readFileSync(fileName).toString(); 286 let cacheInfo: CacheFileName = cache[path.resolve(fileName)]; 287 288 // Error code corresponding to message `Cannot find module xx or its corresponding type declarations` 289 const errorCodeRequireRecheck: number = 2307; 290 291 if (cacheInfo && cacheInfo.error === true && cacheInfo.errorCodes && cacheInfo.errorCodes.includes(errorCodeRequireRecheck)) { 292 // If this file had errors that require recheck in the last compilation, 293 // mark the file as modified by modifying its hash value, thereby triggering tsc to recheck. 294 fileContent += Date.now().toString(); 295 } 296 return createHash(fileContent); 297}; 298 299// Reuse the last language service when dependency in oh-package.json5 changes to enhance performance in incremental building. 300// Setting this to false will create a new language service on dependency changes, like a full rebuild. 301const reuseLanguageServiceForDepChange: boolean = true; 302// When dependency changes and reusing the last language service, enable this flag to recheck code dependent on those dependencies. 303export let needReCheckForChangedDepUsers: boolean = false; 304 305export function createLanguageService(rootFileNames: string[], resolveModulePaths: string[], 306 compilationTime: CompilationTimeStatistics = null, rollupShareObject?: any): ts.LanguageService { 307 setCompilerOptions(resolveModulePaths); 308 const servicesHost: ts.LanguageServiceHost = { 309 getScriptFileNames: () => [...rootFileNames, ...readDeaclareFiles()], 310 getScriptVersion: fileHashScriptVersion, 311 getScriptSnapshot: function(fileName) { 312 if (!fs.existsSync(fileName)) { 313 return undefined; 314 } 315 if (/(?<!\.d)\.(ets|ts)$/.test(fileName)) { 316 startTimeStatisticsLocation(compilationTime ? compilationTime.scriptSnapshotTime : undefined); 317 appComponentCollection.set(path.join(fileName), new Set()); 318 let content: string = processContent(fs.readFileSync(fileName).toString(), fileName); 319 const extendFunctionInfo: extendInfo[] = []; 320 content = instanceInsteadThis(content, fileName, extendFunctionInfo, this.uiProps); 321 stopTimeStatisticsLocation(compilationTime ? compilationTime.scriptSnapshotTime : undefined); 322 return ts.ScriptSnapshot.fromString(content); 323 } 324 return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString()); 325 }, 326 getCurrentDirectory: () => process.cwd(), 327 getCompilationSettings: () => compilerOptions, 328 getDefaultLibFileName: options => ts.getDefaultLibFilePath(options), 329 fileExists: ts.sys.fileExists, 330 readFile: ts.sys.readFile, 331 readDirectory: ts.sys.readDirectory, 332 resolveModuleNames: resolveModuleNames, 333 resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, 334 directoryExists: ts.sys.directoryExists, 335 getDirectories: ts.sys.getDirectories, 336 getJsDocNodeCheckedConfig: (fileCheckedInfo: ts.FileCheckModuleInfo, sourceFileName: string) => { 337 return getJsDocNodeCheckConfig(fileCheckedInfo.currentFileName, sourceFileName); 338 }, 339 getFileCheckedModuleInfo: (containFilePath: string) => { 340 return { 341 fileNeedCheck: true, 342 checkPayload: undefined, 343 currentFileName: containFilePath 344 }; 345 }, 346 getJsDocNodeConditionCheckedResult: (jsDocFileCheckedInfo: ts.FileCheckModuleInfo, jsDocs: ts.JsDocTagInfo[]) => { 347 return getJsDocNodeConditionCheckResult(jsDocFileCheckedInfo, jsDocs); 348 }, 349 uiProps: [], 350 clearProps: function() { 351 dollarCollection.clear(); 352 extendCollection.clear(); 353 this.uiProps.length = 0; 354 }, 355 // TSC will re-do resolution if this callback return true. 356 hasInvalidatedResolutions: (filePath: string): boolean => { 357 return reuseLanguageServiceForDepChange && needReCheckForChangedDepUsers; 358 } 359 }; 360 361 if (process.env.watchMode === 'true') { 362 return ts.createLanguageService(servicesHost, ts.createDocumentRegistry()); 363 } 364 365 return getOrCreateLanguageService(servicesHost, rootFileNames, rollupShareObject); 366} 367 368export let targetESVersionChanged: boolean = false; 369 370function getOrCreateLanguageService(servicesHost: ts.LanguageServiceHost, rootFileNames: string[], 371 rollupShareObject?: any): ts.LanguageService { 372 let cacheKey: string = 'service'; 373 let cache: LanguageServiceCache | undefined = getRollupCache(rollupShareObject, projectConfig, cacheKey); 374 375 let service: ts.LanguageService | undefined = cache?.service; 376 const currentHash: string | undefined = rollupShareObject?.projectConfig?.pkgJsonFileHash; 377 const currentTargetESVersion: ts.ScriptTarget = compilerOptions.target; 378 const lastHash: string | undefined = cache?.pkgJsonFileHash; 379 const lastTargetESVersion: ts.ScriptTarget | undefined = cache?.targetESVersion; 380 const hashDiffers: boolean | undefined = currentHash && lastHash && currentHash !== lastHash; 381 const shouldRebuildForDepDiffers: boolean | undefined = reuseLanguageServiceForDepChange ? 382 (hashDiffers && !rollupShareObject?.depInfo?.enableIncre) : hashDiffers; 383 const targetESVersionDiffers: boolean | undefined = lastTargetESVersion && currentTargetESVersion && lastTargetESVersion !== currentTargetESVersion; 384 const tsImportSendableDiff: boolean = (cache?.preTsImportSendable === undefined && !tsImportSendable) ? 385 false : 386 cache?.preTsImportSendable !== tsImportSendable; 387 const shouldRebuild: boolean | undefined = shouldRebuildForDepDiffers || targetESVersionDiffers || tsImportSendableDiff; 388 if (reuseLanguageServiceForDepChange && hashDiffers && rollupShareObject?.depInfo?.enableIncre) { 389 needReCheckForChangedDepUsers = true; 390 } 391 392 if (!service || shouldRebuild) { 393 rebuiuldProgram(targetESVersionDiffers, tsImportSendableDiff); 394 service = ts.createLanguageService(servicesHost, ts.createDocumentRegistry()); 395 } else { 396 // Found language service from cache, update root files 397 const updateRootFileNames = [...rootFileNames, ...readDeaclareFiles()]; 398 service.updateRootFiles(updateRootFileNames); 399 } 400 401 const newCache: LanguageServiceCache = { 402 service: service, 403 pkgJsonFileHash: currentHash, 404 targetESVersion: currentTargetESVersion, 405 preTsImportSendable: tsImportSendable 406 }; 407 setRollupCache(rollupShareObject, projectConfig, cacheKey, newCache); 408 return service; 409} 410 411function rebuiuldProgram(targetESVersionDiffers: boolean | undefined, tsImportSendableDiff: boolean): void { 412 if (targetESVersionDiffers) { 413 // If the targetESVersion is changed, we need to delete the build info cahce files 414 deleteBuildInfoCache(compilerOptions.tsBuildInfoFile); 415 targetESVersionChanged = true; 416 } else if (tsImportSendableDiff) { 417 // When tsImportSendable is changed, we need to delete the build info cahce files 418 deleteBuildInfoCache(compilerOptions.tsBuildInfoFile); 419 } 420} 421 422function deleteBuildInfoCache(tsBuildInfoFilePath: string): void { 423 // The file name of tsBuildInfoLinterFile is '.tsbuildinfo.linter', so we need to add '.linter' after tsBuildInfoFilePath 424 const tsBuildInfoLinterFilePath: string = tsBuildInfoFilePath + '.linter'; 425 deleteFile(tsBuildInfoFilePath); 426 deleteFile(tsBuildInfoLinterFilePath); 427} 428 429function deleteFile(filePath: string): void { 430 if (fs.existsSync(filePath)) { 431 fs.unlinkSync(filePath); 432 } 433} 434 435interface CacheFileName { 436 mtimeMs: number, 437 children: string[], 438 parent: string[], 439 error: boolean, 440 errorCodes?: number[] 441} 442interface NeedUpdateFlag { 443 flag: boolean; 444} 445interface CheckerResult { 446 count: number 447} 448 449interface WarnCheckerResult { 450 count: number 451} 452 453interface WholeCache { 454 runtimeOS: string, 455 sdkInfo: string, 456 fileList: Cache 457} 458type Cache = Record<string, CacheFileName>; 459export let cache: Cache = {}; 460export const hotReloadSupportFiles: Set<string> = new Set(); 461export const shouldResolvedFiles: Set<string> = new Set(); 462export const appComponentCollection: Map<string, Set<string>> = new Map(); 463const allResolvedModules: Set<string> = new Set(); 464// all files of tsc and rollup for obfuscation scanning. 465export const allSourceFilePaths: Set<string> = new Set(); 466// Used to collect file paths that have not been converted toUnixPath. 467export const allModuleIds: Set<string> = new Set(); 468export let props: string[] = []; 469 470export let fastBuildLogger = null; 471 472export const checkerResult: CheckerResult = { count: 0 }; 473export const warnCheckerResult: WarnCheckerResult = { count: 0 }; 474export let languageService: ts.LanguageService = null; 475let tsImportSendable: boolean = false; 476export function serviceChecker(rootFileNames: string[], newLogger: Object = null, resolveModulePaths: string[] = null, 477 compilationTime: CompilationTimeStatistics = null, rollupShareObject?: Object): void { 478 fastBuildLogger = newLogger; 479 let cacheFile: string = null; 480 tsImportSendable = rollupShareObject?.projectConfig.tsImportSendable; 481 if (projectConfig.xtsMode || process.env.watchMode === 'true') { 482 if (projectConfig.hotReload) { 483 rootFileNames.forEach(fileName => { 484 hotReloadSupportFiles.add(fileName); 485 }); 486 } 487 languageService = createLanguageService(rootFileNames, resolveModulePaths, compilationTime); 488 props = languageService.getProps(); 489 } else { 490 cacheFile = path.resolve(projectConfig.cachePath, '../.ts_checker_cache'); 491 const [isJsonObject, cacheJsonObject]: [boolean, WholeCache | undefined] = isJsonString(cacheFile); 492 const wholeCache: WholeCache = isJsonObject ? cacheJsonObject : { 'runtimeOS': projectConfig.runtimeOS, 'sdkInfo': projectConfig.sdkInfo, 'fileList': {} }; 493 if (wholeCache.runtimeOS === projectConfig.runtimeOS && wholeCache.sdkInfo === projectConfig.sdkInfo) { 494 cache = wholeCache.fileList; 495 } else { 496 cache = {}; 497 } 498 languageService = createLanguageService(rootFileNames, resolveModulePaths, compilationTime, rollupShareObject); 499 } 500 501 const timePrinterInstance = ts.ArkTSLinterTimePrinter.getInstance(); 502 timePrinterInstance.setArkTSTimePrintSwitch(false); 503 timePrinterInstance.appendTime(ts.TimePhase.START); 504 startTimeStatisticsLocation(compilationTime ? compilationTime.createProgramTime : undefined); 505 506 globalProgram.builderProgram = languageService.getBuilderProgram(/*withLinterProgram*/ true); 507 globalProgram.program = globalProgram.builderProgram.getProgram(); 508 props = languageService.getProps(); 509 timePrinterInstance.appendTime(ts.TimePhase.GET_PROGRAM); 510 stopTimeStatisticsLocation(compilationTime ? compilationTime.createProgramTime : undefined); 511 512 collectAllFiles(globalProgram.program); 513 collectFileToIgnoreDiagnostics(rootFileNames); 514 startTimeStatisticsLocation(compilationTime ? compilationTime.runArkTSLinterTime : undefined); 515 runArkTSLinter(); 516 stopTimeStatisticsLocation(compilationTime ? compilationTime.runArkTSLinterTime : undefined); 517 518 if (process.env.watchMode !== 'true') { 519 processBuildHap(cacheFile, rootFileNames, compilationTime, rollupShareObject); 520 } 521 522 if (globalProgram.program && 523 (process.env.watchMode !== 'true' && !projectConfig.isPreview && 524 !projectConfig.hotReload && !projectConfig.coldReload)) { 525 globalProgram.program.releaseTypeChecker(); 526 const allowGC: boolean = global && global.gc && typeof global.gc === 'function'; 527 if (allowGC) { 528 global.gc(); 529 } 530 } 531} 532// collect the compiled files of tsc and rollup for obfuscation scanning. 533export function collectAllFiles(program?: ts.Program, rollupFileList?: IterableIterator<string>, 534 rollupObject?: Object): void { 535 if (program) { 536 collectTscFiles(program); 537 return; 538 } 539 mergeRollUpFiles(rollupFileList, rollupObject); 540} 541 542function isJsonString(cacheFile: string): [boolean, WholeCache | undefined] { 543 if (fs.existsSync(cacheFile)) { 544 try { 545 return [true, JSON.parse(fs.readFileSync(cacheFile).toString())]; 546 } catch(e) { 547 return [false, undefined]; 548 } 549 } else { 550 return [false, undefined]; 551 } 552} 553 554export function collectTscFiles(program: ts.Program): void { 555 const programAllFiles: readonly ts.SourceFile[] = program.getSourceFiles(); 556 let projectRootPath: string = projectConfig.projectRootPath; 557 if (!projectRootPath) { 558 return; 559 } 560 projectRootPath = toUnixPath(projectRootPath); 561 const isMacOrWin = isWindows() || isMac(); 562 programAllFiles.forEach(sourceFile => { 563 const fileName = toUnixPath(sourceFile.fileName); 564 if (!fileName.startsWith(projectRootPath)) { 565 return; 566 } 567 allSourceFilePaths.add(fileName); 568 allModuleIds.add(sourceFile.fileName); 569 // For the windos and mac platform, the file path in filesBuildInfo is in lowercase, 570 // while fileName of sourceFile is the original path (including uppercase). 571 if (filesBuildInfo.size > 0 && 572 Reflect.get(sourceFile, 'version') !== filesBuildInfo.get(isMacOrWin ? tryToLowerCasePath(fileName) : fileName)) { 573 allResolvedModules.add(fileName); 574 } 575 }); 576} 577 578export function mergeRollUpFiles(rollupFileList: IterableIterator<string>, rollupObject: Object) { 579 for (const moduleId of rollupFileList) { 580 if (fs.existsSync(moduleId)) { 581 allSourceFilePaths.add(toUnixPath(moduleId)); 582 allModuleIds.add(moduleId); 583 addLocalPackageSet(moduleId, rollupObject); 584 } 585 } 586} 587 588// collect the modulename or pkgname of all local modules. 589export function addLocalPackageSet(moduleId: string, rollupObject: Object): void { 590 const moduleInfo: Object = rollupObject.getModuleInfo(moduleId); 591 const metaInfo: Object = moduleInfo.meta; 592 if (metaInfo.isLocalDependency) { 593 if (projectConfig.useNormalizedOHMUrl && metaInfo.pkgName) { 594 localPackageSet.add(metaInfo.pkgName); 595 } 596 if (!projectConfig.useNormalizedOHMUrl && metaInfo.moduleName) { 597 localPackageSet.add(metaInfo.moduleName); 598 } 599 } 600} 601 602export function emitBuildInfo(): void { 603 globalProgram.builderProgram.emitBuildInfo(buildInfoWriteFile); 604} 605 606function processBuildHap(cacheFile: string, rootFileNames: string[], compilationTime: CompilationTimeStatistics, 607 rollupShareObject: Object): void { 608 startTimeStatisticsLocation(compilationTime ? compilationTime.diagnosticTime : undefined); 609 const allDiagnostics: ts.Diagnostic[] = globalProgram.builderProgram 610 .getSyntacticDiagnostics() 611 .concat(globalProgram.builderProgram.getSemanticDiagnostics()); 612 stopTimeStatisticsLocation(compilationTime ? compilationTime.diagnosticTime : undefined); 613 emitBuildInfo(); 614 allDiagnostics.forEach((diagnostic: ts.Diagnostic) => { 615 printDiagnostic(diagnostic); 616 }); 617 if (!projectConfig.xtsMode) { 618 fse.ensureDirSync(projectConfig.cachePath); 619 fs.writeFileSync(cacheFile, JSON.stringify({ 620 'runtimeOS': projectConfig.runtimeOS, 621 'sdkInfo': projectConfig.sdkInfo, 622 'fileList': cache 623 }, null, 2)); 624 } 625 if (projectConfig.compileHar || projectConfig.compileShared) { 626 let emit: string | undefined = undefined; 627 let writeFile = (fileName: string, text: string, writeByteOrderMark: boolean): void => { 628 emit = text; 629 }; 630 [...allResolvedModules, ...rootFileNames].forEach(moduleFile => { 631 if (!(moduleFile.match(new RegExp(projectConfig.packageDir)) && projectConfig.compileHar)) { 632 try { 633 if ((/\.d\.e?ts$/).test(moduleFile)) { 634 generateSourceFilesInHar(moduleFile, fs.readFileSync(moduleFile, 'utf-8'), path.extname(moduleFile), 635 projectConfig, projectConfig.modulePathMap); 636 } else if ((/\.e?ts$/).test(moduleFile)) { 637 emit = undefined; 638 let sourcefile = globalProgram.program.getSourceFile(moduleFile); 639 if (sourcefile) { 640 globalProgram.program.emit(sourcefile, writeFile, undefined, true, undefined, true); 641 } 642 if (emit) { 643 generateSourceFilesInHar(moduleFile, emit, '.d' + path.extname(moduleFile), projectConfig, projectConfig.modulePathMap); 644 } 645 } 646 } catch (err) { } 647 } 648 }); 649 printDeclarationDiagnostics(); 650 } 651} 652 653function printDeclarationDiagnostics(): void { 654 globalProgram.builderProgram.getDeclarationDiagnostics().forEach((diagnostic: ts.Diagnostic) => { 655 printDiagnostic(diagnostic); 656 }); 657} 658 659function containFormError(message: string): boolean { 660 if (/can't support form application./.test(message)) { 661 return true; 662 } 663 return false; 664} 665 666let fileToIgnoreDiagnostics: Set<string> | undefined = undefined; 667 668function collectFileToThrowDiagnostics(file: string, fileToThrowDiagnostics: Set<string>): void { 669 const normalizedFilePath: string = path.resolve(file); 670 const unixFilePath: string = toUnixPath(file); 671 if (fileToThrowDiagnostics.has(unixFilePath)) { 672 return; 673 } 674 675 fileToThrowDiagnostics.add(unixFilePath); 676 // Although the cache object filters JavaScript files when collecting dependency relationships, we still include the 677 // filtering of JavaScript files here to avoid potential omissions. 678 if ((/\.(c|m)?js$/).test(file) || 679 !cache[normalizedFilePath] || cache[normalizedFilePath].children.length === 0) { 680 return; 681 } 682 cache[normalizedFilePath].children.forEach(file => { 683 collectFileToThrowDiagnostics(file, fileToThrowDiagnostics); 684 }); 685} 686 687export function collectFileToIgnoreDiagnostics(rootFileNames: string[]): void { 688 if (getArkTSLinterMode() === ArkTSLinterMode.NOT_USE) { 689 return; 690 } 691 692 // In watch mode, the `beforeBuild` phase will clear the parent and children fields in the cache. For files that have 693 // not been modified, the information needs to be restored using the `resolvedModuleNames` variable. 694 if (process.env.watchMode === 'true') { 695 for (let [file, resolvedModules] of resolvedModulesCache) { 696 createOrUpdateCache(resolvedModules, file); 697 } 698 } 699 700 // With arkts linter enabled, `allowJs` option is set to true, resulting JavaScript files themselves and 701 // JavaScript-referenced files are included in the tsc program and checking process, 702 // potentially introducing new errors. For instance, in scenarios where an ets file imports js file imports ts file, 703 // it’s necessary to filter out errors from ts files. 704 let fileToThrowDiagnostics: Set<string> = new Set<string>(); 705 rootFileNames.forEach(file => { 706 if (!(/\.(c|m)?js$/).test(file)) { 707 collectFileToThrowDiagnostics(file, fileToThrowDiagnostics); 708 } 709 }); 710 711 let resolvedTypeReferenceDirectivesFiles: Set<string> = new Set<string>(); 712 globalProgram.program.getResolvedTypeReferenceDirectives().forEach( 713 (elem: ts.ResolvedTypeReferenceDirective | undefined) => { 714 elem && elem.resolvedFileName && resolvedTypeReferenceDirectivesFiles.add(elem.resolvedFileName); 715 }); 716 717 fileToIgnoreDiagnostics = new Set<string>(); 718 globalProgram.program.getSourceFiles().forEach(sourceFile => { 719 // Previous projects had js libraries that were available through SDK, so need to filter js-file in SDK, 720 // like: hypium library 721 sourceFile.fileName && 722 (!isInSDK(sourceFile.fileName) || (/\.(c|m)?js$/).test(sourceFile.fileName)) && 723 !resolvedTypeReferenceDirectivesFiles.has(sourceFile.fileName) && 724 fileToIgnoreDiagnostics.add(toUnixPath(sourceFile.fileName)); 725 }); 726 727 fileToThrowDiagnostics.forEach(file => { 728 fileToIgnoreDiagnostics.delete(file); 729 }); 730} 731 732export function printDiagnostic(diagnostic: ts.Diagnostic): void { 733 if (projectConfig.ignoreWarning) { 734 return; 735 } 736 737 if (fileToIgnoreDiagnostics && diagnostic.file && diagnostic.file.fileName && 738 fileToIgnoreDiagnostics.has(toUnixPath(diagnostic.file.fileName))) { 739 return; 740 } 741 742 const message: string = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); 743 if (validateError(message)) { 744 if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { 745 updateErrorFileCache(diagnostic); 746 } 747 748 if (containFormError(message) && !isCardFile(diagnostic.file.fileName)) { 749 return; 750 } 751 752 const logPrefix: string = diagnostic.category === ts.DiagnosticCategory.Error ? 'ERROR' : 'WARN'; 753 const etsCheckerLogger = fastBuildLogger || logger; 754 let logMessage: string; 755 if (logPrefix === 'ERROR') { 756 checkerResult.count += 1; 757 } else { 758 warnCheckerResult.count += 1; 759 } 760 if (diagnostic.file) { 761 const { line, character }: ts.LineAndCharacter = 762 diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); 763 logMessage = `ArkTS:${logPrefix} File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`; 764 } else { 765 logMessage = `ArkTS:${logPrefix}: ${message}`; 766 } 767 768 if (diagnostic.category === ts.DiagnosticCategory.Error) { 769 etsCheckerLogger.error('\u001b[31m' + logMessage); 770 } else { 771 etsCheckerLogger.warn('\u001b[33m' + logMessage); 772 } 773 } 774} 775 776function validateError(message: string): boolean { 777 const propInfoReg: RegExp = /Cannot find name\s*'(\$?\$?[_a-zA-Z0-9]+)'/; 778 const stateInfoReg: RegExp = /Property\s*'(\$?[_a-zA-Z0-9]+)' does not exist on type/; 779 if (matchMessage(message, props, propInfoReg) || 780 matchMessage(message, props, stateInfoReg)) { 781 return false; 782 } 783 return true; 784} 785function matchMessage(message: string, nameArr: any, reg: RegExp): boolean { 786 if (reg.test(message)) { 787 const match: string[] = message.match(reg); 788 if (match[1] && nameArr.includes(match[1])) { 789 return true; 790 } 791 } 792 return false; 793} 794 795function updateErrorFileCache(diagnostic: ts.Diagnostic): void { 796 if (!diagnostic.file) { 797 return; 798 } 799 800 let cacheInfo: CacheFileName = cache[path.resolve(diagnostic.file.fileName)]; 801 if (cacheInfo) { 802 cacheInfo.error = true; 803 if (!cacheInfo.errorCodes) { 804 cacheInfo.errorCodes = []; 805 } 806 cacheInfo.errorCodes.includes(diagnostic.code) || cacheInfo.errorCodes.push(diagnostic.code); 807 } 808} 809 810function filterInput(rootFileNames: string[]): string[] { 811 return rootFileNames.filter((file: string) => { 812 const needUpdate: NeedUpdateFlag = { flag: false }; 813 const alreadyCheckedFiles: Set<string> = new Set(); 814 checkNeedUpdateFiles(path.resolve(file), needUpdate, alreadyCheckedFiles); 815 if (!needUpdate.flag) { 816 storedFileInfo.changeFiles.push(path.resolve(file)); 817 } 818 return needUpdate.flag; 819 }); 820} 821 822function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag, alreadyCheckedFiles: Set<string>): void { 823 if (alreadyCheckedFiles.has(file)) { 824 return; 825 } else { 826 alreadyCheckedFiles.add(file); 827 } 828 829 if (needUpdate.flag) { 830 return; 831 } 832 833 const value: CacheFileName = cache[file]; 834 const mtimeMs: number = fs.statSync(file).mtimeMs; 835 if (value) { 836 if (value.error || value.mtimeMs !== mtimeMs) { 837 needUpdate.flag = true; 838 return; 839 } 840 for (let i = 0; i < value.children.length; ++i) { 841 if (fs.existsSync(value.children[i])) { 842 checkNeedUpdateFiles(value.children[i], needUpdate, alreadyCheckedFiles); 843 } else { 844 needUpdate.flag = true; 845 } 846 } 847 } else { 848 cache[file] = { mtimeMs, children: [], parent: [], error: false }; 849 needUpdate.flag = true; 850 } 851} 852 853const fileExistsCache: Map<string, boolean> = new Map<string, boolean>(); 854const dirExistsCache: Map<string, boolean> = new Map<string, boolean>(); 855const moduleResolutionHost: ts.ModuleResolutionHost = { 856 fileExists: (fileName: string): boolean => { 857 let exists = fileExistsCache.get(fileName); 858 if (exists === undefined) { 859 exists = ts.sys.fileExists(fileName); 860 fileExistsCache.set(fileName, exists); 861 } 862 return exists; 863 }, 864 directoryExists: (directoryName: string): boolean => { 865 let exists = dirExistsCache.get(directoryName); 866 if (exists === undefined) { 867 exists = ts.sys.directoryExists(directoryName); 868 dirExistsCache.set(directoryName, exists); 869 } 870 return exists; 871 }, 872 readFile(fileName: string): string | undefined { 873 return ts.sys.readFile(fileName); 874 }, 875 realpath(path: string): string { 876 return ts.sys.realpath(path); 877 }, 878 trace(s: string): void { 879 console.info(s); 880 } 881}; 882 883//This is only for test 884export const moduleResolutionHostTest = moduleResolutionHost; 885 886export function resolveTypeReferenceDirectives(typeDirectiveNames: string[] | ts.FileReference[]): ts.ResolvedTypeReferenceDirective[] { 887 if (typeDirectiveNames.length === 0) { 888 return []; 889 } 890 891 const resolvedTypeReferenceCache: ts.ResolvedTypeReferenceDirective[] = []; 892 const cache: Map<string, ts.ResolvedTypeReferenceDirective> = new Map<string, ts.ResolvedTypeReferenceDirective>(); 893 const containingFile: string = path.join(projectConfig.modulePath, 'build-profile.json5'); 894 895 for (const entry of typeDirectiveNames) { 896 const typeName = isString(entry) ? entry : entry.fileName.toLowerCase(); 897 if (!cache.has(typeName)) { 898 const resolvedFile = ts.resolveTypeReferenceDirective(typeName, containingFile, compilerOptions, moduleResolutionHost); 899 if (!resolvedFile || !resolvedFile.resolvedTypeReferenceDirective) { 900 logger.error('\u001b[31m', `ArkTS:Cannot find type definition file for: ${typeName}\n`); 901 } 902 const result: ts.ResolvedTypeReferenceDirective = resolvedFile.resolvedTypeReferenceDirective; 903 cache.set(typeName, result); 904 resolvedTypeReferenceCache.push(result); 905 } 906 } 907 return resolvedTypeReferenceCache; 908} 909 910// resolvedModulesCache records the files and their dependencies of program. 911export const resolvedModulesCache: Map<string, ts.ResolvedModuleFull[]> = new Map(); 912 913export function resolveModuleNames(moduleNames: string[], containingFile: string): ts.ResolvedModuleFull[] { 914 startTimeStatisticsLocation(resolveModuleNamesTime); 915 const resolvedModules: ts.ResolvedModuleFull[] = []; 916 const cacheFileContent: ts.ResolvedModuleFull[] = resolvedModulesCache.get(path.resolve(containingFile)); 917 if (![...shouldResolvedFiles].length || shouldResolvedFiles.has(path.resolve(containingFile)) || 918 !(cacheFileContent && cacheFileContent.length === moduleNames.length)) { 919 for (const moduleName of moduleNames) { 920 const result = ts.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost); 921 if (result.resolvedModule) { 922 if (result.resolvedModule.resolvedFileName && 923 path.extname(result.resolvedModule.resolvedFileName) === EXTNAME_JS) { 924 const resultDETSPath: string = 925 result.resolvedModule.resolvedFileName.replace(EXTNAME_JS, EXTNAME_D_ETS); 926 if (ts.sys.fileExists(resultDETSPath)) { 927 resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); 928 } else { 929 resolvedModules.push(result.resolvedModule); 930 } 931 } else { 932 resolvedModules.push(result.resolvedModule); 933 } 934 } else if (new RegExp(`^@(${sdkConfigPrefix})\\.`, 'i').test(moduleName.trim())) { 935 let apiFileExist: boolean = false; 936 for (let i = 0; i < sdkConfigs.length; i++) { 937 const sdkConfig = sdkConfigs[i]; 938 const resolveModuleInfo: ResolveModuleInfo = getRealModulePath(sdkConfig.apiPath, moduleName, ['.d.ts', '.d.ets']); 939 const modulePath: string = resolveModuleInfo.modulePath; 940 const isDETS: boolean = resolveModuleInfo.isEts; 941 if (systemModules.includes(moduleName + (isDETS ? '.d.ets' : '.d.ts')) && ts.sys.fileExists(modulePath)) { 942 resolvedModules.push(getResolveModule(modulePath, isDETS ? '.d.ets' : '.d.ts')); 943 apiFileExist = true; 944 break; 945 } 946 } 947 if (!apiFileExist) { 948 resolvedModules.push(null); 949 } 950 } else if (/\.ets$/.test(moduleName) && !/\.d\.ets$/.test(moduleName)) { 951 const modulePath: string = path.resolve(path.dirname(containingFile), moduleName); 952 if (ts.sys.fileExists(modulePath)) { 953 resolvedModules.push(getResolveModule(modulePath, '.ets')); 954 } else { 955 resolvedModules.push(null); 956 } 957 } else if (/\.ts$/.test(moduleName)) { 958 const modulePath: string = path.resolve(path.dirname(containingFile), moduleName); 959 if (ts.sys.fileExists(modulePath)) { 960 resolvedModules.push(getResolveModule(modulePath, '.ts')); 961 } else { 962 resolvedModules.push(null); 963 } 964 } else { 965 const modulePath: string = path.resolve(__dirname, '../../../api', moduleName + '.d.ts'); 966 const systemDETSModulePath: string = path.resolve(__dirname, '../../../api', moduleName + '.d.ets'); 967 const kitModulePath: string = path.resolve(__dirname, '../../../kits', moduleName + '.d.ts'); 968 const kitSystemDETSModulePath: string = path.resolve(__dirname, '../../../kits', moduleName + '.d.ets'); 969 const suffix: string = /\.js$/.test(moduleName) ? '' : '.js'; 970 const jsModulePath: string = path.resolve(__dirname, '../node_modules', moduleName + suffix); 971 const fileModulePath: string = 972 path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); 973 const DETSModulePath: string = path.resolve(path.dirname(containingFile), 974 /\.d\.ets$/.test(moduleName) ? moduleName : moduleName + EXTNAME_D_ETS); 975 if (ts.sys.fileExists(modulePath)) { 976 resolvedModules.push(getResolveModule(modulePath, '.d.ts')); 977 } else if (ts.sys.fileExists(systemDETSModulePath)) { 978 resolvedModules.push(getResolveModule(systemDETSModulePath, '.d.ets')); 979 } else if (ts.sys.fileExists(kitModulePath)) { 980 resolvedModules.push(getResolveModule(kitModulePath, '.d.ts')); 981 } else if (ts.sys.fileExists(kitSystemDETSModulePath)) { 982 resolvedModules.push(getResolveModule(kitSystemDETSModulePath, '.d.ets')); 983 } else if (ts.sys.fileExists(jsModulePath)) { 984 resolvedModules.push(getResolveModule(jsModulePath, '.js')); 985 } else if (ts.sys.fileExists(fileModulePath)) { 986 resolvedModules.push(getResolveModule(fileModulePath, '.js')); 987 } else if (ts.sys.fileExists(DETSModulePath)) { 988 resolvedModules.push(getResolveModule(DETSModulePath, '.d.ets')); 989 } else { 990 const srcIndex: number = projectConfig.projectPath.indexOf('src' + path.sep + 'main'); 991 let DETSModulePathFromModule: string; 992 if (srcIndex > 0) { 993 DETSModulePathFromModule = path.resolve( 994 projectConfig.projectPath.substring(0, srcIndex), moduleName + path.sep + 'index' + EXTNAME_D_ETS); 995 if (DETSModulePathFromModule && ts.sys.fileExists(DETSModulePathFromModule)) { 996 resolvedModules.push(getResolveModule(DETSModulePathFromModule, '.d.ets')); 997 } else { 998 resolvedModules.push(null); 999 } 1000 } else { 1001 resolvedModules.push(null); 1002 } 1003 } 1004 } 1005 if (projectConfig.hotReload && resolvedModules.length && 1006 resolvedModules[resolvedModules.length - 1]) { 1007 hotReloadSupportFiles.add(path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName)); 1008 } 1009 if (collectShouldPackedFiles(resolvedModules)) { 1010 allResolvedModules.add(resolvedModules[resolvedModules.length - 1].resolvedFileName); 1011 } 1012 } 1013 if (!projectConfig.xtsMode) { 1014 createOrUpdateCache(resolvedModules, path.resolve(containingFile)); 1015 } 1016 resolvedModulesCache.set(path.resolve(containingFile), resolvedModules); 1017 stopTimeStatisticsLocation(resolveModuleNamesTime); 1018 return resolvedModules; 1019 } 1020 stopTimeStatisticsLocation(resolveModuleNamesTime); 1021 return resolvedModulesCache.get(path.resolve(containingFile)); 1022} 1023 1024export interface ResolveModuleInfo { 1025 modulePath: string; 1026 isEts: boolean; 1027} 1028 1029function collectShouldPackedFiles(resolvedModules: ts.ResolvedModuleFull[]): boolean | RegExpMatchArray { 1030 return (projectConfig.compileHar || projectConfig.compileShared) && resolvedModules[resolvedModules.length - 1] && 1031 resolvedModules[resolvedModules.length - 1].resolvedFileName && 1032 (path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match(/(\.[^d]|[^\.]d|[^\.][^d])\.e?ts$/) || 1033 path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match(/\.d\.e?ts$/) && 1034 path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match( 1035 new RegExp('\\' + path.sep + 'src' + '\\' + path.sep + 'main' + '\\' + path.sep))); 1036} 1037 1038function createOrUpdateCache(resolvedModules: ts.ResolvedModuleFull[], containingFile: string): void { 1039 const children: string[] = []; 1040 const error: boolean = false; 1041 resolvedModules.forEach(moduleObj => { 1042 if (moduleObj && moduleObj.resolvedFileName && /\.(ets|ts)$/.test(moduleObj.resolvedFileName)) { 1043 const file: string = path.resolve(moduleObj.resolvedFileName); 1044 const mtimeMs: number = fs.statSync(file).mtimeMs; 1045 children.push(file); 1046 const value: CacheFileName = cache[file]; 1047 if (value) { 1048 value.mtimeMs = mtimeMs; 1049 value.error = error; 1050 value.parent = value.parent || []; 1051 value.parent.push(path.resolve(containingFile)); 1052 value.parent = [...new Set(value.parent)]; 1053 } else { 1054 cache[file] = { mtimeMs, children: [], parent: [containingFile], error }; 1055 } 1056 } 1057 }); 1058 cache[path.resolve(containingFile)] = { 1059 mtimeMs: fs.statSync(containingFile).mtimeMs, children, 1060 parent: cache[path.resolve(containingFile)] && cache[path.resolve(containingFile)].parent ? 1061 cache[path.resolve(containingFile)].parent : [], error 1062 }; 1063} 1064 1065export function createWatchCompilerHost(rootFileNames: string[], 1066 reportDiagnostic: ts.DiagnosticReporter, delayPrintLogCount: Function, resetErrorCount: Function, 1067 isPipe: boolean = false, resolveModulePaths: string[] = null): ts.WatchCompilerHostOfFilesAndCompilerOptions<ts.BuilderProgram> { 1068 if (projectConfig.hotReload) { 1069 rootFileNames.forEach(fileName => { 1070 hotReloadSupportFiles.add(fileName); 1071 }); 1072 } 1073 if (!(isPipe && process.env.compileTool === 'rollup')) { 1074 setCompilerOptions(resolveModulePaths); 1075 } 1076 // Change the buildInfo file path, or it will cover the buildInfo file created before. 1077 const buildInfoPath: string = path.resolve(projectConfig.cachePath, '..', WATCH_COMPILER_BUILD_INFO_SUFFIX); 1078 const watchCompilerOptions = {...compilerOptions, tsBuildInfoFile: buildInfoPath}; 1079 const createProgram = ts.createSemanticDiagnosticsBuilderProgram; 1080 const host = ts.createWatchCompilerHost( 1081 [...rootFileNames, ...readDeaclareFiles()], watchCompilerOptions, 1082 ts.sys, createProgram, reportDiagnostic, 1083 (diagnostic: ts.Diagnostic) => { 1084 if ([6031, 6032].includes(diagnostic.code)) { 1085 if (!isPipe) { 1086 process.env.watchTs = 'start'; 1087 resetErrorCount(); 1088 } 1089 } 1090 // End of compilation in watch mode flag. 1091 if ([6193, 6194].includes(diagnostic.code)) { 1092 if (!isPipe) { 1093 process.env.watchTs = 'end'; 1094 if (fastBuildLogger) { 1095 fastBuildLogger.debug(TS_WATCH_END_MSG); 1096 tsWatchEmitter.emit(TS_WATCH_END_MSG); 1097 } 1098 } 1099 delayPrintLogCount(); 1100 } 1101 }); 1102 host.readFile = (fileName: string) => { 1103 if (!fs.existsSync(fileName)) { 1104 return undefined; 1105 } 1106 if (/(?<!\.d)\.(ets|ts)$/.test(fileName)) { 1107 let content: string = processContent(fs.readFileSync(fileName).toString(), fileName); 1108 const extendFunctionInfo: extendInfo[] = []; 1109 content = instanceInsteadThis(content, fileName, extendFunctionInfo, props); 1110 return content; 1111 } 1112 return fs.readFileSync(fileName).toString(); 1113 }; 1114 host.resolveModuleNames = resolveModuleNames; 1115 host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives; 1116 return host; 1117} 1118 1119export function watchChecker(rootFileNames: string[], newLogger: any = null, resolveModulePaths: string[] = null): void { 1120 fastBuildLogger = newLogger; 1121 globalProgram.watchProgram = ts.createWatchProgram( 1122 createWatchCompilerHost(rootFileNames, printDiagnostic, () => { }, () => { }, false, resolveModulePaths)); 1123} 1124 1125export function instanceInsteadThis(content: string, fileName: string, extendFunctionInfo: extendInfo[], 1126 props: string[]): string { 1127 checkUISyntax(content, fileName, extendFunctionInfo, props); 1128 extendFunctionInfo.reverse().forEach((item) => { 1129 const subStr: string = content.substring(item.start, item.end); 1130 const insert: string = subStr.replace(/(\s)\$(\.)/g, (origin, item1, item2) => { 1131 return item1 + item.compName + 'Instance' + item2; 1132 }); 1133 content = content.slice(0, item.start) + insert + content.slice(item.end); 1134 }); 1135 return content; 1136} 1137 1138function getResolveModule(modulePath: string, type): ts.ResolvedModuleFull { 1139 return { 1140 resolvedFileName: modulePath, 1141 isExternalLibraryImport: false, 1142 extension: type 1143 }; 1144} 1145 1146export const dollarCollection: Set<string> = new Set(); 1147export const extendCollection: Set<string> = new Set(); 1148export const importModuleCollection: Set<string> = new Set(); 1149 1150function checkUISyntax(source: string, fileName: string, extendFunctionInfo: extendInfo[], props: string[]): void { 1151 if (/\.ets$/.test(fileName)) { 1152 if (process.env.compileMode === 'moduleJson' || 1153 path.resolve(fileName) !== path.resolve(projectConfig.projectPath, 'app.ets')) { 1154 const sourceFile: ts.SourceFile = ts.createSourceFile(fileName, source, 1155 ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS, compilerOptions); 1156 collectComponents(sourceFile); 1157 collectionCustomizeStyles(sourceFile); 1158 parseAllNode(sourceFile, sourceFile, extendFunctionInfo); 1159 props.push(...dollarCollection, ...extendCollection); 1160 } 1161 } 1162} 1163 1164function collectionCustomizeStyles(node: ts.Node): void { 1165 if ((ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) && 1166 (isUIDecorator(node, COMPONENT_STYLES_DECORATOR) || isUIDecorator(node, COMPONENT_EXTEND_DECORATOR)) && 1167 node.name && ts.isIdentifier(node.name)) { 1168 BUILDIN_STYLE_NAMES.add(node.name.escapedText.toString()); 1169 } 1170 if (ts.isSourceFile(node)) { 1171 node.statements.forEach((item: ts.Node) => { 1172 return collectionCustomizeStyles(item); 1173 }); 1174 } else if (ts.isStructDeclaration(node)) { 1175 node.members.forEach((item: ts.Node) => { 1176 return collectionCustomizeStyles(item); 1177 }); 1178 } 1179} 1180 1181function isUIDecorator(node: ts.MethodDeclaration | ts.FunctionDeclaration | 1182 ts.StructDeclaration | ts.ClassDeclaration, decortorName: string): boolean { 1183 const decorators: readonly ts.Decorator[] = ts.getAllDecorators(node); 1184 if (decorators && decorators.length) { 1185 for (let i = 0; i < decorators.length; i++) { 1186 const originalDecortor: string = decorators[i].getText().replace(/\(.*\)$/, '').trim(); 1187 if (originalDecortor === decortorName) { 1188 return true; 1189 } else { 1190 return false; 1191 } 1192 } 1193 } 1194 return false; 1195} 1196function collectComponents(node: ts.SourceFile): void { 1197 // @ts-ignore 1198 if (process.env.watchMode !== 'true' && node.identifiers && node.identifiers.size) { 1199 // @ts-ignore 1200 for (const key of node.identifiers.keys()) { 1201 if (JS_BIND_COMPONENTS.has(key)) { 1202 appComponentCollection.get(path.join(node.fileName)).add(key); 1203 } 1204 } 1205 } 1206} 1207 1208function parseAllNode(node: ts.Node, sourceFileNode: ts.SourceFile, extendFunctionInfo: extendInfo[]): void { 1209 if (ts.isStructDeclaration(node)) { 1210 if (node.members) { 1211 node.members.forEach(item => { 1212 if (ts.isPropertyDeclaration(item) && ts.isIdentifier(item.name)) { 1213 const propertyName: string = item.name.getText(); 1214 const decorators: readonly ts.Decorator[] = ts.getAllDecorators(item); 1215 if (decorators && decorators.length) { 1216 for (let i = 0; i < decorators.length; i++) { 1217 const decoratorName: string = decorators[i].getText().replace(/\(.*\)$/, '').trim(); 1218 if (INNER_COMPONENT_MEMBER_DECORATORS.has(decoratorName)) { 1219 dollarCollection.add('$' + propertyName); 1220 } 1221 } 1222 } 1223 } 1224 }); 1225 } 1226 } 1227 if (process.env.watchMode !== 'true' && ts.isIfStatement(node)) { 1228 appComponentCollection.get(path.join(sourceFileNode.fileName)).add(COMPONENT_IF); 1229 } 1230 if (ts.isMethodDeclaration(node) && node.name.getText() === COMPONENT_BUILD_FUNCTION || 1231 (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) && 1232 hasDecorator(node, COMPONENT_BUILDER_DECORATOR)) { 1233 if (node.body && node.body.statements && node.body.statements.length) { 1234 const checkProp: ts.NodeArray<ts.Statement> = node.body.statements; 1235 checkProp.forEach((item, index) => { 1236 traverseBuild(item, index); 1237 }); 1238 } 1239 } 1240 if (ts.isFunctionDeclaration(node) && hasDecorator(node, COMPONENT_EXTEND_DECORATOR)) { 1241 if (node.body && node.body.statements && node.body.statements.length && 1242 !isOriginalExtend(node.body)) { 1243 extendFunctionInfo.push({ 1244 start: node.pos, 1245 end: node.end, 1246 compName: isExtendFunction(node, { decoratorName: '', componentName: '' }) 1247 }); 1248 } 1249 } 1250 ts.forEachChild(node, (child: ts.Node) => parseAllNode(child, sourceFileNode, extendFunctionInfo)); 1251} 1252 1253function isForeachAndLzayForEach(node: ts.Node): boolean { 1254 return ts.isCallExpression(node) && node.expression && ts.isIdentifier(node.expression) && 1255 FOREACH_LAZYFOREACH.has(node.expression.escapedText.toString()) && node.arguments && node.arguments[1] && 1256 ts.isArrowFunction(node.arguments[1]) && node.arguments[1].body && ts.isBlock(node.arguments[1].body); 1257} 1258 1259function getComponentName(node: ts.Node): string { 1260 let temp = node.expression; 1261 let name: string; 1262 while (temp) { 1263 if (ts.isIdentifier(temp) && temp.parent && (ts.isCallExpression(temp.parent) || 1264 ts.isEtsComponentExpression(temp.parent))) { 1265 name = temp.escapedText.toString(); 1266 break; 1267 } 1268 temp = temp.expression; 1269 } 1270 return name; 1271} 1272 1273function traverseBuild(node: ts.Node, index: number): void { 1274 if (ts.isExpressionStatement(node)) { 1275 const parentComponentName: string = getComponentName(node); 1276 node = node.expression; 1277 while (node) { 1278 if (ts.isEtsComponentExpression(node) && node.body && ts.isBlock(node.body) && 1279 ts.isIdentifier(node.expression) && !DOLLAR_BLOCK_INTERFACE.has(node.expression.escapedText.toString())) { 1280 node.body.statements.forEach((item: ts.Statement, indexBlock: number) => { 1281 traverseBuild(item, indexBlock); 1282 }); 1283 break; 1284 } else if (isForeachAndLzayForEach(node)) { 1285 node.arguments[1].body.statements.forEach((item: ts.Statement, indexBlock: number) => { 1286 traverseBuild(item, indexBlock); 1287 }); 1288 break; 1289 } else { 1290 loopNodeFindDoubleDollar(node, parentComponentName); 1291 if (ts.isEtsComponentExpression(node) && node.body && ts.isBlock(node.body) && 1292 ts.isIdentifier(node.expression)) { 1293 node.body.statements.forEach((item: ts.Statement, indexBlock: number) => { 1294 traverseBuild(item, indexBlock); 1295 }); 1296 break; 1297 } 1298 } 1299 node = node.expression; 1300 } 1301 } else if (ts.isIfStatement(node)) { 1302 ifInnerDollarAttribute(node); 1303 } 1304} 1305 1306function ifInnerDollarAttribute(node: ts.IfStatement): void { 1307 if (node.thenStatement && ts.isBlock(node.thenStatement) && node.thenStatement.statements) { 1308 node.thenStatement.statements.forEach((item, indexIfBlock) => { 1309 traverseBuild(item, indexIfBlock); 1310 }); 1311 } 1312 if (node.elseStatement) { 1313 elseInnerDollarAttribute(node); 1314 } 1315} 1316 1317function elseInnerDollarAttribute(node: ts.IfStatement): void { 1318 if (ts.isIfStatement(node.elseStatement) && node.elseStatement.thenStatement && ts.isBlock(node.elseStatement.thenStatement)) { 1319 traverseBuild(node.elseStatement, 0); 1320 } else if (ts.isBlock(node.elseStatement) && node.elseStatement.statements) { 1321 node.elseStatement.statements.forEach((item, indexElseBlock) => { 1322 traverseBuild(item, indexElseBlock); 1323 }); 1324 } 1325} 1326 1327function isPropertiesAddDoubleDollar(node: ts.Node): boolean { 1328 if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.arguments && node.arguments.length) { 1329 return true; 1330 } else if (ts.isEtsComponentExpression(node) && ts.isIdentifier(node.expression) && 1331 DOLLAR_BLOCK_INTERFACE.has(node.expression.escapedText.toString())) { 1332 return true; 1333 } else { 1334 return false; 1335 } 1336} 1337function loopNodeFindDoubleDollar(node: ts.Node, parentComponentName: string): void { 1338 if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { 1339 const argument: ts.NodeArray<ts.Node> = node.arguments; 1340 const propertyName: ts.Identifier | ts.PrivateIdentifier = node.expression.name; 1341 if (isCanAddDoubleDollar(propertyName.getText(), parentComponentName)) { 1342 argument.forEach((item: ts.Node) => { 1343 doubleDollarCollection(item); 1344 }); 1345 } 1346 } else if (isPropertiesAddDoubleDollar(node)) { 1347 node.arguments.forEach((item: ts.Node) => { 1348 if (ts.isObjectLiteralExpression(item) && item.properties && item.properties.length) { 1349 item.properties.forEach((param: ts.Node) => { 1350 if (isObjectPram(param, parentComponentName)) { 1351 doubleDollarCollection(param.initializer); 1352 } 1353 }); 1354 } else if (ts.isPropertyAccessExpression(item) && (handleComponentDollarBlock(node as ts.CallExpression, parentComponentName) || 1355 STYLE_ADD_DOUBLE_DOLLAR.has(node.expression.getText()))) { 1356 doubleDollarCollection(item); 1357 } 1358 }); 1359 } 1360} 1361 1362function handleComponentDollarBlock(node: ts.CallExpression, parentComponentName: string): boolean { 1363 return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && 1364 DOLLAR_BLOCK_INTERFACE.has(parentComponentName) && PROPERTIES_ADD_DOUBLE_DOLLAR.has(parentComponentName) && 1365 PROPERTIES_ADD_DOUBLE_DOLLAR.get(parentComponentName).has(node.expression.escapedText.toString()); 1366} 1367 1368function doubleDollarCollection(item: ts.Node): void { 1369 if (item.getText().startsWith($$)) { 1370 while (item.expression) { 1371 item = item.expression; 1372 } 1373 dollarCollection.add(item.getText()); 1374 } 1375} 1376 1377function isObjectPram(param: ts.Node, parentComponentName: string): boolean { 1378 return ts.isPropertyAssignment(param) && param.name && ts.isIdentifier(param.name) && 1379 param.initializer && PROPERTIES_ADD_DOUBLE_DOLLAR.has(parentComponentName) && 1380 PROPERTIES_ADD_DOUBLE_DOLLAR.get(parentComponentName).has(param.name.getText()); 1381} 1382 1383function isCanAddDoubleDollar(propertyName: string, parentComponentName: string): boolean { 1384 return PROPERTIES_ADD_DOUBLE_DOLLAR.has(parentComponentName) && 1385 PROPERTIES_ADD_DOUBLE_DOLLAR.get(parentComponentName).has(propertyName) || 1386 STYLE_ADD_DOUBLE_DOLLAR.has(propertyName); 1387} 1388 1389function processContent(source: string, id: string): string { 1390 if (fastBuildLogger) { 1391 source = visualTransform(source, id, fastBuildLogger); 1392 } 1393 source = preprocessExtend(source, extendCollection); 1394 source = preprocessNewExtend(source, extendCollection); 1395 return source; 1396} 1397 1398function judgeFileShouldResolved(file: string, shouldResolvedFiles: Set<string>): void { 1399 if (shouldResolvedFiles.has(file)) { 1400 return; 1401 } 1402 shouldResolvedFiles.add(file); 1403 if (cache && cache[file] && cache[file].parent) { 1404 cache[file].parent.forEach((item) => { 1405 judgeFileShouldResolved(item, shouldResolvedFiles); 1406 }); 1407 cache[file].parent = []; 1408 } 1409 if (cache && cache[file] && cache[file].children) { 1410 cache[file].children.forEach((item) => { 1411 judgeFileShouldResolved(item, shouldResolvedFiles); 1412 }); 1413 cache[file].children = []; 1414 } 1415} 1416 1417export function incrementWatchFile(watchModifiedFiles: string[], 1418 watchRemovedFiles: string[]): void { 1419 const changedFiles: string[] = [...watchModifiedFiles, ...watchRemovedFiles]; 1420 if (changedFiles.length) { 1421 shouldResolvedFiles.clear(); 1422 } 1423 changedFiles.forEach((file) => { 1424 judgeFileShouldResolved(file, shouldResolvedFiles); 1425 }); 1426} 1427 1428export function runArkTSLinter(): void { 1429 const originProgram: ts.BuilderProgram = globalProgram.builderProgram; 1430 1431 const timePrinterInstance = ts.ArkTSLinterTimePrinter.getInstance(); 1432 1433 const arkTSLinterDiagnostics = doArkTSLinter(getArkTSVersion(), 1434 getArkTSLinterMode(), 1435 originProgram, 1436 printArkTSLinterDiagnostic, 1437 !projectConfig.xtsMode, 1438 buildInfoWriteFile); 1439 1440 if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { 1441 arkTSLinterDiagnostics.forEach((diagnostic: ts.Diagnostic) => { 1442 updateErrorFileCache(diagnostic); 1443 }); 1444 timePrinterInstance.appendTime(ts.TimePhase.UPDATE_ERROR_FILE); 1445 } 1446 timePrinterInstance.printTimes(); 1447 ts.ArkTSLinterTimePrinter.destroyInstance(); 1448} 1449 1450function printArkTSLinterDiagnostic(diagnostic: ts.Diagnostic): void { 1451 if (diagnostic.category === ts.DiagnosticCategory.Error && (isInOhModuleFile(diagnostic) || isEtsDeclFileInSdk(diagnostic))) { 1452 const originalCategory = diagnostic.category; 1453 diagnostic.category = ts.DiagnosticCategory.Warning; 1454 printDiagnostic(diagnostic); 1455 diagnostic.category = originalCategory; 1456 return; 1457 } 1458 printDiagnostic(diagnostic); 1459} 1460 1461function isEtsDeclFileInSdk(diagnostics: ts.Diagnostic): boolean { 1462 if (diagnostics.file?.fileName === undefined) { 1463 return false; 1464 } 1465 return isInSDK(diagnostics.file.fileName) && diagnostics.file.fileName.endsWith('.ets'); 1466} 1467 1468function isInOhModuleFile(diagnostics: ts.Diagnostic): boolean { 1469 return (diagnostics.file !== undefined) && 1470 ((diagnostics.file.fileName.indexOf('/oh_modules/') !== -1) || diagnostics.file.fileName.indexOf('\\oh_modules\\') !== -1); 1471} 1472 1473function isInSDK(fileName: string | undefined): boolean { 1474 if (projectConfig.etsLoaderPath === undefined || fileName === undefined) { 1475 return false; 1476 } 1477 const sdkPath = path.resolve(projectConfig.etsLoaderPath, '../../../'); 1478 return path.resolve(fileName).startsWith(sdkPath); 1479} 1480 1481export function getArkTSLinterMode(): ArkTSLinterMode { 1482 if (!partialUpdateConfig.executeArkTSLinter) { 1483 return ArkTSLinterMode.NOT_USE; 1484 } 1485 1486 if (!partialUpdateConfig.standardArkTSLinter) { 1487 return ArkTSLinterMode.COMPATIBLE_MODE; 1488 } 1489 1490 if (isStandardMode()) { 1491 return ArkTSLinterMode.STANDARD_MODE; 1492 } 1493 return ArkTSLinterMode.COMPATIBLE_MODE; 1494} 1495 1496export function isStandardMode(): boolean { 1497 const STANDARD_MODE_COMPATIBLE_SDK_VERSION = 10; 1498 if (projectConfig && 1499 projectConfig.compatibleSdkVersion && 1500 projectConfig.compatibleSdkVersion >= STANDARD_MODE_COMPATIBLE_SDK_VERSION) { 1501 return true; 1502 } 1503 return false; 1504} 1505 1506function getArkTSVersion(): ArkTSVersion { 1507 if (projectConfig.arkTSVersion === '1.0') { 1508 return ArkTSVersion.ArkTS_1_0; 1509 } else if (projectConfig.arkTSVersion === '1.1') { 1510 return ArkTSVersion.ArkTS_1_1; 1511 } else if (projectConfig.arkTSVersion !== undefined) { 1512 const arkTSVersionLogger = fastBuildLogger || logger; 1513 arkTSVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid ArkTS version\n'); 1514 } 1515 1516 if (partialUpdateConfig.arkTSVersion === '1.0') { 1517 return ArkTSVersion.ArkTS_1_0; 1518 } else if (partialUpdateConfig.arkTSVersion === '1.1') { 1519 return ArkTSVersion.ArkTS_1_1; 1520 } else if (partialUpdateConfig.arkTSVersion !== undefined) { 1521 const arkTSVersionLogger = fastBuildLogger || logger; 1522 arkTSVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid ArkTS version in metadata\n'); 1523 } 1524 1525 return ArkTSVersion.ArkTS_1_1; 1526} 1527 1528enum TargetESVersion { 1529 ES2017 = 'ES2017', 1530 ES2021 = 'ES2021', 1531} 1532 1533function getTargetESVersion(): TargetESVersion { 1534 const targetESVersion = projectConfig?.projectArkOption?.tscConfig?.targetESVersion; 1535 if (targetESVersion === 'ES2017') { 1536 return TargetESVersion.ES2017; 1537 } else if (targetESVersion === 'ES2021') { 1538 return TargetESVersion.ES2021; 1539 } else if (targetESVersion !== undefined) { 1540 const targetESVersionLogger = fastBuildLogger || logger; 1541 targetESVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid Target ES version\n'); 1542 } 1543 return TargetESVersion.ES2021; 1544} 1545 1546interface TargetESVersionLib { 1547 ES2017: string[], 1548 ES2021: string[], 1549} 1550 1551const targetESVersionLib: TargetESVersionLib = { 1552 // When target is es2017, the lib is es2020. 1553 ES2017: ['ES2020'], 1554 ES2021: ['ES2021'], 1555}; 1556 1557function getTargetESVersionLib(): string[] { 1558 const targetESVersion = projectConfig?.projectArkOption?.tscConfig?.targetESVersion; 1559 if (targetESVersion === 'ES2017') { 1560 return targetESVersionLib.ES2017; 1561 } else if (targetESVersion === 'ES2021') { 1562 return targetESVersionLib.ES2021; 1563 } else if (targetESVersion !== undefined) { 1564 const targetESVersionLogger = fastBuildLogger || logger; 1565 targetESVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid Target ES version\n'); 1566 } 1567 return targetESVersionLib.ES2021; 1568} 1569 1570function initEtsStandaloneCheckerConfig(logger, config): void { 1571 fastBuildLogger = logger; 1572 if (config.packageManagerType === 'ohpm') { 1573 config.packageDir = 'oh_modules'; 1574 config.packageJson = 'oh-package.json5'; 1575 } else { 1576 config.packageDir = 'node_modules'; 1577 config.packageJson = 'package.json'; 1578 } 1579 if (config.aceModuleJsonPath && fs.existsSync(config.aceModuleJsonPath)) { 1580 process.env.compileMode = 'moduleJson'; 1581 } 1582 Object.assign(projectConfig, config); 1583} 1584 1585function resetEtsStandaloneCheckerConfig(beforeInitFastBuildLogger, beforeInitCompileMode: string): void { 1586 resetProjectConfig(); 1587 resetEtsCheck(); 1588 fastBuildLogger = beforeInitFastBuildLogger; 1589 process.env.compileMode = beforeInitCompileMode; 1590} 1591 1592export function etsStandaloneChecker(entryObj, logger, projectConfig): void { 1593 const beforeInitFastBuildLogger = fastBuildLogger; 1594 const beforeInitCompileMode = process.env.compileMode; 1595 initEtsStandaloneCheckerConfig(logger, projectConfig); 1596 const rootFileNames: string[] = []; 1597 const resolveModulePaths: string[] = []; 1598 Object.values(entryObj).forEach((fileName: string) => { 1599 rootFileNames.push(path.resolve(fileName)); 1600 }); 1601 if (projectConfig.resolveModulePaths && Array.isArray(projectConfig.resolveModulePaths)) { 1602 resolveModulePaths.push(...projectConfig.resolveModulePaths); 1603 } 1604 const filterFiles: string[] = filterInput(rootFileNames); 1605 languageService = createLanguageService(filterFiles, resolveModulePaths); 1606 const timePrinterInstance = ts.ArkTSLinterTimePrinter.getInstance(); 1607 timePrinterInstance.setArkTSTimePrintSwitch(false); 1608 timePrinterInstance.appendTime(ts.TimePhase.START); 1609 globalProgram.builderProgram = languageService.getBuilderProgram(/*withLinterProgram*/ true); 1610 globalProgram.program = globalProgram.builderProgram.getProgram(); 1611 props = languageService.getProps(); 1612 timePrinterInstance.appendTime(ts.TimePhase.GET_PROGRAM); 1613 collectFileToIgnoreDiagnostics(filterFiles); 1614 runArkTSLinter(); 1615 const allDiagnostics: ts.Diagnostic[] = globalProgram.builderProgram 1616 .getSyntacticDiagnostics() 1617 .concat(globalProgram.builderProgram.getSemanticDiagnostics()); 1618 globalProgram.builderProgram.emitBuildInfo(buildInfoWriteFile); 1619 1620 allDiagnostics.forEach((diagnostic: ts.Diagnostic) => { 1621 printDiagnostic(diagnostic); 1622 }); 1623 resetEtsStandaloneCheckerConfig(beforeInitFastBuildLogger, beforeInitCompileMode); 1624} 1625 1626export function resetEtsCheckTypeScript(): void { 1627 if (globalProgram.program) { 1628 globalProgram.program.releaseTypeChecker(); 1629 } else if (languageService) { 1630 languageService.getProgram().releaseTypeChecker(); 1631 } 1632 resetGlobalProgram(); 1633 languageService = null; 1634} 1635 1636export function resetEtsCheck(): void { 1637 cache = {}; 1638 props = []; 1639 needReCheckForChangedDepUsers = false; 1640 resetEtsCheckTypeScript(); 1641 allResolvedModules.clear(); 1642 checkerResult.count = 0; 1643 warnCheckerResult.count = 0; 1644 resolvedModulesCache.clear(); 1645 dollarCollection.clear(); 1646 extendCollection.clear(); 1647 allSourceFilePaths.clear(); 1648 allModuleIds.clear(); 1649 filesBuildInfo.clear(); 1650 fileExistsCache.clear(); 1651 dirExistsCache.clear(); 1652 targetESVersionChanged = false; 1653 fileToIgnoreDiagnostics = undefined; 1654} 1655