1/*
2 * Copyright 2017, 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 */
16
17var path = require("path");
18var fs = require('fs');
19var protobuf = require('protobufjs');
20var loaderUtils = require('loader-utils');
21var jsonTarget = require('protobufjs/cli/targets/json');
22
23
24module.exports = function(source) {
25  var self = this;
26
27  var root = new protobuf.Root();
28
29  var paths = loaderUtils.getOptions(this)['paths'] || [];
30
31  // Search include paths when resolving imports
32  root.resolvePath = function pbjsResolvePath(origin, target) {
33    var normOrigin = protobuf.util.path.normalize(origin);
34    var normTarget = protobuf.util.path.normalize(target);
35
36    var resolved = protobuf.util.path.resolve(normOrigin, normTarget, true);
37    if (fs.existsSync(resolved)) {
38      self.addDependency(resolved);
39      return resolved;
40    }
41
42    for (var i = 0; i < paths.length; ++i) {
43      var iresolved = protobuf.util.path.resolve(paths[i] + "/", target);
44      if (fs.existsSync(iresolved)) {
45        self.addDependency(iresolved);
46        return iresolved;
47      }
48    }
49
50    self.addDependency(resolved);
51    return resolved;
52  };
53
54  root.loadSync(self.resourcePath).resolveAll();
55
56  var result = JSON.stringify(root, null, 2);
57
58  return `module.exports = ${result}`;
59};
60