index.esm.mjs 7.0 KB

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