index.mjs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import postcssBrowserComments from 'postcss-browser-comments';
  2. import Module from 'module';
  3. import path from 'path';
  4. import { URL } from 'url';
  5. import fs from 'fs';
  6. import postcss from 'postcss';
  7. const assign = (...objects) => Object.assign(...objects);
  8. const create = (...objects) => assign(Object.create(null), ...objects);
  9. const currentURL = import.meta.url;
  10. const currentFilename = new URL(currentURL).pathname;
  11. const currentDirname = path.dirname(currentFilename); // get resolved filenames for normalize.css
  12. const normalizeCSS = resolve('@csstools/normalize.css');
  13. const normalizeDir = path.dirname(normalizeCSS);
  14. const normalizeOpinionatedCSS = path.join(normalizeDir, 'opinionated.css'); // get resolved filenames for sanitize.css
  15. const sanitizeCSS = resolve('sanitize.css');
  16. const sanitizeDir = path.dirname(sanitizeCSS);
  17. const sanitizeAssetsCSS = path.join(sanitizeDir, 'assets.css');
  18. const sanitizeFormsCSS = path.join(sanitizeDir, 'forms.css');
  19. const sanitizeReduceMotionCSS = path.join(sanitizeDir, 'reduce-motion.css');
  20. const sanitizeTypographyCSS = path.join(sanitizeDir, 'typography.css');
  21. const sanitizeSystemUiCSS = path.join(sanitizeDir, 'system-ui.css');
  22. const sanitizeUiMonospace = path.join(sanitizeDir, 'ui-monospace.css'); // export a hashmap of css library filenames
  23. const parsableFilenames = create({
  24. [normalizeCSS]: true,
  25. [normalizeOpinionatedCSS]: true,
  26. [sanitizeCSS]: true,
  27. [sanitizeAssetsCSS]: true,
  28. [sanitizeFormsCSS]: true,
  29. [sanitizeReduceMotionCSS]: true,
  30. [sanitizeTypographyCSS]: true,
  31. [sanitizeSystemUiCSS]: true,
  32. [sanitizeUiMonospace]: true
  33. }); // export a hashmap of css library filenames by id
  34. const resolvedFilenamesById = create({
  35. 'normalize': [normalizeCSS],
  36. 'normalize/opinionated': [normalizeOpinionatedCSS],
  37. 'normalize/*': [normalizeOpinionatedCSS],
  38. 'sanitize': [sanitizeCSS],
  39. 'sanitize/assets': [sanitizeAssetsCSS],
  40. 'sanitize/forms': [sanitizeCSS, sanitizeFormsCSS],
  41. 'sanitize/page': [sanitizeAssetsCSS],
  42. // deprecated; remaining for v10.0.0 compatibility
  43. 'sanitize/reduce-motion': [sanitizeCSS, sanitizeReduceMotionCSS],
  44. 'sanitize/system-ui': [sanitizeCSS, sanitizeSystemUiCSS],
  45. 'sanitize/typography': [sanitizeCSS, sanitizeTypographyCSS],
  46. 'sanitize/ui-monospace': [sanitizeCSS, sanitizeUiMonospace],
  47. 'sanitize/*': [sanitizeCSS, sanitizeFormsCSS]
  48. }); // get the resolved filename of a package/module
  49. function resolve(id) {
  50. return resolve[id] = resolve[id] || Module._resolveFilename(id, {
  51. id: currentFilename,
  52. filename: currentFilename,
  53. paths: Module._nodeModulePaths(currentDirname)
  54. });
  55. }
  56. const cache$1 = create();
  57. async function readFile(filename) {
  58. filename = path.resolve(filename);
  59. cache$1[filename] = cache$1[filename] || create();
  60. return new Promise((resolve, reject) => fs.stat(filename, (statsError, {
  61. mtime
  62. }) => statsError ? reject(statsError) : mtime === cache$1[filename].mtime ? resolve(cache$1[filename].data) : fs.readFile(filename, 'utf8', (readFileError, data) => readFileError ? reject(readFileError) : resolve((cache$1[filename] = {
  63. data,
  64. mtime
  65. }).data))));
  66. }
  67. const cache = create(null);
  68. var parse = ((filename, transformer) => readFile(filename).then( // cache the parsed css root
  69. css => cache[css] = cache[css] || postcss.parse(css, {
  70. from: filename
  71. })).then( // clone the cached root
  72. root => root.clone()).then( // transform the cloned root
  73. clone => Promise.resolve(transformer(clone)).then( // resolve the cloned root
  74. () => clone)));
  75. var postcssImportNormalize = (commentsTransformer => opts => {
  76. opts = create(opts); // return an postcss-import configuration
  77. return create({
  78. load(filename, importOptions) {
  79. return filename in parsableFilenames // parse the file (the file and css are conservatively cached)
  80. ? parse(filename, commentsTransformer).then(root => root.toResult({
  81. to: filename,
  82. map: true
  83. }).css) : typeof opts.load === 'function' // otherwise, use the override loader
  84. ? opts.load.call(null, filename, importOptions) // otherwise, return the (conservatively cached) contents of the file
  85. : readFile(filename);
  86. },
  87. resolve(id, basedir, importOptions) {
  88. // get the css id by removing css extensions
  89. const cssId = id.replace(cssExtRegExp$1, '');
  90. return cssId in resolvedFilenamesById // return the known resolved path for the css id
  91. ? resolvedFilenamesById[cssId] : typeof opts.resolve === 'function' // otherwise, use the override resolver
  92. ? opts.resolve.call(null, id, basedir, importOptions) // otherwise, return the id to be resolved by postcss-import
  93. : id;
  94. }
  95. });
  96. });
  97. const cssExtRegExp$1 = /\.css\b/g;
  98. const postcssPlugin = (commentsTransformer, opts) => root => {
  99. const promises = [];
  100. const insertedFilenames = {}; // use @import insertion point
  101. root.walkAtRules(importRegExp, atrule => {
  102. // get name as a fallback value for the library (e.g. @import-normalize is like @import "normalize.css")
  103. const name = atrule.name.match(importRegExp)[1]; // get url from "library", 'library', url("library"), url('library'), or the fallback value
  104. const url = (atrule.params.match(paramsRegExp) || []).slice(1).find(part => part) || name;
  105. if (url) {
  106. // get the css id by removing css extensions
  107. const cssId = url.replace(cssExtRegExp, '');
  108. if (cssId in resolvedFilenamesById) {
  109. // promise the library import is replaced with its contents
  110. promises.push(Promise.all(resolvedFilenamesById[cssId].filter( // ignore filenames that have already been inserted
  111. filename => insertedFilenames[filename] = opts.allowDuplicates || !(filename in insertedFilenames)).map( // parse the file (the file and css are conservatively cached)
  112. filename => parse(filename, commentsTransformer))).then(roots => {
  113. if (roots.length) {
  114. // combine all the library nodes returned by the parsed files
  115. const nodes = roots.reduce((all, root) => all.concat(root.nodes), []); // replace the import with all the library nodes
  116. atrule.replaceWith(...nodes);
  117. }
  118. }));
  119. }
  120. }
  121. });
  122. return Promise.all([].concat( // promise the library imports are replaced with their contents
  123. promises, // promise certain libraries are prepended
  124. Promise.all([].concat(opts.forceImport || []).reduce( // filter the id to be a known id or boolean true
  125. (all, id) => {
  126. if (id === true) {
  127. all.push(...resolvedFilenamesById.normalize);
  128. } else if (typeof id === 'string') {
  129. const cssId = id.replace(cssExtRegExp, '');
  130. if (cssId in resolvedFilenamesById) {
  131. all.push(...resolvedFilenamesById[cssId]);
  132. }
  133. }
  134. return all;
  135. }, []).filter( // ignore filenames that have already been inserted
  136. filename => insertedFilenames[filename] = opts.allowDuplicates || !(filename in insertedFilenames)).map( // parse the file (the file and css are conservatively cached)
  137. filename => parse(filename, commentsTransformer))).then(roots => {
  138. if (roots.length) {
  139. // combine all the library nodes returned by the parsed files
  140. const nodes = roots.reduce((all, root) => all.concat(root.nodes), []); // prepend the stylesheet with all the library nodes
  141. root.prepend(...nodes);
  142. }
  143. })));
  144. };
  145. const cssExtRegExp = /\.css\b/g;
  146. const importRegExp = /^import(?:-(normalize|sanitize))?$/;
  147. const paramsRegExp = /^\s*(?:url\((?:"(.+)"|'(.+)')\)|"(.+)"|'(.+)')[\W\w]*$/;
  148. const plugin = opts => {
  149. opts = create(opts);
  150. const commentsTransformer = postcssBrowserComments(opts).Once;
  151. const normalizeTransformer = postcssPlugin(commentsTransformer, opts);
  152. const postcssImportConfig = postcssImportNormalize(commentsTransformer);
  153. return {
  154. postcssPlugin: 'postcss-normalize',
  155. Once(root) {
  156. return normalizeTransformer(root);
  157. },
  158. postcssImport: postcssImportConfig
  159. };
  160. };
  161. plugin.postcss = true;
  162. export { plugin as default };