马宇豪
2024-07-16 f591c27b57e2418c9495bc02ae8cfff84d35bc18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExplorerSync = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const defaults_1 = require("./defaults");
const ExplorerBase_js_1 = require("./ExplorerBase.js");
const merge_1 = require("./merge");
const util_js_1 = require("./util.js");
/**
 * @internal
 */
class ExplorerSync extends ExplorerBase_js_1.ExplorerBase {
    load(filepath) {
        filepath = path_1.default.resolve(filepath);
        const load = () => {
            return this.config.transform(this.#readConfiguration(filepath));
        };
        if (this.loadCache) {
            return (0, util_js_1.emplace)(this.loadCache, filepath, load);
        }
        return load();
    }
    search(from = '') {
        if (this.config.metaConfigFilePath) {
            this.loadingMetaConfig = true;
            const config = this.load(this.config.metaConfigFilePath);
            this.loadingMetaConfig = false;
            if (config && !config.isEmpty) {
                return config;
            }
        }
        from = path_1.default.resolve(from);
        const dirs = this.#getDirs(from);
        const firstDirIter = dirs.next();
        /* istanbul ignore if -- @preserve */
        if (firstDirIter.done) {
            // this should never happen
            throw new Error(`Could not find any folders to iterate through (start from ${from})`);
        }
        let currentDir = firstDirIter.value;
        const search = () => {
            /* istanbul ignore if -- @preserve */
            if ((0, util_js_1.isDirectorySync)(currentDir.path)) {
                for (const filepath of this.getSearchPlacesForDir(currentDir, defaults_1.globalConfigSearchPlacesSync)) {
                    try {
                        const result = this.#readConfiguration(filepath);
                        if (result !== null &&
                            !(result.isEmpty && this.config.ignoreEmptySearchPlaces)) {
                            return this.config.transform(result);
                        }
                    }
                    catch (error) {
                        if (error.code === 'ENOENT' ||
                            error.code === 'EISDIR' ||
                            error.code === 'ENOTDIR' ||
                            error.code === 'EACCES') {
                            continue;
                        }
                        throw error;
                    }
                }
            }
            const nextDirIter = dirs.next();
            if (!nextDirIter.done) {
                currentDir = nextDirIter.value;
                if (this.searchCache) {
                    return (0, util_js_1.emplace)(this.searchCache, currentDir.path, search);
                }
                return search();
            }
            return this.config.transform(null);
        };
        if (this.searchCache) {
            return (0, util_js_1.emplace)(this.searchCache, from, search);
        }
        return search();
    }
    #readConfiguration(filepath, importStack = []) {
        const contents = fs_1.default.readFileSync(filepath, 'utf8');
        return this.toCosmiconfigResult(filepath, this.#loadConfigFileWithImports(filepath, contents, importStack));
    }
    #loadConfigFileWithImports(filepath, contents, importStack) {
        const loadedContent = this.#loadConfiguration(filepath, contents);
        if (!loadedContent || !(0, merge_1.hasOwn)(loadedContent, '$import')) {
            return loadedContent;
        }
        const fileDirectory = path_1.default.dirname(filepath);
        const { $import: imports, ...ownContent } = loadedContent;
        const importPaths = Array.isArray(imports) ? imports : [imports];
        const newImportStack = [...importStack, filepath];
        this.validateImports(filepath, importPaths, newImportStack);
        const importedConfigs = importPaths.map((importPath) => {
            const fullPath = path_1.default.resolve(fileDirectory, importPath);
            const result = this.#readConfiguration(fullPath, newImportStack);
            return result?.config;
        });
        return (0, merge_1.mergeAll)([...importedConfigs, ownContent], {
            mergeArrays: this.config.mergeImportArrays,
        });
    }
    #loadConfiguration(filepath, contents) {
        if (contents.trim() === '') {
            return;
        }
        const extension = path_1.default.extname(filepath);
        const loader = this.config.loaders[extension || 'noExt'] ??
            this.config.loaders['default'];
        if (!loader) {
            throw new Error(`No loader specified for ${(0, ExplorerBase_js_1.getExtensionDescription)(extension)}`);
        }
        try {
            const loadedContents = loader(filepath, contents);
            if (path_1.default.basename(filepath, extension) !== 'package') {
                return loadedContents;
            }
            return ((0, util_js_1.getPropertyByPath)(loadedContents, this.config.packageProp ?? this.config.moduleName) ?? null);
        }
        catch (error) {
            error.filepath = filepath;
            throw error;
        }
    }
    #fileExists(path) {
        try {
            fs_1.default.statSync(path);
            return true;
        }
        catch (e) {
            return false;
        }
    }
    *#getDirs(startDir) {
        switch (this.config.searchStrategy) {
            case 'none': {
                // there is no next dir
                yield { path: startDir, isGlobalConfig: false };
                return;
            }
            case 'project': {
                let currentDir = startDir;
                while (true) {
                    yield { path: currentDir, isGlobalConfig: false };
                    for (const ext of ['json', 'yaml']) {
                        const packageFile = path_1.default.join(currentDir, `package.${ext}`);
                        if (this.#fileExists(packageFile)) {
                            break;
                        }
                    }
                    const parentDir = path_1.default.dirname(currentDir);
                    /* istanbul ignore if -- @preserve */
                    if (parentDir === currentDir) {
                        // we're probably at the root of the directory structure
                        break;
                    }
                    currentDir = parentDir;
                }
                return;
            }
            case 'global': {
                yield* this.getGlobalDirs(startDir);
            }
        }
    }
    /**
     * @deprecated Use {@link ExplorerSync.prototype.load}.
     */
    /* istanbul ignore next */
    loadSync(filepath) {
        return this.load(filepath);
    }
    /**
     * @deprecated Use {@link ExplorerSync.prototype.search}.
     */
    /* istanbul ignore next */
    searchSync(from = '') {
        return this.search(from);
    }
}
exports.ExplorerSync = ExplorerSync;
//# sourceMappingURL=ExplorerSync.js.map