107ac75b1Sopenharmony_ci/*
207ac75b1Sopenharmony_ci * Copyright (c) 2023 Huawei Device Co., Ltd.
307ac75b1Sopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License");
407ac75b1Sopenharmony_ci * you may not use this file except in compliance with the License.
507ac75b1Sopenharmony_ci * You may obtain a copy of the License at
607ac75b1Sopenharmony_ci *
707ac75b1Sopenharmony_ci *     http://www.apache.org/licenses/LICENSE-2.0
807ac75b1Sopenharmony_ci *
907ac75b1Sopenharmony_ci * Unless required by applicable law or agreed to in writing, software
1007ac75b1Sopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS,
1107ac75b1Sopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1207ac75b1Sopenharmony_ci * See the License for the specific language governing permissions and
1307ac75b1Sopenharmony_ci * limitations under the License.
1407ac75b1Sopenharmony_ci */
1507ac75b1Sopenharmony_ci
1607ac75b1Sopenharmony_ciimport path from 'path';
1707ac75b1Sopenharmony_ciimport fs from 'fs';
1807ac75b1Sopenharmony_ciimport type sourceMap from 'source-map';
1907ac75b1Sopenharmony_ci
2007ac75b1Sopenharmony_ciimport { minify, MinifyOutput } from 'terser';
2107ac75b1Sopenharmony_ciimport {
2207ac75b1Sopenharmony_ci  deleteLineInfoForNameString,
2307ac75b1Sopenharmony_ci  MemoryUtils,
2407ac75b1Sopenharmony_ci  nameCacheMap,
2507ac75b1Sopenharmony_ci  unobfuscationNamesObj
2607ac75b1Sopenharmony_ci} from 'arkguard';
2707ac75b1Sopenharmony_ciimport {
2807ac75b1Sopenharmony_ci  OH_MODULES,
2907ac75b1Sopenharmony_ci  SEPARATOR_AT,
3007ac75b1Sopenharmony_ci  SEPARATOR_BITWISE_AND,
3107ac75b1Sopenharmony_ci  SEPARATOR_SLASH
3207ac75b1Sopenharmony_ci} from './fast_build/ark_compiler/common/ark_define';
3307ac75b1Sopenharmony_ciimport {
3407ac75b1Sopenharmony_ci  ARKTS_MODULE_NAME,
3507ac75b1Sopenharmony_ci  PACKAGES,
3607ac75b1Sopenharmony_ci  TEMPORARY,
3707ac75b1Sopenharmony_ci  ZERO,
3807ac75b1Sopenharmony_ci  ONE,
3907ac75b1Sopenharmony_ci  EXTNAME_JS,
4007ac75b1Sopenharmony_ci  EXTNAME_TS,
4107ac75b1Sopenharmony_ci  EXTNAME_MJS,
4207ac75b1Sopenharmony_ci  EXTNAME_CJS,
4307ac75b1Sopenharmony_ci  EXTNAME_ABC,
4407ac75b1Sopenharmony_ci  EXTNAME_ETS,
4507ac75b1Sopenharmony_ci  EXTNAME_TS_MAP,
4607ac75b1Sopenharmony_ci  EXTNAME_JS_MAP,
4707ac75b1Sopenharmony_ci  ESMODULE,
4807ac75b1Sopenharmony_ci  FAIL,
4907ac75b1Sopenharmony_ci  TS2ABC,
5007ac75b1Sopenharmony_ci  ES2ABC,
5107ac75b1Sopenharmony_ci  EXTNAME_PROTO_BIN,
5207ac75b1Sopenharmony_ci  NATIVE_MODULE
5307ac75b1Sopenharmony_ci} from './pre_define';
5407ac75b1Sopenharmony_ciimport {
5507ac75b1Sopenharmony_ci  isMac,
5607ac75b1Sopenharmony_ci  isWindows,
5707ac75b1Sopenharmony_ci  isPackageModulesFile,
5807ac75b1Sopenharmony_ci  genTemporaryPath,
5907ac75b1Sopenharmony_ci  getExtensionIfUnfullySpecifiedFilepath,
6007ac75b1Sopenharmony_ci  mkdirsSync,
6107ac75b1Sopenharmony_ci  toUnixPath,
6207ac75b1Sopenharmony_ci  validateFilePathLength,
6307ac75b1Sopenharmony_ci  harFilesRecord,
6407ac75b1Sopenharmony_ci  getProjectRootPath
6507ac75b1Sopenharmony_ci} from './utils';
6607ac75b1Sopenharmony_ciimport type { GeneratedFileInHar } from './utils';
6707ac75b1Sopenharmony_ciimport {
6807ac75b1Sopenharmony_ci  extendSdkConfigs,
6907ac75b1Sopenharmony_ci  projectConfig,
7007ac75b1Sopenharmony_ci  sdkConfigPrefix
7107ac75b1Sopenharmony_ci} from '../main';
7207ac75b1Sopenharmony_ciimport { getRelativeSourcePath, mangleFilePath } from './fast_build/ark_compiler/common/ob_config_resolver';
7307ac75b1Sopenharmony_ciimport { moduleRequestCallback } from './fast_build/system_api/api_check_utils';
7407ac75b1Sopenharmony_ciimport { performancePrinter } from 'arkguard/lib/ArkObfuscator';
7507ac75b1Sopenharmony_ciimport { SourceMapGenerator } from './fast_build/ark_compiler/generate_sourcemap';
7607ac75b1Sopenharmony_ciimport { sourceFileBelongProject } from './fast_build/ark_compiler/module/module_source_file';
7707ac75b1Sopenharmony_ci
7807ac75b1Sopenharmony_ciconst red: string = '\u001b[31m';
7907ac75b1Sopenharmony_ciconst reset: string = '\u001b[39m';
8007ac75b1Sopenharmony_ciconst IDENTIFIER_CACHE: string = 'IdentifierCache';
8107ac75b1Sopenharmony_ci
8207ac75b1Sopenharmony_ciexport const SRC_MAIN: string = 'src/main';
8307ac75b1Sopenharmony_ci
8407ac75b1Sopenharmony_ciexport let newSourceMaps: Object = {};
8507ac75b1Sopenharmony_ci
8607ac75b1Sopenharmony_ciexport const packageCollection: Map<string, Array<string>> = new Map();
8707ac75b1Sopenharmony_ci// Splicing ohmurl or record name based on filePath and context information table.
8807ac75b1Sopenharmony_ciexport function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: Object, logger: Object,
8907ac75b1Sopenharmony_ci  pkgParams: Object, importerFile: string): string {
9007ac75b1Sopenharmony_ci  const { pkgName, pkgPath, isRecordName } = pkgParams;
9107ac75b1Sopenharmony_ci  // rollup uses commonjs plugin to handle commonjs files,
9207ac75b1Sopenharmony_ci  // the commonjs files are prefixed with '\x00' and need to be removed.
9307ac75b1Sopenharmony_ci  if (filePath.startsWith('\x00')) {
9407ac75b1Sopenharmony_ci    filePath = filePath.replace('\x00', '');
9507ac75b1Sopenharmony_ci  }
9607ac75b1Sopenharmony_ci  let unixFilePath: string = toUnixPath(filePath);
9707ac75b1Sopenharmony_ci  unixFilePath = unixFilePath.substring(0, filePath.lastIndexOf('.')); // remove extension
9807ac75b1Sopenharmony_ci  let projectFilePath: string = unixFilePath.replace(toUnixPath(pkgPath), '');
9907ac75b1Sopenharmony_ci  // case1: /entry/src/main/ets/xxx/yyy
10007ac75b1Sopenharmony_ci  // case2: /entry/src/ohosTest/ets/xxx/yyy
10107ac75b1Sopenharmony_ci  // case3: /node_modules/xxx/yyy
10207ac75b1Sopenharmony_ci  // case4: /entry/node_modules/xxx/yyy
10307ac75b1Sopenharmony_ci  // case5: /library/node_modules/xxx/yyy
10407ac75b1Sopenharmony_ci  // case6: /library/index.ts
10507ac75b1Sopenharmony_ci  // ---> @normalized:N&<moduleName>&<bunldName>&<packageName>/entry/ets/xxx/yyy&<version>
10607ac75b1Sopenharmony_ci  let pkgInfo = projectConfig.pkgContextInfo[pkgName];
10707ac75b1Sopenharmony_ci  if (pkgInfo === undefined) {
10807ac75b1Sopenharmony_ci    logger.error(red, 'ArkTS:ERROR Failed to resolve OhmUrl.\n' +
10907ac75b1Sopenharmony_ci      `Error Message: Failed to get a resolved OhmUrl for "${filePath}" imported by "${importerFile}".\n` +
11007ac75b1Sopenharmony_ci      `Solutions: > Check whether the module which ${filePath} belongs to is correctly configured.` +
11107ac75b1Sopenharmony_ci      '> Check the corresponding file name is correct(including case-sensitivity).', reset);
11207ac75b1Sopenharmony_ci  }
11307ac75b1Sopenharmony_ci  let recordName = `${pkgInfo.bundleName}&${pkgName}${projectFilePath}&${pkgInfo.version}`;
11407ac75b1Sopenharmony_ci  if (isRecordName) {
11507ac75b1Sopenharmony_ci    // record name style: <bunldName>&<packageName>/entry/ets/xxx/yyy&<version>
11607ac75b1Sopenharmony_ci    return recordName;
11707ac75b1Sopenharmony_ci  }
11807ac75b1Sopenharmony_ci  return `${pkgInfo.isSO ? 'Y' : 'N'}&${pkgInfo.moduleName}&${recordName}`;
11907ac75b1Sopenharmony_ci}
12007ac75b1Sopenharmony_ci
12107ac75b1Sopenharmony_ciexport function getOhmUrlByFilepath(filePath: string, projectConfig: Object, logger: Object, namespace?: string,
12207ac75b1Sopenharmony_ci  importerFile?: string): string {
12307ac75b1Sopenharmony_ci  // remove '\x00' from the rollup virtual commonjs file's filePath
12407ac75b1Sopenharmony_ci  if (filePath.startsWith('\x00')) {
12507ac75b1Sopenharmony_ci    filePath = filePath.replace('\x00', '');
12607ac75b1Sopenharmony_ci  }
12707ac75b1Sopenharmony_ci  let unixFilePath: string = toUnixPath(filePath);
12807ac75b1Sopenharmony_ci  unixFilePath = unixFilePath.substring(0, filePath.lastIndexOf('.')); // remove extension
12907ac75b1Sopenharmony_ci  const REG_PROJECT_SRC: RegExp = /(\S+)\/src\/(?:main|ohosTest)\/(ets|js|mock)\/(\S+)/;
13007ac75b1Sopenharmony_ci
13107ac75b1Sopenharmony_ci  const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath);
13207ac75b1Sopenharmony_ci  const bundleName: string = packageInfo[0];
13307ac75b1Sopenharmony_ci  const moduleName: string = packageInfo[1];
13407ac75b1Sopenharmony_ci  const moduleRootPath: string = toUnixPath(projectConfig.modulePathMap[moduleName]);
13507ac75b1Sopenharmony_ci  const projectRootPath: string = toUnixPath(getProjectRootPath(filePath, projectConfig, projectConfig?.rootPathSet));
13607ac75b1Sopenharmony_ci  // case1: /entry/src/main/ets/xxx/yyy     ---> @bundle:<bundleName>/entry/ets/xxx/yyy
13707ac75b1Sopenharmony_ci  // case2: /entry/src/ohosTest/ets/xxx/yyy ---> @bundle:<bundleName>/entry_test@entry/ets/xxx/yyy
13807ac75b1Sopenharmony_ci  // case3: /node_modules/xxx/yyy           ---> @package:pkg_modules/xxx/yyy
13907ac75b1Sopenharmony_ci  // case4: /entry/node_modules/xxx/yyy     ---> @package:pkg_modules@entry/xxx/yyy
14007ac75b1Sopenharmony_ci  // case5: /library/node_modules/xxx/yyy   ---> @package:pkg_modules@library/xxx/yyy
14107ac75b1Sopenharmony_ci  // case6: /library/index.ts               ---> @bundle:<bundleName>/library/index
14207ac75b1Sopenharmony_ci  const projectFilePath: string = unixFilePath.replace(projectRootPath, '');
14307ac75b1Sopenharmony_ci  const packageDir: string = projectConfig.packageDir;
14407ac75b1Sopenharmony_ci  const result: RegExpMatchArray | null = projectFilePath.match(REG_PROJECT_SRC);
14507ac75b1Sopenharmony_ci  if (result && result[1].indexOf(packageDir) === -1) {
14607ac75b1Sopenharmony_ci    const relativePath = processSrcMain(result, projectFilePath);
14707ac75b1Sopenharmony_ci    if (namespace && moduleName !== namespace) {
14807ac75b1Sopenharmony_ci      return `${bundleName}/${moduleName}@${namespace}/${relativePath}`;
14907ac75b1Sopenharmony_ci    }
15007ac75b1Sopenharmony_ci    return `${bundleName}/${moduleName}/${relativePath}`;
15107ac75b1Sopenharmony_ci  }
15207ac75b1Sopenharmony_ci
15307ac75b1Sopenharmony_ci  const processParams: Object = {
15407ac75b1Sopenharmony_ci    projectFilePath,
15507ac75b1Sopenharmony_ci    unixFilePath,
15607ac75b1Sopenharmony_ci    packageDir,
15707ac75b1Sopenharmony_ci    projectRootPath,
15807ac75b1Sopenharmony_ci    moduleRootPath,
15907ac75b1Sopenharmony_ci    projectConfig,
16007ac75b1Sopenharmony_ci    namespace,
16107ac75b1Sopenharmony_ci    logger,
16207ac75b1Sopenharmony_ci    importerFile,
16307ac75b1Sopenharmony_ci    originalFilePath: filePath
16407ac75b1Sopenharmony_ci  };
16507ac75b1Sopenharmony_ci  return processPackageDir(processParams);
16607ac75b1Sopenharmony_ci}
16707ac75b1Sopenharmony_ci
16807ac75b1Sopenharmony_cifunction processSrcMain(result: RegExpMatchArray | null, projectFilePath: string): string {
16907ac75b1Sopenharmony_ci  let langType: string = result[2];
17007ac75b1Sopenharmony_ci  let relativePath: string = result[3];
17107ac75b1Sopenharmony_ci  // case7: /entry/src/main/ets/xxx/src/main/js/yyy ---> @bundle:<bundleName>/entry/ets/xxx/src/main/js/yyy
17207ac75b1Sopenharmony_ci  const REG_SRC_MAIN: RegExp = /src\/(?:main|ohosTest)\/(ets|js)\//;
17307ac75b1Sopenharmony_ci  const srcMainIndex: number = result[1].search(REG_SRC_MAIN);
17407ac75b1Sopenharmony_ci  if (srcMainIndex !== -1) {
17507ac75b1Sopenharmony_ci    relativePath = projectFilePath.substring(srcMainIndex).replace(REG_SRC_MAIN, '');
17607ac75b1Sopenharmony_ci    langType = projectFilePath.replace(relativePath, '').match(REG_SRC_MAIN)[1];
17707ac75b1Sopenharmony_ci  }
17807ac75b1Sopenharmony_ci  return `${langType}/${relativePath}`;
17907ac75b1Sopenharmony_ci}
18007ac75b1Sopenharmony_ci
18107ac75b1Sopenharmony_cifunction processPackageDir(params: Object): string {
18207ac75b1Sopenharmony_ci  const { projectFilePath, unixFilePath, packageDir, projectRootPath, moduleRootPath,
18307ac75b1Sopenharmony_ci    projectConfig, namespace, logger, importerFile, originalFilePath } = params;
18407ac75b1Sopenharmony_ci  if (projectFilePath.indexOf(packageDir) !== -1) {
18507ac75b1Sopenharmony_ci    if (compileToolIsRollUp()) {
18607ac75b1Sopenharmony_ci      const tryProjectPkg: string = toUnixPath(path.join(projectRootPath, packageDir));
18707ac75b1Sopenharmony_ci      if (unixFilePath.indexOf(tryProjectPkg) !== -1) {
18807ac75b1Sopenharmony_ci        return unixFilePath.replace(tryProjectPkg, `${packageDir}`).replace(new RegExp(packageDir, 'g'), PACKAGES);
18907ac75b1Sopenharmony_ci      }
19007ac75b1Sopenharmony_ci
19107ac75b1Sopenharmony_ci      // iterate the modulePathMap to find the module which contains the pkg_module's file
19207ac75b1Sopenharmony_ci      for (const moduleName in projectConfig.modulePathMap) {
19307ac75b1Sopenharmony_ci        const modulePath: string = projectConfig.modulePathMap[moduleName];
19407ac75b1Sopenharmony_ci        const tryModulePkg: string = toUnixPath(path.resolve(modulePath, packageDir));
19507ac75b1Sopenharmony_ci        if (unixFilePath.indexOf(tryModulePkg) !== -1) {
19607ac75b1Sopenharmony_ci          return unixFilePath.replace(tryModulePkg, `${packageDir}@${moduleName}`).replace(new RegExp(packageDir, 'g'), PACKAGES);
19707ac75b1Sopenharmony_ci        }
19807ac75b1Sopenharmony_ci      }
19907ac75b1Sopenharmony_ci
20007ac75b1Sopenharmony_ci      logger.error(red, 'ArkTS:ERROR Failed to resolve OhmUrl.\n' +
20107ac75b1Sopenharmony_ci        `Error Message: Failed to get a resolved OhmUrl for "${originalFilePath}" imported by "${importerFile}".\n` +
20207ac75b1Sopenharmony_ci        `Solutions: > Check whether the module which ${originalFilePath} belongs to is correctly configured.` +
20307ac75b1Sopenharmony_ci        '> Check the corresponding file name is correct(including case-sensitivity).', reset);
20407ac75b1Sopenharmony_ci      return originalFilePath;
20507ac75b1Sopenharmony_ci    }
20607ac75b1Sopenharmony_ci
20707ac75b1Sopenharmony_ci    // webpack with old implematation
20807ac75b1Sopenharmony_ci    const tryProjectPkg: string = toUnixPath(path.join(projectRootPath, packageDir));
20907ac75b1Sopenharmony_ci    if (unixFilePath.indexOf(tryProjectPkg) !== -1) {
21007ac75b1Sopenharmony_ci      return unixFilePath.replace(tryProjectPkg, `${packageDir}/${ONE}`).replace(new RegExp(packageDir, 'g'), PACKAGES);
21107ac75b1Sopenharmony_ci    }
21207ac75b1Sopenharmony_ci
21307ac75b1Sopenharmony_ci    const tryModulePkg: string = toUnixPath(path.join(moduleRootPath, packageDir));
21407ac75b1Sopenharmony_ci    if (unixFilePath.indexOf(tryModulePkg) !== -1) {
21507ac75b1Sopenharmony_ci      return unixFilePath.replace(tryModulePkg, `${packageDir}/${ZERO}`).replace(new RegExp(packageDir, 'g'), PACKAGES);
21607ac75b1Sopenharmony_ci    }
21707ac75b1Sopenharmony_ci  }
21807ac75b1Sopenharmony_ci
21907ac75b1Sopenharmony_ci  const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath);
22007ac75b1Sopenharmony_ci  const bundleName: string = packageInfo[0];
22107ac75b1Sopenharmony_ci  const moduleName: string = packageInfo[1];
22207ac75b1Sopenharmony_ci  for (const key in projectConfig.modulePathMap) {
22307ac75b1Sopenharmony_ci    const moduleRootPath: string = toUnixPath(projectConfig.modulePathMap[key]);
22407ac75b1Sopenharmony_ci    if (unixFilePath.indexOf(moduleRootPath + '/') !== -1) {
22507ac75b1Sopenharmony_ci      const relativeModulePath: string = unixFilePath.replace(moduleRootPath + '/', '');
22607ac75b1Sopenharmony_ci      if (namespace && moduleName !== namespace) {
22707ac75b1Sopenharmony_ci        return `${bundleName}/${moduleName}@${namespace}/${relativeModulePath}`;
22807ac75b1Sopenharmony_ci      }
22907ac75b1Sopenharmony_ci      return `${bundleName}/${moduleName}/${relativeModulePath}`;
23007ac75b1Sopenharmony_ci    }
23107ac75b1Sopenharmony_ci  }
23207ac75b1Sopenharmony_ci
23307ac75b1Sopenharmony_ci  logger.error(red, 'ArkTS:ERROR Failed to resolve OhmUrl.\n' +
23407ac75b1Sopenharmony_ci    `Error Message: Failed to get a resolved OhmUrl for "${originalFilePath}" imported by "${importerFile}".\n` +
23507ac75b1Sopenharmony_ci    `Solutions: > Check whether the module which ${originalFilePath} belongs to is correctly configured.` +
23607ac75b1Sopenharmony_ci    '> Check the corresponding file name is correct(including case-sensitivity).', reset);
23707ac75b1Sopenharmony_ci  return originalFilePath;
23807ac75b1Sopenharmony_ci}
23907ac75b1Sopenharmony_ci
24007ac75b1Sopenharmony_ci
24107ac75b1Sopenharmony_ciexport function getOhmUrlBySystemApiOrLibRequest(moduleRequest: string, config?: Object, logger?: Object,
24207ac75b1Sopenharmony_ci  importerFile?: string, useNormalizedOHMUrl: boolean = false): string {
24307ac75b1Sopenharmony_ci  // 'arkui-x' represents cross platform related APIs, processed as 'ohos'
24407ac75b1Sopenharmony_ci  const REG_SYSTEM_MODULE: RegExp = new RegExp(`@(${sdkConfigPrefix})\\.(\\S+)`);
24507ac75b1Sopenharmony_ci  const REG_LIB_SO: RegExp = /lib(\S+)\.so/;
24607ac75b1Sopenharmony_ci
24707ac75b1Sopenharmony_ci  if (REG_SYSTEM_MODULE.test(moduleRequest.trim())) {
24807ac75b1Sopenharmony_ci    return moduleRequest.replace(REG_SYSTEM_MODULE, (_, moduleType, systemKey) => {
24907ac75b1Sopenharmony_ci      let moduleRequestStr = '';
25007ac75b1Sopenharmony_ci      if (extendSdkConfigs) {
25107ac75b1Sopenharmony_ci        moduleRequestStr = moduleRequestCallback(moduleRequest, _, moduleType, systemKey);
25207ac75b1Sopenharmony_ci      }
25307ac75b1Sopenharmony_ci      if (moduleRequestStr !== '') {
25407ac75b1Sopenharmony_ci        return moduleRequestStr;
25507ac75b1Sopenharmony_ci      }
25607ac75b1Sopenharmony_ci      const systemModule: string = `${moduleType}.${systemKey}`;
25707ac75b1Sopenharmony_ci      if (NATIVE_MODULE.has(systemModule)) {
25807ac75b1Sopenharmony_ci        return `@native:${systemModule}`;
25907ac75b1Sopenharmony_ci      } else if (moduleType === ARKTS_MODULE_NAME) {
26007ac75b1Sopenharmony_ci        // @arkts.xxx -> @ohos:arkts.xxx
26107ac75b1Sopenharmony_ci        return `@ohos:${systemModule}`;
26207ac75b1Sopenharmony_ci      } else {
26307ac75b1Sopenharmony_ci        return `@ohos:${systemKey}`;
26407ac75b1Sopenharmony_ci      };
26507ac75b1Sopenharmony_ci    });
26607ac75b1Sopenharmony_ci  }
26707ac75b1Sopenharmony_ci  if (REG_LIB_SO.test(moduleRequest.trim())) {
26807ac75b1Sopenharmony_ci    if (useNormalizedOHMUrl) {
26907ac75b1Sopenharmony_ci      const pkgInfo = config.pkgContextInfo[moduleRequest];
27007ac75b1Sopenharmony_ci      if (pkgInfo === undefined) {
27107ac75b1Sopenharmony_ci        logger?.error(red, `ArkTS:INTERNAL ERROR: Can not get pkgContextInfo of package '${moduleRequest}' ` +
27207ac75b1Sopenharmony_ci          `which being imported by '${importerFile}'`, reset);
27307ac75b1Sopenharmony_ci      }
27407ac75b1Sopenharmony_ci      const isSo = pkgInfo.isSO ? 'Y' : 'N';
27507ac75b1Sopenharmony_ci      return `@normalized:${isSo}&${pkgInfo.moduleName}&${pkgInfo.bundleName}&${moduleRequest}&${pkgInfo.version}`;
27607ac75b1Sopenharmony_ci    }
27707ac75b1Sopenharmony_ci    return moduleRequest.replace(REG_LIB_SO, (_, libsoKey) => {
27807ac75b1Sopenharmony_ci      return `@app:${projectConfig.bundleName}/${projectConfig.moduleName}/${libsoKey}`;
27907ac75b1Sopenharmony_ci    });
28007ac75b1Sopenharmony_ci  }
28107ac75b1Sopenharmony_ci  return undefined;
28207ac75b1Sopenharmony_ci}
28307ac75b1Sopenharmony_ci
28407ac75b1Sopenharmony_ciexport function genSourceMapFileName(temporaryFile: string): string {
28507ac75b1Sopenharmony_ci  let abcFile: string = temporaryFile;
28607ac75b1Sopenharmony_ci  if (temporaryFile.endsWith(EXTNAME_TS)) {
28707ac75b1Sopenharmony_ci    abcFile = temporaryFile.replace(/\.ts$/, EXTNAME_TS_MAP);
28807ac75b1Sopenharmony_ci  } else {
28907ac75b1Sopenharmony_ci    abcFile = temporaryFile.replace(/\.js$/, EXTNAME_JS_MAP);
29007ac75b1Sopenharmony_ci  }
29107ac75b1Sopenharmony_ci  return abcFile;
29207ac75b1Sopenharmony_ci}
29307ac75b1Sopenharmony_ci
29407ac75b1Sopenharmony_ciexport function getBuildModeInLowerCase(projectConfig: Object): string {
29507ac75b1Sopenharmony_ci  return (compileToolIsRollUp() ? projectConfig.buildMode : projectConfig.buildArkMode).toLowerCase();
29607ac75b1Sopenharmony_ci}
29707ac75b1Sopenharmony_ci
29807ac75b1Sopenharmony_ci/**
29907ac75b1Sopenharmony_ci * This Api only used by webpack compiling process - js-loader
30007ac75b1Sopenharmony_ci * @param sourcePath The path in build cache dir
30107ac75b1Sopenharmony_ci * @param sourceCode The intermediate js source code
30207ac75b1Sopenharmony_ci */
30307ac75b1Sopenharmony_ciexport function writeFileSyncByString(sourcePath: string, sourceCode: string, projectConfig: Object, logger: Object): void {
30407ac75b1Sopenharmony_ci  const filePath: string = genTemporaryPath(sourcePath, projectConfig.projectPath, process.env.cachePath,
30507ac75b1Sopenharmony_ci    projectConfig, undefined);
30607ac75b1Sopenharmony_ci  if (filePath.length === 0) {
30707ac75b1Sopenharmony_ci    return;
30807ac75b1Sopenharmony_ci  }
30907ac75b1Sopenharmony_ci  mkdirsSync(path.dirname(filePath));
31007ac75b1Sopenharmony_ci  if (/\.js$/.test(sourcePath)) {
31107ac75b1Sopenharmony_ci    sourceCode = transformModuleSpecifier(sourcePath, sourceCode, projectConfig);
31207ac75b1Sopenharmony_ci    if (projectConfig.buildArkMode === 'debug') {
31307ac75b1Sopenharmony_ci      fs.writeFileSync(filePath, sourceCode);
31407ac75b1Sopenharmony_ci      return;
31507ac75b1Sopenharmony_ci    }
31607ac75b1Sopenharmony_ci    writeObfuscatedSourceCode({content: sourceCode, buildFilePath: filePath, relativeSourceFilePath: ''},
31707ac75b1Sopenharmony_ci      logger, projectConfig);
31807ac75b1Sopenharmony_ci  }
31907ac75b1Sopenharmony_ci  if (/\.json$/.test(sourcePath)) {
32007ac75b1Sopenharmony_ci    fs.writeFileSync(filePath, sourceCode);
32107ac75b1Sopenharmony_ci  }
32207ac75b1Sopenharmony_ci}
32307ac75b1Sopenharmony_ci
32407ac75b1Sopenharmony_ciexport function transformModuleSpecifier(sourcePath: string, sourceCode: string, projectConfig: Object): string {
32507ac75b1Sopenharmony_ci  // replace relative moduleSpecifier with ohmURl
32607ac75b1Sopenharmony_ci  const REG_RELATIVE_DEPENDENCY: RegExp = /(?:import|from)(?:\s*)['"]((?:\.\/|\.\.\/)[^'"]+|(?:\.\/?|\.\.\/?))['"]/g;
32707ac75b1Sopenharmony_ci  const REG_HAR_DEPENDENCY: RegExp = /(?:import|from)(?:\s*)['"]([^\.\/][^'"]+)['"]/g;
32807ac75b1Sopenharmony_ci  // replace requireNapi and requireNativeModule with import
32907ac75b1Sopenharmony_ci  const REG_REQUIRE_NATIVE_MODULE: RegExp = /var (\S+) = globalThis.requireNativeModule\(['"](\S+)['"]\);/g;
33007ac75b1Sopenharmony_ci  const REG_REQUIRE_NAPI_APP: RegExp = /var (\S+) = globalThis.requireNapi\(['"](\S+)['"], true, ['"](\S+)['"]\);/g;
33107ac75b1Sopenharmony_ci  const REG_REQUIRE_NAPI_OHOS: RegExp = /var (\S+) = globalThis.requireNapi\(['"](\S+)['"]\);/g;
33207ac75b1Sopenharmony_ci
33307ac75b1Sopenharmony_ci  return sourceCode.replace(REG_HAR_DEPENDENCY, (item, moduleRequest) => {
33407ac75b1Sopenharmony_ci    return replaceHarDependency(item, moduleRequest, projectConfig);
33507ac75b1Sopenharmony_ci  }).replace(REG_RELATIVE_DEPENDENCY, (item, moduleRequest) => {
33607ac75b1Sopenharmony_ci    return replaceRelativeDependency(item, moduleRequest, toUnixPath(sourcePath), projectConfig);
33707ac75b1Sopenharmony_ci  }).replace(REG_REQUIRE_NATIVE_MODULE, (_, moduleRequest, moduleName) => {
33807ac75b1Sopenharmony_ci    return `import ${moduleRequest} from '@native:${moduleName}';`;
33907ac75b1Sopenharmony_ci  }).replace(REG_REQUIRE_NAPI_APP, (_, moduleRequest, soName, moudlePath) => {
34007ac75b1Sopenharmony_ci    return `import ${moduleRequest} from '@app:${moudlePath}/${soName}';`;
34107ac75b1Sopenharmony_ci  }).replace(REG_REQUIRE_NAPI_OHOS, (_, moduleRequest, moduleName) => {
34207ac75b1Sopenharmony_ci    return `import ${moduleRequest} from '@ohos:${moduleName}';`;
34307ac75b1Sopenharmony_ci  });
34407ac75b1Sopenharmony_ci}
34507ac75b1Sopenharmony_ci
34607ac75b1Sopenharmony_cifunction removeSuffix(filePath: string): string {
34707ac75b1Sopenharmony_ci  const SUFFIX_REG = /\.(?:d\.)?(ets|ts|mjs|cjs|js)$/;
34807ac75b1Sopenharmony_ci  return filePath.split(path.sep).join('/').replace(SUFFIX_REG, '');
34907ac75b1Sopenharmony_ci}
35007ac75b1Sopenharmony_ci
35107ac75b1Sopenharmony_ciexport function getNormalizedOhmUrlByAliasName(aliasName: string, projectConfig: Object,
35207ac75b1Sopenharmony_ci  logger?: Object, filePath?: string): string {
35307ac75b1Sopenharmony_ci  let pkgName: string = aliasName;
35407ac75b1Sopenharmony_ci  const aliasPkgNameMap: Map<string, string> = projectConfig.dependencyAliasMap;
35507ac75b1Sopenharmony_ci  if (aliasPkgNameMap.has(aliasName)) {
35607ac75b1Sopenharmony_ci    pkgName = aliasPkgNameMap.get(aliasName);
35707ac75b1Sopenharmony_ci  }
35807ac75b1Sopenharmony_ci  const pkgInfo: Object = projectConfig.pkgContextInfo[pkgName];
35907ac75b1Sopenharmony_ci  if (!pkgInfo) {
36007ac75b1Sopenharmony_ci    logger.error(red, `ArkTS:INTERNAL ERROR: Failed to find package '${pkgName}'.\n` +
36107ac75b1Sopenharmony_ci      `Error Message: Failed to obtain package '${pkgName}' from the package context information.`, reset);
36207ac75b1Sopenharmony_ci  }
36307ac75b1Sopenharmony_ci  let normalizedPath: string = '';
36407ac75b1Sopenharmony_ci  if (!filePath) {
36507ac75b1Sopenharmony_ci    if (!pkgInfo.entryPath) {
36607ac75b1Sopenharmony_ci      logger.error(red, `ArkTS:INTERNAL ERROR: Failed to find entry file of '${pkgName}'.\n` +
36707ac75b1Sopenharmony_ci        `Error Message: Failed to obtain the entry file information of '${pkgName}' from the package context information.`, reset);
36807ac75b1Sopenharmony_ci    }
36907ac75b1Sopenharmony_ci    normalizedPath = `${pkgName}/${toUnixPath(pkgInfo.entryPath)}`;
37007ac75b1Sopenharmony_ci    normalizedPath = removeSuffix(normalizedPath);
37107ac75b1Sopenharmony_ci  } else {
37207ac75b1Sopenharmony_ci    const relativePath = toUnixPath(filePath).replace(aliasName, '');
37307ac75b1Sopenharmony_ci    normalizedPath = `${pkgName}${relativePath}`;
37407ac75b1Sopenharmony_ci  }
37507ac75b1Sopenharmony_ci  const isSo = pkgInfo.isSO ? 'Y' : 'N';
37607ac75b1Sopenharmony_ci  return `@normalized:${isSo}&${pkgInfo.moduleName}&${pkgInfo.bundleName}&${normalizedPath}&${pkgInfo.version}`;
37707ac75b1Sopenharmony_ci}
37807ac75b1Sopenharmony_ci
37907ac75b1Sopenharmony_ciexport function getOhmUrlByByteCodeHar(moduleRequest: string, projectConfig: Object, logger?: Object):
38007ac75b1Sopenharmony_ci  string | undefined {
38107ac75b1Sopenharmony_ci  if (projectConfig.byteCodeHarInfo) {
38207ac75b1Sopenharmony_ci    if (Object.prototype.hasOwnProperty.call(projectConfig.byteCodeHarInfo, moduleRequest)) {
38307ac75b1Sopenharmony_ci      return getNormalizedOhmUrlByAliasName(moduleRequest, projectConfig, logger);
38407ac75b1Sopenharmony_ci    }
38507ac75b1Sopenharmony_ci    for (const byteCodeHarName in projectConfig.byteCodeHarInfo) {
38607ac75b1Sopenharmony_ci      if (moduleRequest.startsWith(byteCodeHarName + '/')) {
38707ac75b1Sopenharmony_ci        return getNormalizedOhmUrlByAliasName(byteCodeHarName, projectConfig, logger, moduleRequest);
38807ac75b1Sopenharmony_ci      }
38907ac75b1Sopenharmony_ci    }
39007ac75b1Sopenharmony_ci  }
39107ac75b1Sopenharmony_ci  return undefined;
39207ac75b1Sopenharmony_ci}
39307ac75b1Sopenharmony_ci
39407ac75b1Sopenharmony_ciexport function getOhmUrlByExternalPackage(moduleRequest: string, projectConfig: Object, logger?: Object,
39507ac75b1Sopenharmony_ci  useNormalizedOHMUrl: boolean = false): string | undefined {
39607ac75b1Sopenharmony_ci  // The externalPkgMap store the ohmurl with the alias of hsp package and the hars depended on bytecode har.
39707ac75b1Sopenharmony_ci  let externalPkgMap: Object = Object.assign({}, projectConfig.hspNameOhmMap, projectConfig.harNameOhmMap);
39807ac75b1Sopenharmony_ci  if (Object.keys(externalPkgMap).length !== 0) {
39907ac75b1Sopenharmony_ci    if (Object.prototype.hasOwnProperty.call(externalPkgMap, moduleRequest)) {
40007ac75b1Sopenharmony_ci      if (useNormalizedOHMUrl) {
40107ac75b1Sopenharmony_ci        return getNormalizedOhmUrlByAliasName(moduleRequest, projectConfig, logger);
40207ac75b1Sopenharmony_ci      }
40307ac75b1Sopenharmony_ci      // case1: "@ohos/lib" ---> "@bundle:bundleName/lib/ets/index"
40407ac75b1Sopenharmony_ci      return externalPkgMap[moduleRequest];
40507ac75b1Sopenharmony_ci    }
40607ac75b1Sopenharmony_ci
40707ac75b1Sopenharmony_ci    for (const externalPkgName in externalPkgMap) {
40807ac75b1Sopenharmony_ci      if (moduleRequest.startsWith(externalPkgName + '/')) {
40907ac75b1Sopenharmony_ci        if (useNormalizedOHMUrl) {
41007ac75b1Sopenharmony_ci          return getNormalizedOhmUrlByAliasName(externalPkgName, projectConfig, logger, moduleRequest);
41107ac75b1Sopenharmony_ci        }
41207ac75b1Sopenharmony_ci        // case2: "@ohos/lib/src/main/ets/pages/page1" ---> "@bundle:bundleName/lib/ets/pages/page1"
41307ac75b1Sopenharmony_ci        const idx: number = externalPkgMap[externalPkgName].split('/', 2).join('/').length;
41407ac75b1Sopenharmony_ci        const ohmName: string = externalPkgMap[externalPkgName].substring(0, idx);
41507ac75b1Sopenharmony_ci        if (moduleRequest.indexOf(externalPkgName + '/' + SRC_MAIN) === 0) {
41607ac75b1Sopenharmony_ci          return moduleRequest.replace(externalPkgName + '/' + SRC_MAIN, ohmName);
41707ac75b1Sopenharmony_ci        } else {
41807ac75b1Sopenharmony_ci          return moduleRequest.replace(externalPkgName, ohmName);
41907ac75b1Sopenharmony_ci        }
42007ac75b1Sopenharmony_ci      }
42107ac75b1Sopenharmony_ci    }
42207ac75b1Sopenharmony_ci  }
42307ac75b1Sopenharmony_ci  return undefined;
42407ac75b1Sopenharmony_ci}
42507ac75b1Sopenharmony_ci
42607ac75b1Sopenharmony_cifunction replaceHarDependency(item: string, moduleRequest: string, projectConfig: Object): string {
42707ac75b1Sopenharmony_ci  const hspOhmUrl: string | undefined = getOhmUrlByExternalPackage(moduleRequest, projectConfig);
42807ac75b1Sopenharmony_ci  if (hspOhmUrl !== undefined) {
42907ac75b1Sopenharmony_ci    return item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => {
43007ac75b1Sopenharmony_ci      return quotation + hspOhmUrl + quotation;
43107ac75b1Sopenharmony_ci    });
43207ac75b1Sopenharmony_ci  }
43307ac75b1Sopenharmony_ci  return item;
43407ac75b1Sopenharmony_ci}
43507ac75b1Sopenharmony_ci
43607ac75b1Sopenharmony_cifunction locateActualFilePathWithModuleRequest(absolutePath: string): string {
43707ac75b1Sopenharmony_ci  if (!fs.existsSync(absolutePath) || !fs.statSync(absolutePath).isDirectory()) {
43807ac75b1Sopenharmony_ci    return absolutePath;
43907ac75b1Sopenharmony_ci  }
44007ac75b1Sopenharmony_ci
44107ac75b1Sopenharmony_ci  const filePath: string = absolutePath + getExtensionIfUnfullySpecifiedFilepath(absolutePath);
44207ac75b1Sopenharmony_ci  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
44307ac75b1Sopenharmony_ci    return absolutePath;
44407ac75b1Sopenharmony_ci  }
44507ac75b1Sopenharmony_ci
44607ac75b1Sopenharmony_ci  return path.join(absolutePath, 'index');
44707ac75b1Sopenharmony_ci}
44807ac75b1Sopenharmony_ci
44907ac75b1Sopenharmony_cifunction replaceRelativeDependency(item: string, moduleRequest: string, sourcePath: string, projectConfig: Object): string {
45007ac75b1Sopenharmony_ci  if (sourcePath && projectConfig.compileMode === ESMODULE) {
45107ac75b1Sopenharmony_ci    // remove file extension from moduleRequest
45207ac75b1Sopenharmony_ci    const SUFFIX_REG: RegExp = /\.(?:[cm]?js|[e]?ts|json)$/;
45307ac75b1Sopenharmony_ci    moduleRequest = moduleRequest.replace(SUFFIX_REG, '');
45407ac75b1Sopenharmony_ci
45507ac75b1Sopenharmony_ci    // normalize the moduleRequest
45607ac75b1Sopenharmony_ci    item = item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => {
45707ac75b1Sopenharmony_ci      let normalizedModuleRequest: string = toUnixPath(path.normalize(moduleRequest));
45807ac75b1Sopenharmony_ci      if (moduleRequest.startsWith('./')) {
45907ac75b1Sopenharmony_ci        normalizedModuleRequest = './' + normalizedModuleRequest;
46007ac75b1Sopenharmony_ci      }
46107ac75b1Sopenharmony_ci      return quotation + normalizedModuleRequest + quotation;
46207ac75b1Sopenharmony_ci    });
46307ac75b1Sopenharmony_ci
46407ac75b1Sopenharmony_ci    const filePath: string =
46507ac75b1Sopenharmony_ci      locateActualFilePathWithModuleRequest(path.resolve(path.dirname(sourcePath), moduleRequest));
46607ac75b1Sopenharmony_ci    const result: RegExpMatchArray | null =
46707ac75b1Sopenharmony_ci      filePath.match(/(\S+)(\/|\\)src(\/|\\)(?:main|ohosTest)(\/|\\)(ets|js)(\/|\\)(\S+)/);
46807ac75b1Sopenharmony_ci    if (result && projectConfig.aceModuleJsonPath) {
46907ac75b1Sopenharmony_ci      const npmModuleIdx: number = result[1].search(/(\/|\\)node_modules(\/|\\)/);
47007ac75b1Sopenharmony_ci      const projectRootPath: string = projectConfig.projectRootPath;
47107ac75b1Sopenharmony_ci      if (npmModuleIdx === -1 || npmModuleIdx === projectRootPath.search(/(\/|\\)node_modules(\/|\\)/)) {
47207ac75b1Sopenharmony_ci        const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath);
47307ac75b1Sopenharmony_ci        const bundleName: string = packageInfo[0];
47407ac75b1Sopenharmony_ci        const moduleName: string = packageInfo[1];
47507ac75b1Sopenharmony_ci        moduleRequest = `@bundle:${bundleName}/${moduleName}/${result[5]}/${toUnixPath(result[7])}`;
47607ac75b1Sopenharmony_ci        item = item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => {
47707ac75b1Sopenharmony_ci          return quotation + moduleRequest + quotation;
47807ac75b1Sopenharmony_ci        });
47907ac75b1Sopenharmony_ci      }
48007ac75b1Sopenharmony_ci    }
48107ac75b1Sopenharmony_ci  }
48207ac75b1Sopenharmony_ci  return item;
48307ac75b1Sopenharmony_ci}
48407ac75b1Sopenharmony_ci
48507ac75b1Sopenharmony_ciinterface ModuleInfo {
48607ac75b1Sopenharmony_ci  content: string,
48707ac75b1Sopenharmony_ci  /**
48807ac75b1Sopenharmony_ci   * the path in build cache dir
48907ac75b1Sopenharmony_ci   */
49007ac75b1Sopenharmony_ci  buildFilePath: string,
49107ac75b1Sopenharmony_ci  /**
49207ac75b1Sopenharmony_ci   * the `originSourceFilePath` relative to project root dir.
49307ac75b1Sopenharmony_ci   */
49407ac75b1Sopenharmony_ci  relativeSourceFilePath: string,
49507ac75b1Sopenharmony_ci  /**
49607ac75b1Sopenharmony_ci   * the origin source file path will be set with rollup moduleId when obfuscate intermediate js source code,
49707ac75b1Sopenharmony_ci   * whereas be set with tsc node.fileName when obfuscate intermediate ts source code.
49807ac75b1Sopenharmony_ci   */
49907ac75b1Sopenharmony_ci  originSourceFilePath?: string,
50007ac75b1Sopenharmony_ci  rollupModuleId?: string
50107ac75b1Sopenharmony_ci}
50207ac75b1Sopenharmony_ci
50307ac75b1Sopenharmony_ciexport async function writeObfuscatedSourceCode(moduleInfo: ModuleInfo, logger: Object,
50407ac75b1Sopenharmony_ci  projectConfig: Object, rollupNewSourceMaps: Object = {}): Promise<void> {
50507ac75b1Sopenharmony_ci  if (compileToolIsRollUp() && projectConfig.arkObfuscator) {
50607ac75b1Sopenharmony_ci    MemoryUtils.tryGC();
50707ac75b1Sopenharmony_ci    performancePrinter?.filesPrinter?.startEvent(moduleInfo.buildFilePath);
50807ac75b1Sopenharmony_ci    await writeArkguardObfuscatedSourceCode(moduleInfo, logger, projectConfig, rollupNewSourceMaps);
50907ac75b1Sopenharmony_ci    performancePrinter?.filesPrinter?.endEvent(moduleInfo.buildFilePath, undefined, true);
51007ac75b1Sopenharmony_ci    MemoryUtils.tryGC();
51107ac75b1Sopenharmony_ci    return;
51207ac75b1Sopenharmony_ci  }
51307ac75b1Sopenharmony_ci  mkdirsSync(path.dirname(moduleInfo.buildFilePath));
51407ac75b1Sopenharmony_ci  if (!compileToolIsRollUp()) {
51507ac75b1Sopenharmony_ci    await writeMinimizedSourceCode(moduleInfo.content, moduleInfo.buildFilePath, logger, projectConfig.compileHar);
51607ac75b1Sopenharmony_ci    return;
51707ac75b1Sopenharmony_ci  }
51807ac75b1Sopenharmony_ci
51907ac75b1Sopenharmony_ci  if (moduleInfo.originSourceFilePath) {
52007ac75b1Sopenharmony_ci    const originSourceFilePath = toUnixPath(moduleInfo.originSourceFilePath);
52107ac75b1Sopenharmony_ci    let genFileInHar: GeneratedFileInHar = harFilesRecord.get(originSourceFilePath);
52207ac75b1Sopenharmony_ci
52307ac75b1Sopenharmony_ci    if (!genFileInHar) {
52407ac75b1Sopenharmony_ci      genFileInHar = { sourcePath: originSourceFilePath };
52507ac75b1Sopenharmony_ci    }
52607ac75b1Sopenharmony_ci    if (!genFileInHar.sourceCachePath) {
52707ac75b1Sopenharmony_ci      genFileInHar.sourceCachePath = toUnixPath(moduleInfo.buildFilePath);
52807ac75b1Sopenharmony_ci    }
52907ac75b1Sopenharmony_ci    harFilesRecord.set(originSourceFilePath, genFileInHar);
53007ac75b1Sopenharmony_ci  }
53107ac75b1Sopenharmony_ci
53207ac75b1Sopenharmony_ci  fs.writeFileSync(moduleInfo.buildFilePath, moduleInfo.content);
53307ac75b1Sopenharmony_ci}
53407ac75b1Sopenharmony_ci
53507ac75b1Sopenharmony_ci/**
53607ac75b1Sopenharmony_ci * This Api only be used by rollup compiling process & only be
53707ac75b1Sopenharmony_ci * exported for unit test.
53807ac75b1Sopenharmony_ci */
53907ac75b1Sopenharmony_ciexport async function writeArkguardObfuscatedSourceCode(moduleInfo: ModuleInfo, logger: Object,
54007ac75b1Sopenharmony_ci  projectConfig: Object, rollupNewSourceMaps: Object = {}): Promise<void> {
54107ac75b1Sopenharmony_ci  const arkObfuscator = projectConfig.arkObfuscator;
54207ac75b1Sopenharmony_ci  const isDeclaration = (/\.d\.e?ts$/).test(moduleInfo.buildFilePath);
54307ac75b1Sopenharmony_ci  const packageDir = projectConfig.packageDir;
54407ac75b1Sopenharmony_ci  const projectRootPath = projectConfig.projectRootPath;
54507ac75b1Sopenharmony_ci  const useNormalized = projectConfig.useNormalizedOHMUrl;
54607ac75b1Sopenharmony_ci  const localPackageSet = projectConfig.localPackageSet;
54707ac75b1Sopenharmony_ci  const useTsHar = projectConfig.useTsHar;
54807ac75b1Sopenharmony_ci  const sourceMapGeneratorInstance = SourceMapGenerator.getInstance();
54907ac75b1Sopenharmony_ci
55007ac75b1Sopenharmony_ci  let previousStageSourceMap: sourceMap.RawSourceMap | undefined = undefined;
55107ac75b1Sopenharmony_ci  if (moduleInfo.relativeSourceFilePath.length > 0 && !isDeclaration) {
55207ac75b1Sopenharmony_ci    const selectedFilePath = sourceMapGeneratorInstance.isNewSourceMaps() ? moduleInfo.rollupModuleId! : moduleInfo.relativeSourceFilePath;
55307ac75b1Sopenharmony_ci    previousStageSourceMap = sourceMapGeneratorInstance.getSpecifySourceMap(rollupNewSourceMaps, selectedFilePath) as sourceMap.RawSourceMap;
55407ac75b1Sopenharmony_ci  }
55507ac75b1Sopenharmony_ci
55607ac75b1Sopenharmony_ci  let historyNameCache = new Map<string, string>();
55707ac75b1Sopenharmony_ci  let namecachePath = moduleInfo.relativeSourceFilePath;
55807ac75b1Sopenharmony_ci  if (isDeclaration) {
55907ac75b1Sopenharmony_ci    namecachePath = getRelativeSourcePath(moduleInfo.originSourceFilePath, projectRootPath,
56007ac75b1Sopenharmony_ci      sourceFileBelongProject.get(toUnixPath(moduleInfo.originSourceFilePath)));
56107ac75b1Sopenharmony_ci  }
56207ac75b1Sopenharmony_ci  if (nameCacheMap) {
56307ac75b1Sopenharmony_ci    let identifierCache = nameCacheMap.get(namecachePath)?.[IDENTIFIER_CACHE];
56407ac75b1Sopenharmony_ci    deleteLineInfoForNameString(historyNameCache, identifierCache);
56507ac75b1Sopenharmony_ci  }
56607ac75b1Sopenharmony_ci
56707ac75b1Sopenharmony_ci  let mixedInfo: { content: string, sourceMap?: Object, nameCache?: Object, unobfuscationNameMap?: Map<string, Set<string>>};
56807ac75b1Sopenharmony_ci  let projectInfo: {
56907ac75b1Sopenharmony_ci    packageDir: string,
57007ac75b1Sopenharmony_ci    projectRootPath: string,
57107ac75b1Sopenharmony_ci    localPackageSet: Set<string>,
57207ac75b1Sopenharmony_ci    useNormalized: boolean,
57307ac75b1Sopenharmony_ci    useTsHar: boolean
57407ac75b1Sopenharmony_ci  } = { packageDir, projectRootPath, localPackageSet, useNormalized, useTsHar };
57507ac75b1Sopenharmony_ci  let filePathObj = { buildFilePath: moduleInfo.buildFilePath, relativeFilePath: moduleInfo.relativeSourceFilePath };
57607ac75b1Sopenharmony_ci  try {
57707ac75b1Sopenharmony_ci    mixedInfo = await arkObfuscator.obfuscate(moduleInfo.content, filePathObj, previousStageSourceMap,
57807ac75b1Sopenharmony_ci      historyNameCache, moduleInfo.originSourceFilePath, projectInfo);
57907ac75b1Sopenharmony_ci  } catch (err) {
58007ac75b1Sopenharmony_ci    logger.error(red, `ArkTS:INTERNAL ERROR: Failed to obfuscate file '${moduleInfo.relativeSourceFilePath}' with arkguard. ${err}`);
58107ac75b1Sopenharmony_ci  }
58207ac75b1Sopenharmony_ci
58307ac75b1Sopenharmony_ci  if (mixedInfo.sourceMap && !isDeclaration) {
58407ac75b1Sopenharmony_ci    const selectedFilePath = sourceMapGeneratorInstance.isNewSourceMaps() ? moduleInfo.rollupModuleId! : moduleInfo.relativeSourceFilePath;
58507ac75b1Sopenharmony_ci    mixedInfo.sourceMap.sources = [moduleInfo.relativeSourceFilePath];
58607ac75b1Sopenharmony_ci    sourceMapGeneratorInstance.fillSourceMapPackageInfo(moduleInfo.rollupModuleId!, mixedInfo.sourceMap);
58707ac75b1Sopenharmony_ci    sourceMapGeneratorInstance.updateSpecifySourceMap(rollupNewSourceMaps, selectedFilePath, mixedInfo.sourceMap);
58807ac75b1Sopenharmony_ci  }
58907ac75b1Sopenharmony_ci
59007ac75b1Sopenharmony_ci  if (mixedInfo.nameCache && !isDeclaration) {
59107ac75b1Sopenharmony_ci    let obfName: string = moduleInfo.relativeSourceFilePath;
59207ac75b1Sopenharmony_ci    let isOhModule = isPackageModulesFile(moduleInfo.originSourceFilePath, projectConfig);
59307ac75b1Sopenharmony_ci    if (projectConfig.obfuscationMergedObConfig?.options.enableFileNameObfuscation && !isOhModule) {
59407ac75b1Sopenharmony_ci      obfName = mangleFilePath(moduleInfo.relativeSourceFilePath);
59507ac75b1Sopenharmony_ci    }
59607ac75b1Sopenharmony_ci    mixedInfo.nameCache.obfName = obfName;
59707ac75b1Sopenharmony_ci    nameCacheMap.set(moduleInfo.relativeSourceFilePath, mixedInfo.nameCache);
59807ac75b1Sopenharmony_ci  }
59907ac75b1Sopenharmony_ci
60007ac75b1Sopenharmony_ci  if (mixedInfo.unobfuscationNameMap && !isDeclaration) {
60107ac75b1Sopenharmony_ci    let arrayObject: Record<string, string[]> = {};
60207ac75b1Sopenharmony_ci    // The type of unobfuscationNameMap's value is Set, convert Set to Array.
60307ac75b1Sopenharmony_ci    mixedInfo.unobfuscationNameMap.forEach((value: Set<string>, key: string) => {
60407ac75b1Sopenharmony_ci      let array: string[] = Array.from(value);
60507ac75b1Sopenharmony_ci      arrayObject[key] = array;
60607ac75b1Sopenharmony_ci    });
60707ac75b1Sopenharmony_ci    unobfuscationNamesObj[moduleInfo.relativeSourceFilePath] = arrayObject;
60807ac75b1Sopenharmony_ci  }
60907ac75b1Sopenharmony_ci
61007ac75b1Sopenharmony_ci  const newFilePath: string = tryMangleFileName(moduleInfo.buildFilePath, projectConfig, moduleInfo.originSourceFilePath);
61107ac75b1Sopenharmony_ci  if (newFilePath !== moduleInfo.buildFilePath && !isDeclaration) {
61207ac75b1Sopenharmony_ci    sourceMapGeneratorInstance.saveKeyMappingForObfFileName(moduleInfo.rollupModuleId!);
61307ac75b1Sopenharmony_ci  }
61407ac75b1Sopenharmony_ci  mkdirsSync(path.dirname(newFilePath));
61507ac75b1Sopenharmony_ci  fs.writeFileSync(newFilePath, mixedInfo.content ?? '');
61607ac75b1Sopenharmony_ci}
61707ac75b1Sopenharmony_ci
61807ac75b1Sopenharmony_ciexport function tryMangleFileName(filePath: string, projectConfig: Object, originalFilePath: string): string {
61907ac75b1Sopenharmony_ci  originalFilePath = toUnixPath(originalFilePath);
62007ac75b1Sopenharmony_ci  let isOhModule = isPackageModulesFile(originalFilePath, projectConfig);
62107ac75b1Sopenharmony_ci  let genFileInHar: GeneratedFileInHar = harFilesRecord.get(originalFilePath);
62207ac75b1Sopenharmony_ci  if (!genFileInHar) {
62307ac75b1Sopenharmony_ci    genFileInHar = { sourcePath: originalFilePath };
62407ac75b1Sopenharmony_ci    harFilesRecord.set(originalFilePath, genFileInHar);
62507ac75b1Sopenharmony_ci  }
62607ac75b1Sopenharmony_ci
62707ac75b1Sopenharmony_ci  if (projectConfig.obfuscationMergedObConfig?.options?.enableFileNameObfuscation && !isOhModule) {
62807ac75b1Sopenharmony_ci    const mangledFilePath: string = mangleFilePath(filePath);
62907ac75b1Sopenharmony_ci    if ((/\.d\.e?ts$/).test(filePath)) {
63007ac75b1Sopenharmony_ci      genFileInHar.obfuscatedDeclarationCachePath = mangledFilePath;
63107ac75b1Sopenharmony_ci    } else {
63207ac75b1Sopenharmony_ci      genFileInHar.obfuscatedSourceCachePath = mangledFilePath;
63307ac75b1Sopenharmony_ci    }
63407ac75b1Sopenharmony_ci    filePath = mangledFilePath;
63507ac75b1Sopenharmony_ci  } else if (!(/\.d\.e?ts$/).test(filePath)) {
63607ac75b1Sopenharmony_ci    genFileInHar.sourceCachePath = filePath;
63707ac75b1Sopenharmony_ci  }
63807ac75b1Sopenharmony_ci  return filePath;
63907ac75b1Sopenharmony_ci}
64007ac75b1Sopenharmony_ci
64107ac75b1Sopenharmony_ciexport async function mangleDeclarationFileName(logger: Object, projectConfig: Object,
64207ac75b1Sopenharmony_ci  sourceFileBelongProject: Map<string, string>): Promise<void> {
64307ac75b1Sopenharmony_ci  for (const [sourcePath, genFilesInHar] of harFilesRecord) {
64407ac75b1Sopenharmony_ci    if (genFilesInHar.originalDeclarationCachePath && genFilesInHar.originalDeclarationContent) {
64507ac75b1Sopenharmony_ci      let filePath = genFilesInHar.originalDeclarationCachePath;
64607ac75b1Sopenharmony_ci      let relativeSourceFilePath = getRelativeSourcePath(filePath,
64707ac75b1Sopenharmony_ci         projectConfig.projectRootPath, sourceFileBelongProject.get(toUnixPath(filePath)));
64807ac75b1Sopenharmony_ci      await writeObfuscatedSourceCode({
64907ac75b1Sopenharmony_ci          content: genFilesInHar.originalDeclarationContent,
65007ac75b1Sopenharmony_ci          buildFilePath: genFilesInHar.originalDeclarationCachePath,
65107ac75b1Sopenharmony_ci          relativeSourceFilePath: relativeSourceFilePath,
65207ac75b1Sopenharmony_ci          originSourceFilePath: sourcePath
65307ac75b1Sopenharmony_ci        }, logger, projectConfig, {});
65407ac75b1Sopenharmony_ci    }
65507ac75b1Sopenharmony_ci  }
65607ac75b1Sopenharmony_ci}
65707ac75b1Sopenharmony_ci
65807ac75b1Sopenharmony_ciexport async function writeMinimizedSourceCode(content: string, filePath: string, logger: Object,
65907ac75b1Sopenharmony_ci  isHar: boolean = false): Promise<void> {
66007ac75b1Sopenharmony_ci  let result: MinifyOutput;
66107ac75b1Sopenharmony_ci  try {
66207ac75b1Sopenharmony_ci    const minifyOptions = {
66307ac75b1Sopenharmony_ci      compress: {
66407ac75b1Sopenharmony_ci        join_vars: false,
66507ac75b1Sopenharmony_ci        sequences: 0,
66607ac75b1Sopenharmony_ci        directives: false
66707ac75b1Sopenharmony_ci      }
66807ac75b1Sopenharmony_ci    };
66907ac75b1Sopenharmony_ci    if (!isHar) {
67007ac75b1Sopenharmony_ci      minifyOptions['format'] = {
67107ac75b1Sopenharmony_ci        semicolons: false,
67207ac75b1Sopenharmony_ci        beautify: true,
67307ac75b1Sopenharmony_ci        indent_level: 2
67407ac75b1Sopenharmony_ci      };
67507ac75b1Sopenharmony_ci    }
67607ac75b1Sopenharmony_ci    result = await minify(content, minifyOptions);
67707ac75b1Sopenharmony_ci  } catch {
67807ac75b1Sopenharmony_ci    logger.error(red, `ArkTS:INTERNAL ERROR: Failed to obfuscate source code for ${filePath}`, reset);
67907ac75b1Sopenharmony_ci  }
68007ac75b1Sopenharmony_ci
68107ac75b1Sopenharmony_ci  fs.writeFileSync(filePath, result.code);
68207ac75b1Sopenharmony_ci}
68307ac75b1Sopenharmony_ci
68407ac75b1Sopenharmony_ciexport function genBuildPath(filePath: string, projectPath: string, buildPath: string, projectConfig: Object): string {
68507ac75b1Sopenharmony_ci  filePath = toUnixPath(filePath);
68607ac75b1Sopenharmony_ci  if (filePath.endsWith(EXTNAME_MJS)) {
68707ac75b1Sopenharmony_ci    filePath = filePath.replace(/\.mjs$/, EXTNAME_JS);
68807ac75b1Sopenharmony_ci  }
68907ac75b1Sopenharmony_ci  if (filePath.endsWith(EXTNAME_CJS)) {
69007ac75b1Sopenharmony_ci    filePath = filePath.replace(/\.cjs$/, EXTNAME_JS);
69107ac75b1Sopenharmony_ci  }
69207ac75b1Sopenharmony_ci  projectPath = toUnixPath(projectPath);
69307ac75b1Sopenharmony_ci
69407ac75b1Sopenharmony_ci  if (isPackageModulesFile(filePath, projectConfig)) {
69507ac75b1Sopenharmony_ci    const packageDir: string = projectConfig.packageDir;
69607ac75b1Sopenharmony_ci    const fakePkgModulesPath: string = toUnixPath(path.join(projectConfig.projectRootPath, packageDir));
69707ac75b1Sopenharmony_ci    let output: string = '';
69807ac75b1Sopenharmony_ci    if (filePath.indexOf(fakePkgModulesPath) === -1) {
69907ac75b1Sopenharmony_ci      const hapPath: string = toUnixPath(projectConfig.projectRootPath);
70007ac75b1Sopenharmony_ci      const tempFilePath: string = filePath.replace(hapPath, '');
70107ac75b1Sopenharmony_ci      const sufStr: string = tempFilePath.substring(tempFilePath.indexOf(packageDir) + packageDir.length + 1);
70207ac75b1Sopenharmony_ci      output = path.join(projectConfig.nodeModulesPath, ZERO, sufStr);
70307ac75b1Sopenharmony_ci    } else {
70407ac75b1Sopenharmony_ci      output = filePath.replace(fakePkgModulesPath, path.join(projectConfig.nodeModulesPath, ONE));
70507ac75b1Sopenharmony_ci    }
70607ac75b1Sopenharmony_ci    return output;
70707ac75b1Sopenharmony_ci  }
70807ac75b1Sopenharmony_ci
70907ac75b1Sopenharmony_ci  if (filePath.indexOf(projectPath) !== -1) {
71007ac75b1Sopenharmony_ci    const sufStr: string = filePath.replace(projectPath, '');
71107ac75b1Sopenharmony_ci    const output: string = path.join(buildPath, sufStr);
71207ac75b1Sopenharmony_ci    return output;
71307ac75b1Sopenharmony_ci  }
71407ac75b1Sopenharmony_ci
71507ac75b1Sopenharmony_ci  return '';
71607ac75b1Sopenharmony_ci}
71707ac75b1Sopenharmony_ci
71807ac75b1Sopenharmony_ciexport function getPackageInfo(configFile: string): Array<string> {
71907ac75b1Sopenharmony_ci  if (packageCollection.has(configFile)) {
72007ac75b1Sopenharmony_ci    return packageCollection.get(configFile);
72107ac75b1Sopenharmony_ci  }
72207ac75b1Sopenharmony_ci  const data: Object = JSON.parse(fs.readFileSync(configFile).toString());
72307ac75b1Sopenharmony_ci  const bundleName: string = data.app.bundleName;
72407ac75b1Sopenharmony_ci  const moduleName: string = data.module.name;
72507ac75b1Sopenharmony_ci  packageCollection.set(configFile, [bundleName, moduleName]);
72607ac75b1Sopenharmony_ci  return [bundleName, moduleName];
72707ac75b1Sopenharmony_ci}
72807ac75b1Sopenharmony_ci
72907ac75b1Sopenharmony_ci/**
73007ac75b1Sopenharmony_ci * This Api only used by webpack compiling process - result_process
73107ac75b1Sopenharmony_ci * @param sourcePath The path in build cache dir
73207ac75b1Sopenharmony_ci * @param sourceContent The intermediate js source code
73307ac75b1Sopenharmony_ci */
73407ac75b1Sopenharmony_ciexport function generateSourceFilesToTemporary(sourcePath: string, sourceContent: string, sourceMap: Object,
73507ac75b1Sopenharmony_ci  projectConfig: Object, logger: Object): void {
73607ac75b1Sopenharmony_ci    let jsFilePath: string = genTemporaryPath(sourcePath, projectConfig.projectPath, process.env.cachePath,
73707ac75b1Sopenharmony_ci      projectConfig, undefined);
73807ac75b1Sopenharmony_ci  if (jsFilePath.length === 0) {
73907ac75b1Sopenharmony_ci    return;
74007ac75b1Sopenharmony_ci  }
74107ac75b1Sopenharmony_ci  if (jsFilePath.endsWith(EXTNAME_ETS)) {
74207ac75b1Sopenharmony_ci    jsFilePath = jsFilePath.replace(/\.ets$/, EXTNAME_JS);
74307ac75b1Sopenharmony_ci  } else {
74407ac75b1Sopenharmony_ci    jsFilePath = jsFilePath.replace(/\.ts$/, EXTNAME_JS);
74507ac75b1Sopenharmony_ci  }
74607ac75b1Sopenharmony_ci  let sourceMapFile: string = genSourceMapFileName(jsFilePath);
74707ac75b1Sopenharmony_ci  if (sourceMapFile.length > 0 && projectConfig.buildArkMode === 'debug') {
74807ac75b1Sopenharmony_ci    let source = toUnixPath(sourcePath).replace(toUnixPath(projectConfig.projectRootPath) + '/', '');
74907ac75b1Sopenharmony_ci    // adjust sourceMap info
75007ac75b1Sopenharmony_ci    sourceMap.sources = [source];
75107ac75b1Sopenharmony_ci    sourceMap.file = path.basename(sourceMap.file);
75207ac75b1Sopenharmony_ci    delete sourceMap.sourcesContent;
75307ac75b1Sopenharmony_ci    newSourceMaps[source] = sourceMap;
75407ac75b1Sopenharmony_ci  }
75507ac75b1Sopenharmony_ci  sourceContent = transformModuleSpecifier(sourcePath, sourceContent, projectConfig);
75607ac75b1Sopenharmony_ci
75707ac75b1Sopenharmony_ci  mkdirsSync(path.dirname(jsFilePath));
75807ac75b1Sopenharmony_ci  if (projectConfig.buildArkMode === 'debug') {
75907ac75b1Sopenharmony_ci    fs.writeFileSync(jsFilePath, sourceContent);
76007ac75b1Sopenharmony_ci    return;
76107ac75b1Sopenharmony_ci  }
76207ac75b1Sopenharmony_ci
76307ac75b1Sopenharmony_ci  writeObfuscatedSourceCode({content: sourceContent, buildFilePath: jsFilePath, relativeSourceFilePath: ''},
76407ac75b1Sopenharmony_ci    logger, projectConfig);
76507ac75b1Sopenharmony_ci}
76607ac75b1Sopenharmony_ci
76707ac75b1Sopenharmony_ciexport function genAbcFileName(temporaryFile: string): string {
76807ac75b1Sopenharmony_ci  let abcFile: string = temporaryFile;
76907ac75b1Sopenharmony_ci  if (temporaryFile.endsWith(EXTNAME_TS)) {
77007ac75b1Sopenharmony_ci    abcFile = temporaryFile.replace(/\.ts$/, EXTNAME_ABC);
77107ac75b1Sopenharmony_ci  } else {
77207ac75b1Sopenharmony_ci    abcFile = temporaryFile.replace(/\.js$/, EXTNAME_ABC);
77307ac75b1Sopenharmony_ci  }
77407ac75b1Sopenharmony_ci  return abcFile;
77507ac75b1Sopenharmony_ci}
77607ac75b1Sopenharmony_ci
77707ac75b1Sopenharmony_ciexport function isOhModules(projectConfig: Object): boolean {
77807ac75b1Sopenharmony_ci  return projectConfig.packageDir === OH_MODULES;
77907ac75b1Sopenharmony_ci}
78007ac75b1Sopenharmony_ci
78107ac75b1Sopenharmony_ciexport function isEs2Abc(projectConfig: Object): boolean {
78207ac75b1Sopenharmony_ci  return projectConfig.pandaMode === ES2ABC || projectConfig.pandaMode === 'undefined' ||
78307ac75b1Sopenharmony_ci    projectConfig.pandaMode === undefined;
78407ac75b1Sopenharmony_ci}
78507ac75b1Sopenharmony_ci
78607ac75b1Sopenharmony_ciexport function isTs2Abc(projectConfig: Object): boolean {
78707ac75b1Sopenharmony_ci  return projectConfig.pandaMode === TS2ABC;
78807ac75b1Sopenharmony_ci}
78907ac75b1Sopenharmony_ci
79007ac75b1Sopenharmony_ciexport function genProtoFileName(temporaryFile: string): string {
79107ac75b1Sopenharmony_ci  return temporaryFile.replace(/\.(?:[tj]s|json)$/, EXTNAME_PROTO_BIN);
79207ac75b1Sopenharmony_ci}
79307ac75b1Sopenharmony_ci
79407ac75b1Sopenharmony_ciexport function genMergeProtoFileName(temporaryFile: string): string {
79507ac75b1Sopenharmony_ci  let protoTempPathArr: string[] = temporaryFile.split(TEMPORARY);
79607ac75b1Sopenharmony_ci  const sufStr: string = protoTempPathArr[protoTempPathArr.length - 1];
79707ac75b1Sopenharmony_ci  let protoBuildPath: string = path.join(process.env.cachePath, 'protos', sufStr);
79807ac75b1Sopenharmony_ci
79907ac75b1Sopenharmony_ci  return protoBuildPath;
80007ac75b1Sopenharmony_ci}
80107ac75b1Sopenharmony_ci
80207ac75b1Sopenharmony_ciexport function removeDuplicateInfo(moduleInfos: Array<any>): Array<any> {
80307ac75b1Sopenharmony_ci  const tempModuleInfos: any[] = Array<any>();
80407ac75b1Sopenharmony_ci  moduleInfos.forEach((item) => {
80507ac75b1Sopenharmony_ci    let check: boolean = tempModuleInfos.every((newItem) => {
80607ac75b1Sopenharmony_ci      return item.tempFilePath !== newItem.tempFilePath;
80707ac75b1Sopenharmony_ci    });
80807ac75b1Sopenharmony_ci    if (check) {
80907ac75b1Sopenharmony_ci      tempModuleInfos.push(item);
81007ac75b1Sopenharmony_ci    }
81107ac75b1Sopenharmony_ci  });
81207ac75b1Sopenharmony_ci  moduleInfos = tempModuleInfos;
81307ac75b1Sopenharmony_ci
81407ac75b1Sopenharmony_ci  return moduleInfos;
81507ac75b1Sopenharmony_ci}
81607ac75b1Sopenharmony_ci
81707ac75b1Sopenharmony_ciexport function buildCachePath(tailName: string, projectConfig: Object, logger: Object): string {
81807ac75b1Sopenharmony_ci  let pathName: string = process.env.cachePath !== undefined ?
81907ac75b1Sopenharmony_ci    path.join(projectConfig.cachePath, tailName) : path.join(projectConfig.aceModuleBuild, tailName);
82007ac75b1Sopenharmony_ci  validateFilePathLength(pathName, logger);
82107ac75b1Sopenharmony_ci  return pathName;
82207ac75b1Sopenharmony_ci}
82307ac75b1Sopenharmony_ci
82407ac75b1Sopenharmony_ciexport function getArkBuildDir(arkDir: string): string {
82507ac75b1Sopenharmony_ci  if (isWindows()) {
82607ac75b1Sopenharmony_ci    return path.join(arkDir, 'build-win');
82707ac75b1Sopenharmony_ci  } else if (isMac()) {
82807ac75b1Sopenharmony_ci    return path.join(arkDir, 'build-mac');
82907ac75b1Sopenharmony_ci  } else {
83007ac75b1Sopenharmony_ci    return path.join(arkDir, 'build');
83107ac75b1Sopenharmony_ci  }
83207ac75b1Sopenharmony_ci}
83307ac75b1Sopenharmony_ci
83407ac75b1Sopenharmony_ciexport function getBuildBinDir(arkDir: string): string {
83507ac75b1Sopenharmony_ci  return path.join(getArkBuildDir(arkDir), 'bin');
83607ac75b1Sopenharmony_ci}
83707ac75b1Sopenharmony_ci
83807ac75b1Sopenharmony_ciexport function cleanUpUtilsObjects(): void {
83907ac75b1Sopenharmony_ci  newSourceMaps = {};
84007ac75b1Sopenharmony_ci  nameCacheMap.clear();
84107ac75b1Sopenharmony_ci  packageCollection.clear();
84207ac75b1Sopenharmony_ci}
84307ac75b1Sopenharmony_ci
84407ac75b1Sopenharmony_ciexport function getHookEventFactory(share: Object, pluginName: string, hookName: string): Object {
84507ac75b1Sopenharmony_ci  if (typeof share.getHookEventFactory === 'function') {
84607ac75b1Sopenharmony_ci    return share.getHookEventFactory(pluginName, hookName);
84707ac75b1Sopenharmony_ci  } else {
84807ac75b1Sopenharmony_ci    return undefined;
84907ac75b1Sopenharmony_ci  }
85007ac75b1Sopenharmony_ci}
85107ac75b1Sopenharmony_ci
85207ac75b1Sopenharmony_ciexport function createAndStartEvent(eventOrEventFactory: Object, eventName: string, syncFlag = false): Object {
85307ac75b1Sopenharmony_ci  if (eventOrEventFactory === undefined) {
85407ac75b1Sopenharmony_ci    return undefined;
85507ac75b1Sopenharmony_ci  }
85607ac75b1Sopenharmony_ci  let event: Object;
85707ac75b1Sopenharmony_ci  if (typeof eventOrEventFactory.createSubEvent === 'function') {
85807ac75b1Sopenharmony_ci    event = eventOrEventFactory.createSubEvent(eventName);
85907ac75b1Sopenharmony_ci  } else {
86007ac75b1Sopenharmony_ci    event = eventOrEventFactory.createEvent(eventName);
86107ac75b1Sopenharmony_ci  }
86207ac75b1Sopenharmony_ci  if (typeof event.startAsyncEvent === 'function' && syncFlag) {
86307ac75b1Sopenharmony_ci    event.startAsyncEvent();
86407ac75b1Sopenharmony_ci  } else {
86507ac75b1Sopenharmony_ci    event.start();
86607ac75b1Sopenharmony_ci  }
86707ac75b1Sopenharmony_ci  return event;
86807ac75b1Sopenharmony_ci}
86907ac75b1Sopenharmony_ci
87007ac75b1Sopenharmony_ciexport function stopEvent(event: Object, syncFlag = false): void {
87107ac75b1Sopenharmony_ci  if (event !== undefined) {
87207ac75b1Sopenharmony_ci    if (typeof event.stopAsyncEvent === 'function' && syncFlag) {
87307ac75b1Sopenharmony_ci      event.stopAsyncEvent();
87407ac75b1Sopenharmony_ci    } else {
87507ac75b1Sopenharmony_ci      event.stop();
87607ac75b1Sopenharmony_ci    }
87707ac75b1Sopenharmony_ci  }
87807ac75b1Sopenharmony_ci}
87907ac75b1Sopenharmony_ci
88007ac75b1Sopenharmony_ciexport function compileToolIsRollUp(): boolean {
88107ac75b1Sopenharmony_ci  return process.env.compileTool === 'rollup';
88207ac75b1Sopenharmony_ci}
88307ac75b1Sopenharmony_ci
88407ac75b1Sopenharmony_ciexport function transformOhmurlToRecordName(ohmurl: string): string {
88507ac75b1Sopenharmony_ci  // @normalized:N&<moduleName>&<bunldName>&<packageName>/entry/ets/xxx/yyy&<version>
88607ac75b1Sopenharmony_ci  // ----> <bunldName>&<packageName>/entry/ets/xxx/yyy&<version>
88707ac75b1Sopenharmony_ci  return ohmurl.split(SEPARATOR_BITWISE_AND).slice(2).join(SEPARATOR_BITWISE_AND);
88807ac75b1Sopenharmony_ci}
88907ac75b1Sopenharmony_ci
89007ac75b1Sopenharmony_ciexport function transformOhmurlToPkgName(ohmurl: string): string {
89107ac75b1Sopenharmony_ci  let normalizedPath: string = ohmurl.split(SEPARATOR_BITWISE_AND)[3];
89207ac75b1Sopenharmony_ci  let paths: Array<string> = normalizedPath.split(SEPARATOR_SLASH);
89307ac75b1Sopenharmony_ci  if (normalizedPath.startsWith(SEPARATOR_AT)) {
89407ac75b1Sopenharmony_ci    // Spec: If the normalized import path starts with '@', the package name is before the second '/' in the normalized
89507ac75b1Sopenharmony_ci    // import path, like:  @aaa/bbb/ccc/ddd ---> package name is @aaa/bbb
89607ac75b1Sopenharmony_ci    return paths.slice(0, 2).join(SEPARATOR_SLASH);
89707ac75b1Sopenharmony_ci  }
89807ac75b1Sopenharmony_ci  return paths[0];
89907ac75b1Sopenharmony_ci}