index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. "use strict";
  2. const selectorParser = require("postcss-selector-parser");
  3. const valueParser = require("postcss-value-parser");
  4. const { extractICSS } = require("icss-utils");
  5. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  6. function normalizeNodeArray(nodes) {
  7. const array = [];
  8. nodes.forEach((x) => {
  9. if (Array.isArray(x)) {
  10. normalizeNodeArray(x).forEach((item) => {
  11. array.push(item);
  12. });
  13. } else if (x) {
  14. array.push(x);
  15. }
  16. });
  17. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  18. array.pop();
  19. }
  20. return array;
  21. }
  22. function localizeNode(rule, mode, localAliasMap) {
  23. const transform = (node, context) => {
  24. if (context.ignoreNextSpacing && !isSpacing(node)) {
  25. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  26. }
  27. if (context.enforceNoSpacing && isSpacing(node)) {
  28. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  29. }
  30. let newNodes;
  31. switch (node.type) {
  32. case "root": {
  33. let resultingGlobal;
  34. context.hasPureGlobals = false;
  35. newNodes = node.nodes.map((n) => {
  36. const nContext = {
  37. global: context.global,
  38. lastWasSpacing: true,
  39. hasLocals: false,
  40. explicit: false,
  41. };
  42. n = transform(n, nContext);
  43. if (typeof resultingGlobal === "undefined") {
  44. resultingGlobal = nContext.global;
  45. } else if (resultingGlobal !== nContext.global) {
  46. throw new Error(
  47. 'Inconsistent rule global/local result in rule "' +
  48. node +
  49. '" (multiple selectors must result in the same mode for the rule)'
  50. );
  51. }
  52. if (!nContext.hasLocals) {
  53. context.hasPureGlobals = true;
  54. }
  55. return n;
  56. });
  57. context.global = resultingGlobal;
  58. node.nodes = normalizeNodeArray(newNodes);
  59. break;
  60. }
  61. case "selector": {
  62. newNodes = node.map((childNode) => transform(childNode, context));
  63. node = node.clone();
  64. node.nodes = normalizeNodeArray(newNodes);
  65. break;
  66. }
  67. case "combinator": {
  68. if (isSpacing(node)) {
  69. if (context.ignoreNextSpacing) {
  70. context.ignoreNextSpacing = false;
  71. context.lastWasSpacing = false;
  72. context.enforceNoSpacing = false;
  73. return null;
  74. }
  75. context.lastWasSpacing = true;
  76. return node;
  77. }
  78. break;
  79. }
  80. case "pseudo": {
  81. let childContext;
  82. const isNested = !!node.length;
  83. const isScoped = node.value === ":local" || node.value === ":global";
  84. const isImportExport =
  85. node.value === ":import" || node.value === ":export";
  86. if (isImportExport) {
  87. context.hasLocals = true;
  88. // :local(.foo)
  89. } else if (isNested) {
  90. if (isScoped) {
  91. if (node.nodes.length === 0) {
  92. throw new Error(`${node.value}() can't be empty`);
  93. }
  94. if (context.inside) {
  95. throw new Error(
  96. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  97. );
  98. }
  99. childContext = {
  100. global: node.value === ":global",
  101. inside: node.value,
  102. hasLocals: false,
  103. explicit: true,
  104. };
  105. newNodes = node
  106. .map((childNode) => transform(childNode, childContext))
  107. .reduce((acc, next) => acc.concat(next.nodes), []);
  108. if (newNodes.length) {
  109. const { before, after } = node.spaces;
  110. const first = newNodes[0];
  111. const last = newNodes[newNodes.length - 1];
  112. first.spaces = { before, after: first.spaces.after };
  113. last.spaces = { before: last.spaces.before, after };
  114. }
  115. node = newNodes;
  116. break;
  117. } else {
  118. childContext = {
  119. global: context.global,
  120. inside: context.inside,
  121. lastWasSpacing: true,
  122. hasLocals: false,
  123. explicit: context.explicit,
  124. };
  125. newNodes = node.map((childNode) => {
  126. const newContext = {
  127. ...childContext,
  128. enforceNoSpacing: false,
  129. };
  130. const result = transform(childNode, newContext);
  131. childContext.global = newContext.global;
  132. childContext.hasLocals = newContext.hasLocals;
  133. return result;
  134. });
  135. node = node.clone();
  136. node.nodes = normalizeNodeArray(newNodes);
  137. if (childContext.hasLocals) {
  138. context.hasLocals = true;
  139. }
  140. }
  141. break;
  142. //:local .foo .bar
  143. } else if (isScoped) {
  144. if (context.inside) {
  145. throw new Error(
  146. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  147. );
  148. }
  149. const addBackSpacing = !!node.spaces.before;
  150. context.ignoreNextSpacing = context.lastWasSpacing
  151. ? node.value
  152. : false;
  153. context.enforceNoSpacing = context.lastWasSpacing
  154. ? false
  155. : node.value;
  156. context.global = node.value === ":global";
  157. context.explicit = true;
  158. // because this node has spacing that is lost when we remove it
  159. // we make up for it by adding an extra combinator in since adding
  160. // spacing on the parent selector doesn't work
  161. return addBackSpacing
  162. ? selectorParser.combinator({ value: " " })
  163. : null;
  164. }
  165. break;
  166. }
  167. case "id":
  168. case "class": {
  169. if (!node.value) {
  170. throw new Error("Invalid class or id selector syntax");
  171. }
  172. if (context.global) {
  173. break;
  174. }
  175. const isImportedValue = localAliasMap.has(node.value);
  176. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  177. if (!isImportedValue || isImportedWithExplicitScope) {
  178. const innerNode = node.clone();
  179. innerNode.spaces = { before: "", after: "" };
  180. node = selectorParser.pseudo({
  181. value: ":local",
  182. nodes: [innerNode],
  183. spaces: node.spaces,
  184. });
  185. context.hasLocals = true;
  186. }
  187. break;
  188. }
  189. }
  190. context.lastWasSpacing = false;
  191. context.ignoreNextSpacing = false;
  192. context.enforceNoSpacing = false;
  193. return node;
  194. };
  195. const rootContext = {
  196. global: mode === "global",
  197. hasPureGlobals: false,
  198. };
  199. rootContext.selector = selectorParser((root) => {
  200. transform(root, rootContext);
  201. }).processSync(rule, { updateSelector: false, lossless: true });
  202. return rootContext;
  203. }
  204. function localizeDeclNode(node, context) {
  205. switch (node.type) {
  206. case "word":
  207. if (context.localizeNextItem) {
  208. if (!context.localAliasMap.has(node.value)) {
  209. node.value = ":local(" + node.value + ")";
  210. context.localizeNextItem = false;
  211. }
  212. }
  213. break;
  214. case "function":
  215. if (
  216. context.options &&
  217. context.options.rewriteUrl &&
  218. node.value.toLowerCase() === "url"
  219. ) {
  220. node.nodes.map((nestedNode) => {
  221. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  222. return;
  223. }
  224. let newUrl = context.options.rewriteUrl(
  225. context.global,
  226. nestedNode.value
  227. );
  228. switch (nestedNode.type) {
  229. case "string":
  230. if (nestedNode.quote === "'") {
  231. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  232. }
  233. if (nestedNode.quote === '"') {
  234. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  235. }
  236. break;
  237. case "word":
  238. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  239. break;
  240. }
  241. nestedNode.value = newUrl;
  242. });
  243. }
  244. break;
  245. }
  246. return node;
  247. }
  248. // `none` is special value, other is global values
  249. const specialKeywords = [
  250. "none",
  251. "inherit",
  252. "initial",
  253. "revert",
  254. "revert-layer",
  255. "unset",
  256. ];
  257. function localizeDeclarationValues(localize, declaration, context) {
  258. const valueNodes = valueParser(declaration.value);
  259. valueNodes.walk((node, index, nodes) => {
  260. if (
  261. node.type === "function" &&
  262. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  263. ) {
  264. return false;
  265. }
  266. if (
  267. node.type === "word" &&
  268. specialKeywords.includes(node.value.toLowerCase())
  269. ) {
  270. return;
  271. }
  272. const subContext = {
  273. options: context.options,
  274. global: context.global,
  275. localizeNextItem: localize && !context.global,
  276. localAliasMap: context.localAliasMap,
  277. };
  278. nodes[index] = localizeDeclNode(node, subContext);
  279. });
  280. declaration.value = valueNodes.toString();
  281. }
  282. function localizeDeclaration(declaration, context) {
  283. const isAnimation = /animation$/i.test(declaration.prop);
  284. if (isAnimation) {
  285. // letter
  286. // An uppercase letter or a lowercase letter.
  287. //
  288. // ident-start code point
  289. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  290. //
  291. // ident code point
  292. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  293. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  294. const validIdent =
  295. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-)((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  296. /*
  297. The spec defines some keywords that you can use to describe properties such as the timing
  298. function. These are still valid animation names, so as long as there is a property that accepts
  299. a keyword, it is given priority. Only when all the properties that can take a keyword are
  300. exhausted can the animation name be set to the keyword. I.e.
  301. animation: infinite infinite;
  302. The animation will repeat an infinite number of times from the first argument, and will have an
  303. animation name of infinite from the second.
  304. */
  305. const animationKeywords = {
  306. // animation-direction
  307. $normal: 1,
  308. $reverse: 1,
  309. $alternate: 1,
  310. "$alternate-reverse": 1,
  311. // animation-fill-mode
  312. $forwards: 1,
  313. $backwards: 1,
  314. $both: 1,
  315. // animation-iteration-count
  316. $infinite: 1,
  317. // animation-play-state
  318. $paused: 1,
  319. $running: 1,
  320. // animation-timing-function
  321. $ease: 1,
  322. "$ease-in": 1,
  323. "$ease-out": 1,
  324. "$ease-in-out": 1,
  325. $linear: 1,
  326. "$step-end": 1,
  327. "$step-start": 1,
  328. // Special
  329. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  330. // Global values
  331. $initial: Infinity,
  332. $inherit: Infinity,
  333. $unset: Infinity,
  334. $revert: Infinity,
  335. "$revert-layer": Infinity,
  336. };
  337. let parsedAnimationKeywords = {};
  338. const valueNodes = valueParser(declaration.value).walk((node) => {
  339. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  340. if (node.type === "div") {
  341. parsedAnimationKeywords = {};
  342. return;
  343. }
  344. // Do not handle nested functions
  345. else if (node.type === "function") {
  346. return false;
  347. }
  348. // Ignore all except word
  349. else if (node.type !== "word") {
  350. return;
  351. }
  352. const value = node.type === "word" ? node.value.toLowerCase() : null;
  353. let shouldParseAnimationName = false;
  354. if (value && validIdent.test(value)) {
  355. if ("$" + value in animationKeywords) {
  356. parsedAnimationKeywords["$" + value] =
  357. "$" + value in parsedAnimationKeywords
  358. ? parsedAnimationKeywords["$" + value] + 1
  359. : 0;
  360. shouldParseAnimationName =
  361. parsedAnimationKeywords["$" + value] >=
  362. animationKeywords["$" + value];
  363. } else {
  364. shouldParseAnimationName = true;
  365. }
  366. }
  367. const subContext = {
  368. options: context.options,
  369. global: context.global,
  370. localizeNextItem: shouldParseAnimationName && !context.global,
  371. localAliasMap: context.localAliasMap,
  372. };
  373. return localizeDeclNode(node, subContext);
  374. });
  375. declaration.value = valueNodes.toString();
  376. return;
  377. }
  378. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  379. if (isAnimationName) {
  380. return localizeDeclarationValues(true, declaration, context);
  381. }
  382. const hasUrl = /url\(/i.test(declaration.value);
  383. if (hasUrl) {
  384. return localizeDeclarationValues(false, declaration, context);
  385. }
  386. }
  387. module.exports = (options = {}) => {
  388. if (
  389. options &&
  390. options.mode &&
  391. options.mode !== "global" &&
  392. options.mode !== "local" &&
  393. options.mode !== "pure"
  394. ) {
  395. throw new Error(
  396. 'options.mode must be either "global", "local" or "pure" (default "local")'
  397. );
  398. }
  399. const pureMode = options && options.mode === "pure";
  400. const globalMode = options && options.mode === "global";
  401. return {
  402. postcssPlugin: "postcss-modules-local-by-default",
  403. prepare() {
  404. const localAliasMap = new Map();
  405. return {
  406. Once(root) {
  407. const { icssImports } = extractICSS(root, false);
  408. Object.keys(icssImports).forEach((key) => {
  409. Object.keys(icssImports[key]).forEach((prop) => {
  410. localAliasMap.set(prop, icssImports[key][prop]);
  411. });
  412. });
  413. root.walkAtRules((atRule) => {
  414. if (/keyframes$/i.test(atRule.name)) {
  415. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  416. atRule.params
  417. );
  418. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  419. atRule.params
  420. );
  421. let globalKeyframes = globalMode;
  422. if (globalMatch) {
  423. if (pureMode) {
  424. throw atRule.error(
  425. "@keyframes :global(...) is not allowed in pure mode"
  426. );
  427. }
  428. atRule.params = globalMatch[1];
  429. globalKeyframes = true;
  430. } else if (localMatch) {
  431. atRule.params = localMatch[0];
  432. globalKeyframes = false;
  433. } else if (!globalMode) {
  434. if (atRule.params && !localAliasMap.has(atRule.params)) {
  435. atRule.params = ":local(" + atRule.params + ")";
  436. }
  437. }
  438. atRule.walkDecls((declaration) => {
  439. localizeDeclaration(declaration, {
  440. localAliasMap,
  441. options: options,
  442. global: globalKeyframes,
  443. });
  444. });
  445. } else if (atRule.nodes) {
  446. atRule.nodes.forEach((declaration) => {
  447. if (declaration.type === "decl") {
  448. localizeDeclaration(declaration, {
  449. localAliasMap,
  450. options: options,
  451. global: globalMode,
  452. });
  453. }
  454. });
  455. }
  456. });
  457. root.walkRules((rule) => {
  458. if (
  459. rule.parent &&
  460. rule.parent.type === "atrule" &&
  461. /keyframes$/i.test(rule.parent.name)
  462. ) {
  463. // ignore keyframe rules
  464. return;
  465. }
  466. const context = localizeNode(rule, options.mode, localAliasMap);
  467. context.options = options;
  468. context.localAliasMap = localAliasMap;
  469. if (pureMode && context.hasPureGlobals) {
  470. throw rule.error(
  471. 'Selector "' +
  472. rule.selector +
  473. '" is not pure ' +
  474. "(pure selectors must contain at least one local class or id)"
  475. );
  476. }
  477. rule.selector = context.selector;
  478. // Less-syntax mixins parse as rules with no nodes
  479. if (rule.nodes) {
  480. rule.nodes.forEach((declaration) =>
  481. localizeDeclaration(declaration, context)
  482. );
  483. }
  484. });
  485. },
  486. };
  487. },
  488. };
  489. };
  490. module.exports.postcss = true;