UNPKG

2.36 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.createModuleTypeClassifier = void 0;
4const ts_internals_1 = require("./ts-internals");
5const util_1 = require("./util");
6/**
7 * @internal
8 * May receive non-normalized options -- basePath and patterns -- and will normalize them
9 * internally.
10 * However, calls to `classifyModule` must pass pre-normalized paths!
11 */
12function createModuleTypeClassifier(options) {
13 const { patterns, basePath: _basePath } = options;
14 const basePath = _basePath !== undefined
15 ? (0, util_1.normalizeSlashes)(_basePath).replace(/\/$/, '')
16 : undefined;
17 const patternTypePairs = Object.entries(patterns !== null && patterns !== void 0 ? patterns : []).map(([_pattern, type]) => {
18 const pattern = (0, util_1.normalizeSlashes)(_pattern);
19 return { pattern: parsePattern(basePath, pattern), type };
20 });
21 const classifications = {
22 package: {
23 moduleType: 'auto',
24 },
25 cjs: {
26 moduleType: 'cjs',
27 },
28 esm: {
29 moduleType: 'esm',
30 },
31 };
32 const auto = classifications.package;
33 // Passed path must be normalized!
34 function classifyModuleNonCached(path) {
35 const matched = matchPatterns(patternTypePairs, (_) => _.pattern, path);
36 if (matched)
37 return classifications[matched.type];
38 return auto;
39 }
40 const classifyModule = (0, util_1.cachedLookup)(classifyModuleNonCached);
41 function classifyModuleAuto(path) {
42 return auto;
43 }
44 return {
45 classifyModuleByModuleTypeOverrides: patternTypePairs.length
46 ? classifyModule
47 : classifyModuleAuto,
48 };
49}
50exports.createModuleTypeClassifier = createModuleTypeClassifier;
51function parsePattern(basePath, patternString) {
52 const pattern = (0, ts_internals_1.getPatternFromSpec)(patternString, basePath);
53 return pattern !== undefined ? new RegExp(pattern) : /(?:)/;
54}
55function matchPatterns(objects, getPattern, candidate) {
56 for (let i = objects.length - 1; i >= 0; i--) {
57 const object = objects[i];
58 const pattern = getPattern(object);
59 if (pattern === null || pattern === void 0 ? void 0 : pattern.test(candidate)) {
60 return object;
61 }
62 }
63}
64//# sourceMappingURL=module-type-classifier.js.map
\No newline at end of file