1/* 2 * Copyright (c) 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 * as path from 'path'; 17 18const nativeModuleLibraries: Map<string, string> = new Map(); 19 20export function loadNativeLibrary(name: string): Record<string, object> { 21 // CC-OFFNXT(no_explicit_any) project code style 22 if ((globalThis as any).requireNapi) { 23 // CC-OFFNXT(no_explicit_any) project code style 24 return (globalThis as any).requireNapi(name, true); 25 } else { 26 const suffixedName = name.endsWith('.node') ? name : `${name}.node`; 27 if (process.platform === 'win32') { 28 return require(suffixedName); 29 } else { 30 // CC-OFFNXT(no_eval) project code style 31 return eval(`let exports = {}; process.dlopen({ exports }, require.resolve("${suffixedName}"), 2); exports`); 32 } 33 } 34} 35 36export function registerNativeModuleLibraryName(nativeModule: string, libraryName: string): void { 37 nativeModuleLibraries.set(nativeModule, libraryName); 38} 39 40export function loadNativeModuleLibrary(moduleName: string, module?: object): void { 41 if (!module) { 42 throw new Error('<module> argument is required and optional only for compatibility with ArkTS'); 43 } 44 const library = loadNativeLibrary(nativeModuleLibraries.get(moduleName) ?? moduleName); 45 if (!library || !library[moduleName]) { 46 console.error(`Failed to load library for module ${moduleName}`); 47 return; 48 } 49 Object.assign(module, library[moduleName]); 50} 51