1/* 2 * Copyright (c) 2023 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 path from 'path'; 17import { isDeclarationFile, isNeedMocked } from '../common/commonUtils'; 18import { 19 arktsDtsFileList, 20 mockBufferMap, 21 NO_CONTENT_FILES, 22 ohosDtsFileList 23} from '../common/constants'; 24 25/** 26 * 声测会给你index文件 27 * @param indexFilePath index文件输出路径 28 * @returns 29 */ 30export function generateIndex(indexFilePath: string): string { 31 let indexBody = ''; 32 let caseBody = ''; 33 34 [ 35 ...ohosDtsFileList, 36 ...arktsDtsFileList 37 ].forEach(fileName => { 38 if (NO_CONTENT_FILES.has(fileName)) { 39 return; 40 } 41 if (!isDeclarationFile(fileName)) { 42 return; 43 } 44 if (!isNeedMocked(fileName)) { 45 return; 46 } 47 48 const mockBuffer = mockBufferMap.get(fileName); 49 const mockedFilePath = mockBuffer.mockedFilePath; 50 const fileBaseName = path.basename(mockedFilePath, '.js'); 51 const relativePath = path.relative(path.dirname(indexFilePath), mockedFilePath).replace(/\.js$/, '').replace(/\\/g, '/'); 52 const asName = path.basename(fileBaseName).replace(/^@/, '').replace(/\./g, '_'); 53 if (mockBuffer?.contents.members.default && mockBuffer?.contents.members.default.isNeedMock) { 54 indexBody += `import ${asName} from './${relativePath}';\n`; 55 } else { 56 indexBody += `import * as ${asName} from './${relativePath}';\n`; 57 } 58 59 caseBody += `case '${fileBaseName.replace(/^@(ohos\.)?/, '')}':\n\treturn ${asName};\n`; 60 }); 61 62 indexBody += `export function mockRequireNapiFun() { 63 global.requireNapi = function(...args) { 64 const globalNapi = global.requireNapiPreview(...args); 65 if (globalNapi !== undefined) { 66 return globalNapi; 67 } 68 switch (args[0]) {`; 69 indexBody += caseBody; 70 const endBody = `} 71 if (global.hosMockFunc !== undefined) { 72 return global.hosMockFunc(args[0]); 73 } 74 } 75 }`; 76 indexBody += endBody; 77 return indexBody; 78} 79