1/* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16const fs = require('fs'); 17const protobuf = require('protobufjs'); 18const loaderUtils = require('loader-utils'); 19 20module.exports = function(source) { 21 const webpackContext = this; 22 const root = new protobuf.Root(); 23 const paths = loaderUtils.getOptions(this)['paths'] || []; 24 25 root.resolvePath = function resolvePath(origin, target) { 26 const normOrigin = protobuf.util.path.normalize(origin); 27 const normTarget = protobuf.util.path.normalize(target); 28 29 let candidates = [ 30 protobuf.util.path.resolve(normOrigin, normTarget, true) 31 ]; 32 candidates = candidates.concat( 33 paths.map(path => protobuf.util.path.resolve(path + "/", target)) 34 ); 35 36 for (const path of candidates) { 37 if (fs.existsSync(path)) { 38 webpackContext.addDependency(path); 39 return path; 40 } 41 } 42 43 throw Error(`Failed to resolve path: origin=${origin}, target=${target}, candidates=${candidates}`); 44 }; 45 46 root.loadSync(webpackContext.resourcePath).resolveAll(); 47 48 const result = JSON.stringify(root, null, 2); 49 50 return `module.exports = ${result}`; 51}; 52