1/* 2 * Copyright (c) 2024 - 2025 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 type {ArkFile, ImportInfo} from 'arkanalyzer'; 17import type {DependsNode} from 'arkanalyzer/lib/core/graph/DependsGraph'; 18import type {File, FileDepsGraph, ImportInfo4Dep} from './fileComponent'; 19 20export class ArkFileDeps { 21 private static instance: ArkFileDeps; 22 23 private constructor() { 24 } 25 26 public static getInstance(): ArkFileDeps { 27 if (!this.instance) { 28 this.instance = new ArkFileDeps(); 29 } 30 return this.instance; 31 } 32 33 public addDeps(depsGraph: FileDepsGraph, node: DependsNode<File>, arkFile: ArkFile): void { 34 let importInfos = arkFile.getImportInfos(); 35 if (importInfos && importInfos.length > 0) { 36 for (let importInfo of importInfos) { 37 this.processImportInfo(depsGraph, node, importInfo); 38 } 39 } 40 } 41 42 private processImportInfo(depsGraph: FileDepsGraph, src: DependsNode<File>, importInfo: ImportInfo): void { 43 const nodeAttr = this.genNodeByImportInfo(importInfo); 44 if (nodeAttr) { 45 const dst = depsGraph.addDepsNode(nodeAttr.name, nodeAttr); 46 const edge = depsGraph.addEdge(src, dst, {kind: 0, attr: new Map()}); 47 depsGraph.addImportInfo2Edge(edge.getEdgeAttr(), this.simplifyImportInfo(importInfo)); 48 } 49 } 50 51 private genNodeByImportInfo(importInfo: ImportInfo): File | undefined { 52 const lazyExport = importInfo.getLazyExportInfo(); 53 if (lazyExport) { 54 const exportArkFile = lazyExport.getDeclaringArkFile(); 55 if (exportArkFile) { 56 return { 57 name: exportArkFile.getFilePath(), 58 kind: 0, 59 }; 60 } 61 } 62 const from = importInfo.getFrom(); 63 if (from?.endsWith('.so')) { 64 return { 65 name: importInfo.getFrom()!, 66 kind: 0, 67 }; 68 } 69 if (from) { 70 return { 71 name: importInfo.getFrom()!, 72 kind: 1, 73 }; 74 } 75 return undefined; 76 } 77 78 private simplifyImportInfo(importInfo: ImportInfo): ImportInfo4Dep { 79 return { 80 importClauseName: importInfo.getImportClauseName(), 81 importType: importInfo.getImportType(), 82 importFrom: importInfo.getFrom(), 83 nameBeforeAs: importInfo.getNameBeforeAs(), 84 isDefault: importInfo.isDefault(), 85 }; 86 } 87}