1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const fs_1 = require("fs");
|
4 | const path_1 = require("path");
|
5 | let caches = Object.create(null);
|
6 | function closestFileData(relPath, oneOrMoreReader) {
|
7 | const paths = [];
|
8 | const readers = Array.isArray(oneOrMoreReader) ? oneOrMoreReader : [oneOrMoreReader];
|
9 | if (readers.length < 1) {
|
10 | throw new RangeError(`At least one reader must be given.`);
|
11 | }
|
12 |
|
13 | const cacheKey = readers.map(r => r.basename).join('::');
|
14 | if (!(cacheKey in caches)) {
|
15 | caches[cacheKey] = Object.create(null);
|
16 | }
|
17 | const cache = caches[cacheKey];
|
18 | let result;
|
19 | let directory = relPath;
|
20 | do {
|
21 | if (directory in cache) {
|
22 | result = cache[directory];
|
23 | break;
|
24 | }
|
25 | paths.push(directory);
|
26 |
|
27 | readers.find(({ basename, read }) => {
|
28 | const path = path_1.join(directory, basename);
|
29 | if (fs_1.existsSync(path)) {
|
30 | const config = read(path);
|
31 | if (typeof config !== 'undefined') {
|
32 | result = Object.freeze({ path, data: config });
|
33 | return true;
|
34 | }
|
35 | }
|
36 | return false;
|
37 | });
|
38 |
|
39 | } while (!result && directory !== (directory = path_1.dirname(directory)));
|
40 |
|
41 | paths.forEach(d => (cache[d] = result));
|
42 | return result;
|
43 | }
|
44 | exports.default = Object.assign(closestFileData, {
|
45 | cache: {
|
46 | clear: () => (caches = Object.create(null)),
|
47 | },
|
48 | });
|