postcss-modules 9.1.0 → 9.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 9.1.1
4
+
5
+ ### Fixed
6
+
7
+ - Updated the custom loader TypeScript declaration to include the resolver argument and optional dependency source outputs already supported at runtime.
8
+
9
+ ### Internal
10
+
11
+ - Split plugin orchestration, dependency processing, path resolution, graph storage, and filesystem access into focused modules without changing generated CSS, tokens, messages, or custom loader behavior.
12
+
3
13
  ## 9.1.0
4
14
 
5
15
  ### Added
package/README.md CHANGED
@@ -228,7 +228,7 @@ postcss([
228
228
  generateScopedName: function (name, filename, css) {
229
229
  var path = require("path");
230
230
  var i = css.indexOf("." + name);
231
- var line = css.substr(0, i).split(/[\r\n]/).length;
231
+ var line = css.slice(0, i).split(/[\r\n]/).length;
232
232
  var file = path.basename(filename, ".css");
233
233
 
234
234
  return "_" + file + "_" + line + "_" + name;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "default", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return DependencyStore;
9
+ }
10
+ });
11
+ // Sorts dependencies in the following way:
12
+ // AAA comes before AA and A
13
+ // AB comes after AA and before A
14
+ // All Bs come after all As
15
+ // This ensures that the files are always returned in the following order:
16
+ // - In the order they were required, except
17
+ // - After all their dependencies
18
+ const dependencyPathSorter = (a, b)=>{
19
+ if (a.length < b.length) {
20
+ return a < b.substring(0, a.length) ? -1 : 1;
21
+ }
22
+ if (a.length > b.length) {
23
+ return a.substring(0, b.length) <= b ? -1 : 1;
24
+ }
25
+ return a < b ? -1 : 1;
26
+ };
27
+ class DependencyStore {
28
+ constructor(){
29
+ this.sources = {};
30
+ this.dependencyPaths = {};
31
+ this.tokensByFile = {};
32
+ }
33
+ getTokens(file) {
34
+ return this.tokensByFile[file];
35
+ }
36
+ record({ file, dependencyPath, source, tokens }) {
37
+ this.sources[file] = source;
38
+ this.dependencyPaths[dependencyPath] = file;
39
+ this.tokensByFile[file] = tokens;
40
+ }
41
+ get finalSources() {
42
+ const written = new Set();
43
+ return Object.keys(this.dependencyPaths).sort(dependencyPathSorter).map((key)=>{
44
+ const filename = this.dependencyPaths[key];
45
+ if (written.has(filename)) return null;
46
+ written.add(filename);
47
+ return {
48
+ file: filename,
49
+ source: this.sources[filename]
50
+ };
51
+ }).filter(Boolean);
52
+ }
53
+ get dependencies() {
54
+ return this.finalSources.map((entry)=>entry.file);
55
+ }
56
+ get finalSource() {
57
+ return this.finalSources.map((entry)=>entry.source).join("");
58
+ }
59
+ }
@@ -9,128 +9,82 @@ Object.defineProperty(exports, "default", {
9
9
  return FileSystemLoader;
10
10
  }
11
11
  });
12
- const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss"));
13
- const _path = /*#__PURE__*/ _interop_require_default(require("path"));
14
- const _Parser = /*#__PURE__*/ _interop_require_default(require("./Parser"));
15
- const _fs = require("./fs");
12
+ const _DependencyStore = /*#__PURE__*/ _interop_require_default(require("./DependencyStore"));
13
+ const _processImportedCSS = require("./processImportedCSS");
14
+ const _resolveImport = require("./resolveImport");
16
15
  function _interop_require_default(obj) {
17
16
  return obj && obj.__esModule ? obj : {
18
17
  default: obj
19
18
  };
20
19
  }
21
- class Core {
22
- constructor(plugins){
23
- this.plugins = plugins || Core.defaultPlugins;
24
- }
25
- async load(sourceString, sourcePath, trace, pathFetcher) {
26
- const parser = new _Parser.default(pathFetcher, trace);
27
- const plugins = this.plugins.concat([
28
- parser.plugin()
29
- ]);
30
- const result = await (0, _postcss.default)(plugins).process(sourceString, {
31
- from: sourcePath
32
- });
33
- return {
34
- injectableSource: result.css,
35
- exportTokens: parser.exportTokens
36
- };
37
- }
38
- }
39
- // Sorts dependencies in the following way:
40
- // AAA comes before AA and A
41
- // AB comes after AA and before A
42
- // All Bs come after all As
43
- // This ensures that the files are always returned in the following order:
44
- // - In the order they were required, except
45
- // - After all their dependencies
46
- const traceKeySorter = (a, b)=>{
47
- if (a.length < b.length) {
48
- return a < b.substring(0, a.length) ? -1 : 1;
49
- }
50
- if (a.length > b.length) {
51
- return a.substring(0, b.length) <= b ? -1 : 1;
52
- }
53
- return a < b ? -1 : 1;
54
- };
55
20
  class FileSystemLoader {
56
- constructor(root, plugins, fileResolve){
57
- if (root === "/" && process.platform === "win32") {
58
- const cwdDrive = process.cwd().slice(0, 3);
59
- if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
60
- throw new Error(`Failed to obtain root from "${process.cwd()}".`);
61
- }
62
- root = cwdDrive;
63
- }
64
- this.root = root;
65
- this.fileResolve = fileResolve;
66
- this.sources = {};
67
- this.traces = {};
68
- this.importNr = 0;
69
- this.core = new Core(plugins);
70
- this.tokensByFile = {};
71
- this.fs = (0, _fs.getFileSystem)();
21
+ #fileResolve;
22
+ #fileSystem;
23
+ #nextImportIndex = 0;
24
+ #processImportedCSS;
25
+ #root;
26
+ #store;
27
+ constructor(root, plugins, fileResolve, fileSystem){
28
+ this.#root = (0, _resolveImport.normalizeRoot)(root);
29
+ this.#fileResolve = fileResolve;
30
+ this.#processImportedCSS = (0, _processImportedCSS.createImportedCSSProcessor)(plugins);
31
+ this.#store = new _DependencyStore.default();
32
+ this.#fileSystem = fileSystem;
72
33
  }
73
- async fetch(_newPath, relativeTo, _trace) {
74
- const newPath = _newPath.replace(/^["']|["']$/g, "");
75
- const trace = _trace || String.fromCharCode(this.importNr++);
76
- const useFileResolve = typeof this.fileResolve === "function";
77
- const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
78
- if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
79
- throw new Error('The returned path from the "fileResolve" option must be absolute.');
80
- }
81
- const relativeDir = _path.default.dirname(relativeTo);
82
- const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
83
- let fileRelativePath = fileResolvedPath || _path.default.resolve(_path.default.resolve(this.root, relativeDir), newPath);
84
- // if the path is not relative or absolute, try to resolve it in node_modules
85
- if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
86
- try {
87
- fileRelativePath = require.resolve(newPath);
88
- } catch {
89
- // noop
90
- }
91
- }
92
- const tokens = this.tokensByFile[fileRelativePath];
93
- if (tokens) return tokens;
94
- return new Promise((resolve, reject)=>{
95
- this.fs.readFile(fileRelativePath, "utf-8", async (err, source)=>{
96
- if (err) {
97
- reject(err);
98
- return;
99
- }
100
- try {
101
- const { injectableSource, exportTokens } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
102
- this.sources[fileRelativePath] = injectableSource;
103
- this.traces[trace] = fileRelativePath;
104
- this.tokensByFile[fileRelativePath] = exportTokens;
105
- resolve(exportTokens);
106
- } catch (error) {
107
- reject(error);
108
- }
109
- });
110
- });
34
+ async fetch(_request, relativeTo, _dependencyPath) {
35
+ const request = this.#normalizeRequest(_request);
36
+ const dependencyPath = this.#getOrCreateDependencyPath(_dependencyPath);
37
+ const { filePath, sourcePath } = await this.#resolvePaths(request, relativeTo);
38
+ const cachedTokens = this.#store.getTokens(filePath);
39
+ if (cachedTokens) return cachedTokens;
40
+ const source = await this.#readFile(filePath);
41
+ const result = await this.#processSource(source, sourcePath, dependencyPath);
42
+ this.#recordDependency(filePath, dependencyPath, result);
43
+ const { exportTokens } = result;
44
+ return exportTokens;
111
45
  }
112
46
  get finalSources() {
113
- const traces = this.traces;
114
- const sources = this.sources;
115
- const written = new Set();
116
- return Object.keys(traces).sort(traceKeySorter).map((key)=>{
117
- const filename = traces[key];
118
- if (written.has(filename)) {
119
- return null;
120
- }
121
- written.add(filename);
122
- return {
123
- file: filename,
124
- source: sources[filename]
125
- };
126
- }).filter(Boolean);
47
+ return this.#store.finalSources;
127
48
  }
128
49
  // Files read through `composes` and `@value` imports, including nested ones,
129
50
  // in the order their CSS is prepended.
130
51
  get dependencies() {
131
- return this.finalSources.map((entry)=>entry.file);
52
+ return this.#store.dependencies;
132
53
  }
133
54
  get finalSource() {
134
- return this.finalSources.map((entry)=>entry.source).join("");
55
+ return this.#store.finalSource;
56
+ }
57
+ #normalizeRequest(request) {
58
+ return request.replace(/^["']|["']$/g, "");
59
+ }
60
+ #getOrCreateDependencyPath(dependencyPath) {
61
+ return dependencyPath || String.fromCharCode(this.#nextImportIndex++);
62
+ }
63
+ #resolvePaths(request, relativeTo) {
64
+ return (0, _resolveImport.resolveImport)({
65
+ request,
66
+ relativeTo,
67
+ root: this.#root,
68
+ fileResolve: this.#fileResolve
69
+ });
70
+ }
71
+ #readFile(filePath) {
72
+ return new Promise((resolve, reject)=>{
73
+ this.#fileSystem.readFile(filePath, "utf-8", (error, contents)=>{
74
+ if (error) reject(error);
75
+ else resolve(contents);
76
+ });
77
+ });
78
+ }
79
+ #processSource(source, sourcePath, dependencyPath) {
80
+ return this.#processImportedCSS(source, sourcePath, dependencyPath, this.fetch.bind(this));
81
+ }
82
+ #recordDependency(filePath, dependencyPath, { injectableSource, exportTokens }) {
83
+ this.#store.record({
84
+ file: filePath,
85
+ dependencyPath,
86
+ source: injectableSource,
87
+ tokens: exportTokens
88
+ });
135
89
  }
136
90
  }
package/build/Parser.js CHANGED
@@ -12,12 +12,12 @@ const _icssutils = require("icss-utils");
12
12
  // Initially copied from https://github.com/css-modules/css-modules-loader-core
13
13
  const importRegexp = /^:import\((.+)\)$/;
14
14
  class Parser {
15
- constructor(pathFetcher, trace){
15
+ constructor(pathFetcher, dependencyPath){
16
16
  this.pathFetcher = pathFetcher;
17
17
  this.plugin = this.plugin.bind(this);
18
18
  this.exportTokens = {};
19
19
  this.translations = {};
20
- this.trace = trace;
20
+ this.dependencyPath = dependencyPath;
21
21
  }
22
22
  plugin() {
23
23
  const parser = this;
@@ -60,8 +60,8 @@ class Parser {
60
60
  }
61
61
  async fetchImport(importNode, relativeTo, depNr) {
62
62
  const file = importNode.selector.match(importRegexp)[1];
63
- const depTrace = this.trace + String.fromCharCode(depNr);
64
- const exports1 = await this.pathFetcher(file, relativeTo, depTrace);
63
+ const childDependencyPath = this.dependencyPath + String.fromCharCode(depNr);
64
+ const exports1 = await this.pathFetcher(file, relativeTo, childDependencyPath);
65
65
  try {
66
66
  importNode.each((decl)=>{
67
67
  if (decl.type == "decl") {
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "createLoader", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return createLoader;
9
+ }
10
+ });
11
+ const _FileSystemLoader = /*#__PURE__*/ _interop_require_default(require("./FileSystemLoader"));
12
+ function _interop_require_default(obj) {
13
+ return obj && obj.__esModule ? obj : {
14
+ default: obj
15
+ };
16
+ }
17
+ function createLoader(opts, plugins, fileSystem) {
18
+ const root = typeof opts.root === "undefined" ? "/" : opts.root;
19
+ return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve, fileSystem);
20
+ }
package/build/index.js CHANGED
@@ -3,11 +3,12 @@ Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
5
  const _fs = require("fs");
6
- const _fs1 = require("./fs");
7
6
  const _pluginFactory = require("./pluginFactory");
8
- (0, _fs1.setFileSystem)({
7
+ const fileSystem = {
9
8
  readFile: _fs.readFile,
10
9
  writeFile: _fs.writeFile
11
- });
12
- module.exports = (opts = {})=>(0, _pluginFactory.makePlugin)(opts);
10
+ };
11
+ module.exports = (opts = {})=>(0, _pluginFactory.makePlugin)(opts, {
12
+ fileSystem
13
+ });
13
14
  module.exports.postcss = true;
@@ -13,7 +13,9 @@ const _unquote = /*#__PURE__*/ _interop_require_default(require("./unquote"));
13
13
  const _Parser = /*#__PURE__*/ _interop_require_default(require("./Parser"));
14
14
  const _saveJSON = /*#__PURE__*/ _interop_require_default(require("./saveJSON"));
15
15
  const _localsConvention = require("./localsConvention");
16
- const _FileSystemLoader = /*#__PURE__*/ _interop_require_default(require("./FileSystemLoader"));
16
+ const _createLoader = require("./createLoader");
17
+ const _prependDependencySources = require("./prependDependencySources");
18
+ const _resultMessages = require("./resultMessages");
17
19
  const _scoping = require("./scoping");
18
20
  function _interop_require_default(obj) {
19
21
  return obj && obj.__esModule ? obj : {
@@ -21,41 +23,21 @@ function _interop_require_default(obj) {
21
23
  };
22
24
  }
23
25
  const PLUGIN_NAME = "postcss-modules";
24
- function isGlobalModule(globalModules, inputFile) {
25
- return globalModules.some((regex)=>inputFile.match(regex));
26
- }
27
- function getDefaultPluginsList(opts, inputFile) {
28
- const globalModulesList = opts.globalModulePaths || null;
29
- const exportGlobals = opts.exportGlobals || false;
30
- const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
31
- const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
32
- if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
33
- return (0, _scoping.getDefaultPlugins)({
34
- behaviour: _scoping.behaviours.GLOBAL,
35
- generateScopedName,
36
- exportGlobals
37
- });
38
- }
39
- return (0, _scoping.getDefaultPlugins)({
40
- behaviour: defaultBehaviour,
41
- generateScopedName,
42
- exportGlobals
43
- });
44
- }
45
- function getLoader(opts, plugins) {
46
- const root = typeof opts.root === "undefined" ? "/" : opts.root;
47
- return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
48
- }
49
26
  function isOurPlugin(plugin) {
50
27
  return plugin.postcssPlugin === PLUGIN_NAME;
51
28
  }
52
- function makePlugin(opts) {
29
+ function removeEmptySelectors(css) {
30
+ css.walkRules((rule)=>{
31
+ if (rule.selector.trim() === "") rule.remove();
32
+ });
33
+ }
34
+ function makePlugin(opts, { fileSystem } = {}) {
53
35
  return {
54
36
  postcssPlugin: PLUGIN_NAME,
55
37
  async OnceExit (css, { result }) {
56
- const getJSON = opts.getJSON || _saveJSON.default;
38
+ const getJSON = opts.getJSON || (0, _saveJSON.default)(fileSystem.writeFile);
57
39
  const inputFile = css.source.input.file;
58
- const pluginList = getDefaultPluginsList(opts, inputFile);
40
+ const pluginList = (0, _scoping.getDefaultPluginsList)(opts, inputFile);
59
41
  const resultPluginIndex = result.processor.plugins.findIndex((plugin)=>isOurPlugin(plugin));
60
42
  if (resultPluginIndex === -1) {
61
43
  throw new Error("Plugin missing from options.");
@@ -65,10 +47,10 @@ function makePlugin(opts) {
65
47
  ...earlierPlugins,
66
48
  ...pluginList
67
49
  ];
68
- const loader = getLoader(opts, loaderPlugins);
69
- const fetcher = async (file, relativeTo, depTrace)=>{
50
+ const loader = (0, _createLoader.createLoader)(opts, loaderPlugins, fileSystem);
51
+ const fetcher = async (file, relativeTo, dependencyPath)=>{
70
52
  const unquoteFile = (0, _unquote.default)(file);
71
- return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
53
+ return loader.fetch.call(loader, unquoteFile, relativeTo, dependencyPath);
72
54
  };
73
55
  const parser = new _Parser.default(fetcher);
74
56
  await (0, _postcss.default)([
@@ -79,79 +61,14 @@ function makePlugin(opts) {
79
61
  });
80
62
  // Remove rules whose selector was reduced to whitespace after
81
63
  // `:global { ... }` unwrapping — see #136.
82
- css.walkRules((rule)=>{
83
- if (rule.selector.trim() === "") rule.remove();
84
- });
85
- // Prepend the traced dependencies exactly as before, then re-parse
86
- // each dependency with its own `from` and graft those sources onto
87
- // the prepended nodes, pairing them by position. The pairing holds
88
- // because each dependency is complete CSS, so parsing the
89
- // concatenation yields the same node sequence as parsing each part.
90
- // If malformed CSS merges nodes across a file boundary the counts
91
- // differ and the graft is skipped, leaving the nodes unattributed
92
- // as before. Plugins that run after this one (e.g. url rewriters)
93
- // need `source.input.file` to resolve relative paths against the
94
- // file the CSS actually came from — see #149.
95
- const sources = Array.isArray(loader.finalSources) ? loader.finalSources : null;
96
- if (sources) {
97
- const joined = sources.map((entry)=>entry.source).join("");
98
- if (joined) {
99
- const countBefore = css.nodes.length;
100
- css.prepend(joined);
101
- const prepended = css.nodes.slice(0, css.nodes.length - countBefore);
102
- const sourceSeq = [];
103
- for (const { file, source } of sources){
104
- _postcss.default.parse(source, {
105
- from: file
106
- }).walk((node)=>{
107
- sourceSeq.push(node.source);
108
- });
109
- }
110
- let count = 0;
111
- for (const node of prepended){
112
- count += 1;
113
- if (typeof node.walk === "function") {
114
- node.walk(()=>{
115
- count += 1;
116
- });
117
- }
118
- }
119
- if (count === sourceSeq.length) {
120
- let i = 0;
121
- for (const node of prepended){
122
- node.source = sourceSeq[i++];
123
- if (typeof node.walk === "function") {
124
- node.walk((child)=>{
125
- child.source = sourceSeq[i++];
126
- });
127
- }
128
- }
129
- }
130
- }
131
- } else {
132
- // Custom loaders may not implement `finalSources`.
133
- const out = loader.finalSource;
134
- if (out) css.prepend(out);
135
- }
136
- // Report the files read through `composes` and `@value` imports, so
137
- // runners can rebuild this file when one of them changes.
138
- for (const file of loader.dependencies || []){
139
- result.messages.push({
140
- type: "dependency",
141
- plugin: PLUGIN_NAME,
142
- file,
143
- parent: result.opts.from || inputFile
144
- });
145
- }
64
+ removeEmptySelectors(css);
65
+ (0, _prependDependencySources.prependDependencySources)(css, loader);
66
+ (0, _resultMessages.addDependencyMessages)(result, loader, inputFile);
146
67
  if (opts.localsConvention) {
147
68
  const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
148
69
  parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
149
70
  }
150
- result.messages.push({
151
- type: "export",
152
- plugin: "postcss-modules",
153
- exportTokens: parser.exportTokens
154
- });
71
+ (0, _resultMessages.addExportMessage)(result, parser.exportTokens);
155
72
  // getJSON may return a promise
156
73
  return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
157
74
  }
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "prependDependencySources", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return prependDependencySources;
9
+ }
10
+ });
11
+ const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss"));
12
+ function _interop_require_default(obj) {
13
+ return obj && obj.__esModule ? obj : {
14
+ default: obj
15
+ };
16
+ }
17
+ function countNodes(nodes) {
18
+ let count = 0;
19
+ for (const node of nodes){
20
+ count += 1;
21
+ if (typeof node.walk === "function") {
22
+ node.walk(()=>{
23
+ count += 1;
24
+ });
25
+ }
26
+ }
27
+ return count;
28
+ }
29
+ function collectSourceSequence(sources) {
30
+ const sequence = [];
31
+ for (const { file, source } of sources){
32
+ _postcss.default.parse(source, {
33
+ from: file
34
+ }).walk((node)=>{
35
+ sequence.push(node.source);
36
+ });
37
+ }
38
+ return sequence;
39
+ }
40
+ function assignSourceSequence(nodes, sources) {
41
+ let index = 0;
42
+ for (const node of nodes){
43
+ node.source = sources[index++];
44
+ if (typeof node.walk === "function") {
45
+ node.walk((child)=>{
46
+ child.source = sources[index++];
47
+ });
48
+ }
49
+ }
50
+ }
51
+ function prependDependencySources(css, loader) {
52
+ const sources = Array.isArray(loader.finalSources) ? loader.finalSources : null;
53
+ if (!sources) {
54
+ if (loader.finalSource) css.prepend(loader.finalSource);
55
+ return;
56
+ }
57
+ const joined = sources.map((entry)=>entry.source).join("");
58
+ if (!joined) return;
59
+ const countBefore = css.nodes.length;
60
+ css.prepend(joined);
61
+ const prepended = css.nodes.slice(0, css.nodes.length - countBefore);
62
+ const sourceSequence = collectSourceSequence(sources);
63
+ if (countNodes(prepended) === sourceSequence.length) {
64
+ assignSourceSequence(prepended, sourceSequence);
65
+ }
66
+ }
@@ -10,17 +10,16 @@ Object.defineProperty(exports, "processCSS", {
10
10
  });
11
11
  const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss"));
12
12
  const _fs = require("fs");
13
- const _fs1 = require("./fs");
14
13
  const _pluginFactory = require("./pluginFactory");
15
14
  function _interop_require_default(obj) {
16
15
  return obj && obj.__esModule ? obj : {
17
16
  default: obj
18
17
  };
19
18
  }
20
- (0, _fs1.setFileSystem)({
19
+ const fileSystem = {
21
20
  readFile: _fs.readFile,
22
21
  writeFile: _fs.writeFile
23
- });
22
+ };
24
23
  async function processCSS(source, filename, opts = {}) {
25
24
  let tokens = {};
26
25
  const plugin = (0, _pluginFactory.makePlugin)({
@@ -28,6 +27,8 @@ async function processCSS(source, filename, opts = {}) {
28
27
  getJSON: (_cssFile, json)=>{
29
28
  tokens = json;
30
29
  }
30
+ }, {
31
+ fileSystem
31
32
  });
32
33
  await (0, _postcss.default)([
33
34
  plugin
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "createImportedCSSProcessor", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return createImportedCSSProcessor;
9
+ }
10
+ });
11
+ const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss"));
12
+ const _Parser = /*#__PURE__*/ _interop_require_default(require("./Parser"));
13
+ function _interop_require_default(obj) {
14
+ return obj && obj.__esModule ? obj : {
15
+ default: obj
16
+ };
17
+ }
18
+ function createImportedCSSProcessor(plugins) {
19
+ return async function processImportedCSS(source, sourcePath, dependencyPath, pathFetcher) {
20
+ const parser = new _Parser.default(pathFetcher, dependencyPath);
21
+ const result = await (0, _postcss.default)(plugins.concat([
22
+ parser.plugin()
23
+ ])).process(source, {
24
+ from: sourcePath
25
+ });
26
+ return {
27
+ injectableSource: result.css,
28
+ exportTokens: parser.exportTokens
29
+ };
30
+ };
31
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: Object.getOwnPropertyDescriptor(all, name).get
9
+ });
10
+ }
11
+ _export(exports, {
12
+ get normalizeRoot () {
13
+ return normalizeRoot;
14
+ },
15
+ get resolveImport () {
16
+ return resolveImport;
17
+ }
18
+ });
19
+ const _path = /*#__PURE__*/ _interop_require_default(require("path"));
20
+ function _interop_require_default(obj) {
21
+ return obj && obj.__esModule ? obj : {
22
+ default: obj
23
+ };
24
+ }
25
+ function normalizeRoot(root, platform = process.platform, cwd = process.cwd()) {
26
+ if (root !== "/" || platform !== "win32") return root;
27
+ const cwdDrive = cwd.slice(0, 3);
28
+ if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
29
+ throw new Error(`Failed to obtain root from "${cwd}".`);
30
+ }
31
+ return cwdDrive;
32
+ }
33
+ async function resolveImport({ request, relativeTo, root, fileResolve, resolveModule = require.resolve }) {
34
+ const useFileResolve = typeof fileResolve === "function";
35
+ const resolvedByUser = useFileResolve ? await fileResolve(request, relativeTo) : undefined;
36
+ if (resolvedByUser && !_path.default.isAbsolute(resolvedByUser)) {
37
+ throw new Error('The returned path from the "fileResolve" option must be absolute.');
38
+ }
39
+ const relativeDir = _path.default.dirname(relativeTo);
40
+ const sourcePath = resolvedByUser || _path.default.resolve(relativeDir, request);
41
+ let filePath = resolvedByUser || _path.default.resolve(_path.default.resolve(root, relativeDir), request);
42
+ if (!useFileResolve && request[0] !== "." && !_path.default.isAbsolute(request)) {
43
+ try {
44
+ filePath = resolveModule(request);
45
+ } catch {
46
+ // Keep the path-based fallback when Node cannot resolve the request.
47
+ }
48
+ }
49
+ return {
50
+ filePath,
51
+ sourcePath
52
+ };
53
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: Object.getOwnPropertyDescriptor(all, name).get
9
+ });
10
+ }
11
+ _export(exports, {
12
+ get addDependencyMessages () {
13
+ return addDependencyMessages;
14
+ },
15
+ get addExportMessage () {
16
+ return addExportMessage;
17
+ }
18
+ });
19
+ const PLUGIN_NAME = "postcss-modules";
20
+ function addDependencyMessages(result, loader, inputFile) {
21
+ for (const file of loader.dependencies || []){
22
+ result.messages.push({
23
+ type: "dependency",
24
+ plugin: PLUGIN_NAME,
25
+ file,
26
+ parent: result.opts.from || inputFile
27
+ });
28
+ }
29
+ }
30
+ function addExportMessage(result, exportTokens) {
31
+ result.messages.push({
32
+ type: "export",
33
+ plugin: PLUGIN_NAME,
34
+ exportTokens
35
+ });
36
+ }
package/build/saveJSON.js CHANGED
@@ -5,13 +5,13 @@ Object.defineProperty(exports, "__esModule", {
5
5
  Object.defineProperty(exports, "default", {
6
6
  enumerable: true,
7
7
  get: function() {
8
- return saveJSON;
8
+ return createJSONWriter;
9
9
  }
10
10
  });
11
- const _fs = require("./fs");
12
- function saveJSON(cssFile, json) {
13
- return new Promise((resolve, reject)=>{
14
- const { writeFile } = (0, _fs.getFileSystem)();
15
- writeFile(`${cssFile}.json`, JSON.stringify(json), (e)=>e ? reject(e) : resolve(json));
16
- });
11
+ function createJSONWriter(writeFile) {
12
+ return function saveJSON(cssFile, json) {
13
+ return new Promise((resolve, reject)=>{
14
+ writeFile(`${cssFile}.json`, JSON.stringify(json), (error)=>error ? reject(error) : resolve(json));
15
+ });
16
+ };
17
17
  }
package/build/scoping.js CHANGED
@@ -15,6 +15,9 @@ _export(exports, {
15
15
  get getDefaultPlugins () {
16
16
  return getDefaultPlugins;
17
17
  },
18
+ get getDefaultPluginsList () {
19
+ return getDefaultPluginsList;
20
+ },
18
21
  get getDefaultScopeBehaviour () {
19
22
  return getDefaultScopeBehaviour;
20
23
  },
@@ -80,8 +83,8 @@ function getDefaultScopeBehaviour(scopeBehaviour) {
80
83
  function makeDefaultScopedNameGenerator(hashPrefix) {
81
84
  return function generateScopedNameDefault(name, filename, css) {
82
85
  const i = css.indexOf(`.${name}`);
83
- const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
84
- const hash = (0, _stringhash.default)(`${hashPrefix || ""}${css}`).toString(36).substr(0, 5);
86
+ const lineNumber = css.slice(0, i).split(/[\r\n]/).length;
87
+ const hash = (0, _stringhash.default)(`${hashPrefix || ""}${css}`).toString(36).slice(0, 5);
85
88
  return `_${name}_${hash}_${lineNumber}`;
86
89
  };
87
90
  }
@@ -95,3 +98,18 @@ function getScopedNameGenerator(generateScopedName, hashPrefix) {
95
98
  hashPrefix: hashPrefix
96
99
  });
97
100
  }
101
+ function isGlobalModule(globalModules, inputFile) {
102
+ return globalModules.some((regex)=>inputFile.match(regex));
103
+ }
104
+ function getDefaultPluginsList(opts, inputFile) {
105
+ const globalModules = opts.globalModulePaths || null;
106
+ const exportGlobals = opts.exportGlobals || false;
107
+ const generateScopedName = getScopedNameGenerator(opts.generateScopedName, opts.hashPrefix);
108
+ const configuredBehaviour = getDefaultScopeBehaviour(opts.scopeBehaviour);
109
+ const behaviour = globalModules && isGlobalModule(globalModules, inputFile) ? behaviours.GLOBAL : configuredBehaviour;
110
+ return getDefaultPlugins({
111
+ behaviour,
112
+ generateScopedName,
113
+ exportGlobals
114
+ });
115
+ }
package/index.d.ts CHANGED
@@ -2,18 +2,29 @@ import type { Plugin } from "postcss";
2
2
 
3
3
  declare type GenerateScopedNameFunction = (name: string, filename: string, css: string) => string;
4
4
 
5
+ declare type ResolveFunction = (
6
+ file: string,
7
+ importer: string,
8
+ ) => string | null | Promise<string | null>;
9
+
5
10
  declare type LocalsConventionFunction = (
6
11
  originalClassName: string,
7
12
  generatedClassName: string,
8
- inputFile: string
13
+ inputFile: string,
9
14
  ) => string | string[];
10
15
 
11
16
  declare class Loader {
12
- constructor(root: string, plugins: Plugin[]);
17
+ constructor(root: string, plugins: Plugin[], resolve?: ResolveFunction);
13
18
 
14
- fetch(file: string, relativeTo: string, depTrace: string): Promise<{ [key: string]: string }>;
19
+ fetch(
20
+ file: string,
21
+ relativeTo: string,
22
+ dependencyPath: string,
23
+ ): Promise<{ [key: string]: string }>;
15
24
 
16
25
  finalSource?: string | undefined;
26
+ finalSources?: { file: string; source: string }[] | undefined;
27
+ dependencies?: string[] | undefined;
17
28
  }
18
29
 
19
30
  declare interface Options {
@@ -39,7 +50,7 @@ declare interface Options {
39
50
 
40
51
  Loader?: typeof Loader;
41
52
 
42
- resolve?: (file: string, importer: string) => string | null | Promise<string | null>;
53
+ resolve?: ResolveFunction;
43
54
  }
44
55
 
45
56
  declare interface PostcssModulesPlugin {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postcss-modules",
3
- "version": "9.1.0",
3
+ "version": "9.1.2",
4
4
  "description": "PostCSS plugin to use CSS Modules everywhere",
5
5
  "main": "build/index.js",
6
6
  "types": "index.d.ts",
package/build/fs.js DELETED
@@ -1,33 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: Object.getOwnPropertyDescriptor(all, name).get
9
- });
10
- }
11
- _export(exports, {
12
- get getFileSystem () {
13
- return getFileSystem;
14
- },
15
- get setFileSystem () {
16
- return setFileSystem;
17
- }
18
- });
19
- let fileSystem = {
20
- readFile: ()=>{
21
- throw Error("readFile not implemented");
22
- },
23
- writeFile: ()=>{
24
- throw Error("writeFile not implemented");
25
- }
26
- };
27
- function setFileSystem(fs) {
28
- fileSystem.readFile = fs.readFile;
29
- fileSystem.writeFile = fs.writeFile;
30
- }
31
- function getFileSystem() {
32
- return fileSystem;
33
- }