|
| 1 | +const dirname = require('path').dirname; |
| 2 | +const forEach = require('lodash'); |
1 | 3 | const plugin = require('postcss').plugin; |
| 4 | +const postcss = require('postcss'); |
| 5 | +const readFile = require('fs').readFile; |
| 6 | +const readFileSync = require('fs').readFileSync; |
| 7 | +const resolve = require('path').resolve; |
2 | 8 |
|
3 | 9 | const importRegexp = /^:import\((.+)\)$/; |
| 10 | +const nameOfTheCurrentPlugin = 'postcss-modules-resolve-imports'; |
4 | 11 |
|
5 | 12 | /** |
6 | 13 | * @param {object} [opts] |
7 | 14 | * @param {boolean} opts.sync |
8 | 15 | * @return {function} |
9 | 16 | */ |
10 | | -module.exports = plugin('postcss-modules-resolve-imports', function postcssModulesResolveImports(opts) { |
11 | | - return function resolveImports(css, result) { |
| 17 | +module.exports = plugin(nameOfTheCurrentPlugin, function postcssModulesResolveImports(opts) { |
| 18 | + return function resolveImports(tree, result) { |
12 | 19 | // https://github.com/postcss/postcss/blob/master/docs/api.md#inputfile |
13 | | - const filepath = css.source.input.file; |
14 | | - const plugins = result.processor.plugins; |
| 20 | + // const filepath = tree.source.input.file; |
| 21 | + const plugins = getPluginsForParse(result.processor.plugins); |
| 22 | + const runner = postcss(plugins); |
15 | 23 |
|
16 | | - css.walkRules(importRegexp, rule => { |
17 | | - const dependency = RegExp.$1.replace(/^["']|["']$/g, ''); |
| 24 | + const cache = {}; |
| 25 | + const queue = []; |
| 26 | + const traces = {}; |
18 | 27 |
|
19 | | - // Шаги -> Резолвим путь -> Загружаем содержимое -> Прогоняем через postcss -> Достаем Root |
20 | | - // -> Резолвим зависимости -> Вставляем ноды в исходное дерево (желательно использовать tracesort) |
21 | | - // Получается, нужен кэш с файлами и конечный резолвер на случай, когда файлы загружены. |
22 | | - // |
23 | | - // По сути можно хранить список файлов и их контент + отдельно помечать глубину загрузки |
| 28 | + traverseImports(tree, dependency => |
| 29 | + loadDependency(dependency, {cache, queue, runner})); |
24 | 30 |
|
25 | | - // path RegExp.$1 |
26 | | - }); |
| 31 | + return Promise.all(queue) |
| 32 | + .then(_ => combineTrees(tree, cache)); |
27 | 33 |
|
28 | | - return css; |
| 34 | + // -> traceKeySorter |
29 | 35 | }; |
30 | 36 | }); |
| 37 | + |
| 38 | +/** |
| 39 | + * @param {array} plugins |
| 40 | + * @return {array} |
| 41 | + */ |
| 42 | +function getPluginsForParse(plugins) { |
| 43 | + const pluginsForParse = plugins.slice(); |
| 44 | + let ln = pluginsForParse.length; |
| 45 | + |
| 46 | + while (pluginsForParse[--ln].postcssPlugin !== nameOfTheCurrentPlugin) { |
| 47 | + pluginsForParse.pop(); |
| 48 | + } |
| 49 | + |
| 50 | + return pluginsForParse; |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * @param {root} tree |
| 55 | + * @param {function} iterator |
| 56 | + */ |
| 57 | +function traverseImports(tree, iterator) { |
| 58 | + // https://github.com/postcss/postcss/blob/master/docs/api.md#inputfile |
| 59 | + const source = tree.source.input.file; |
| 60 | + // https://github.com/postcss/postcss/blob/master/docs/api.md#containerwalkrulesselectorfilter-callback |
| 61 | + tree.walkRules(importRegexp, rule => { |
| 62 | + iterator(getDepsPath(RegExp.$1, source), source); |
| 63 | + tree.removeChild(rule); |
| 64 | + }); |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * @param {string} to |
| 69 | + * @param {string} from |
| 70 | + * @return {string} |
| 71 | + */ |
| 72 | +function getDepsPath(to, from) { |
| 73 | + // @todo support non-relative imports |
| 74 | + // const filepath = /\w/i.test(to[0]) |
| 75 | + // ? require.resolve(to) |
| 76 | + // : resolve(dirname(from), to); |
| 77 | + return resolve(dirname(from), to.replace(/^["']|["']$/g, '')); |
| 78 | +} |
| 79 | + |
| 80 | +/** |
| 81 | + * @param {string} dependency |
| 82 | + * @param {object} options.cache |
| 83 | + * @param {array} options.queue |
| 84 | + */ |
| 85 | +function loadDependency(dependency, {cache, queue, runner}) { |
| 86 | + const pending = new Promise((resolve, reject) => |
| 87 | + readFile(dependency, 'utf8', (er, source) => { |
| 88 | + if (er) { |
| 89 | + return void reject(er); |
| 90 | + } |
| 91 | + |
| 92 | + runner |
| 93 | + .process(source, {from: dependency}) |
| 94 | + .then(result => { |
| 95 | + cache[dependency] = result.root; |
| 96 | + |
| 97 | + traverseImports(result.root, deps => |
| 98 | + loadDependency(deps, {cache, queue, runner})); |
| 99 | + |
| 100 | + resolve(result.root); |
| 101 | + }) |
| 102 | + .catch(reject); |
| 103 | + })); |
| 104 | + |
| 105 | + queue.push(pending); |
| 106 | + return pending; |
| 107 | +} |
| 108 | + |
| 109 | +function combineTrees(root, cache) { |
| 110 | + forEach(cache, tree => root.prepend.apply(root, tree.nodes)); |
| 111 | + console.log('test', root) |
| 112 | + return root; |
| 113 | +} |
| 114 | + |
| 115 | +// Sorts dependencies in the following way: |
| 116 | +// AAA comes before AA and A |
| 117 | +// AB comes after AA and before A |
| 118 | +// All Bs come after all As |
| 119 | +// This ensures that the files are always returned in the following order: |
| 120 | +// - In the order they were required, except |
| 121 | +// - After all their dependencies |
| 122 | +function traceKeySorter(a, b) { |
| 123 | + if (a.length < b.length) { |
| 124 | + return a < b.substring(0, a.length) ? -1 : 1; |
| 125 | + } else if (a.length > b.length) { |
| 126 | + return a.substring(0, b.length) <= b ? -1 : 1; |
| 127 | + } else { |
| 128 | + return a < b ? -1 : 1; |
| 129 | + } |
| 130 | +}; |
0 commit comments