Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

babel-plugin-emotion.cjs.dev.js 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  4. var nodePath = _interopDefault(require('path'));
  5. var sourceMap = require('source-map');
  6. var convert = _interopDefault(require('convert-source-map'));
  7. var findRoot = _interopDefault(require('find-root'));
  8. var memoize = _interopDefault(require('@emotion/memoize'));
  9. var hashString = _interopDefault(require('@emotion/hash'));
  10. var escapeRegexp = _interopDefault(require('escape-string-regexp'));
  11. var serialize = require('@emotion/serialize');
  12. var helperModuleImports = require('@babel/helper-module-imports');
  13. var babelPluginMacros = require('babel-plugin-macros');
  14. // babel-plugin-styled-components
  15. // https://github.com/styled-components/babel-plugin-styled-components/blob/8d44acc36f067d60d4e09f9c22ff89695bc332d2/src/minify/index.js
  16. var multilineCommentRegex = /\/\*[^!](.|[\r\n])*?\*\//g;
  17. var lineCommentStart = /\/\//g;
  18. var symbolRegex = /(\s*[;:{},]\s*)/g; // Counts occurences of substr inside str
  19. var countOccurences = function countOccurences(str, substr) {
  20. return str.split(substr).length - 1;
  21. }; // Joins substrings until predicate returns true
  22. var reduceSubstr = function reduceSubstr(substrs, join, predicate) {
  23. var length = substrs.length;
  24. var res = substrs[0];
  25. if (length === 1) {
  26. return res;
  27. }
  28. for (var i = 1; i < length; i++) {
  29. if (predicate(res)) {
  30. break;
  31. }
  32. res += join + substrs[i];
  33. }
  34. return res;
  35. }; // Joins at comment starts when it's inside a string or parantheses
  36. // effectively removing line comments
  37. var stripLineComment = function stripLineComment(line) {
  38. return reduceSubstr(line.split(lineCommentStart), '//', function (str) {
  39. return !str.endsWith(':') && // NOTE: This is another guard against urls, if they're not inside strings or parantheses.
  40. countOccurences(str, "'") % 2 === 0 && countOccurences(str, '"') % 2 === 0 && countOccurences(str, '(') === countOccurences(str, ')');
  41. });
  42. };
  43. var compressSymbols = function compressSymbols(code) {
  44. return code.split(symbolRegex).reduce(function (str, fragment, index) {
  45. // Even-indices are non-symbol fragments
  46. if (index % 2 === 0) {
  47. return str + fragment;
  48. } // Only manipulate symbols outside of strings
  49. if (countOccurences(str, "'") % 2 === 0 && countOccurences(str, '"') % 2 === 0) {
  50. return str + fragment.trim();
  51. }
  52. return str + fragment;
  53. }, '');
  54. }; // Detects lines that are exclusively line comments
  55. var isLineComment = function isLineComment(line) {
  56. return line.trim().startsWith('//');
  57. };
  58. var linebreakRegex = /[\r\n]\s*/g;
  59. var spacesAndLinebreakRegex = /\s+|\n+/g;
  60. function multilineReplacer(match) {
  61. // When we encounter a standard multi-line CSS comment and it contains a '@'
  62. // character, we keep the comment but optimize it into a single line. Some
  63. // Stylis plugins, such as the stylis-rtl via the cssjanus plugin, use this
  64. // special comment syntax to control behavior (such as: /* @noflip */).
  65. // We can do this with standard CSS comments because they will work with
  66. // compression, as opposed to non-standard single-line comments that will
  67. // break compressed CSS. If the comment doesn't contain '@', then we replace
  68. // it with a line break, which effectively removes it from the output.
  69. var keepComment = match.indexOf('@') > -1;
  70. if (keepComment) {
  71. return match.replace(spacesAndLinebreakRegex, ' ').trim();
  72. }
  73. return '\n';
  74. }
  75. var minify = function minify(code) {
  76. var newCode = code.replace(multilineCommentRegex, multilineReplacer) // If allowed, remove line breaks and extra space from multi-line comments so they appear on one line
  77. .split(linebreakRegex) // Split at newlines
  78. .filter(function (line) {
  79. return line.length > 0 && !isLineComment(line);
  80. }) // Removes lines containing only line comments
  81. .map(stripLineComment) // Remove line comments inside text
  82. .join(' '); // Rejoin all lines
  83. return compressSymbols(newCode);
  84. };
  85. function getExpressionsFromTemplateLiteral(node, t) {
  86. var raw = createRawStringFromTemplateLiteral(node);
  87. var minified = minify(raw);
  88. return replacePlaceholdersWithExpressions(minified, node.expressions || [], t);
  89. }
  90. var interleave = function interleave(strings, interpolations) {
  91. return interpolations.reduce(function (array, interp, i) {
  92. return array.concat([interp], strings[i + 1]);
  93. }, [strings[0]]);
  94. };
  95. function getDynamicMatches(str) {
  96. var re = /xxx(\d+)xxx/gm;
  97. var match;
  98. var matches = [];
  99. while ((match = re.exec(str)) !== null) {
  100. // so that flow doesn't complain
  101. if (match !== null) {
  102. matches.push({
  103. value: match[0],
  104. p1: parseInt(match[1], 10),
  105. index: match.index
  106. });
  107. }
  108. }
  109. return matches;
  110. }
  111. function replacePlaceholdersWithExpressions(str, expressions, t) {
  112. var matches = getDynamicMatches(str);
  113. if (matches.length === 0) {
  114. if (str === '') {
  115. return [];
  116. }
  117. return [t.stringLiteral(str)];
  118. }
  119. var strings = [];
  120. var finalExpressions = [];
  121. var cursor = 0;
  122. matches.forEach(function (_ref, i) {
  123. var value = _ref.value,
  124. p1 = _ref.p1,
  125. index = _ref.index;
  126. var preMatch = str.substring(cursor, index);
  127. cursor = cursor + preMatch.length + value.length;
  128. if (preMatch) {
  129. strings.push(t.stringLiteral(preMatch));
  130. } else if (i === 0) {
  131. strings.push(t.stringLiteral(''));
  132. }
  133. finalExpressions.push(expressions[p1]);
  134. if (i === matches.length - 1) {
  135. strings.push(t.stringLiteral(str.substring(index + value.length)));
  136. }
  137. });
  138. return interleave(strings, finalExpressions).filter(function (node) {
  139. return node.value !== '';
  140. });
  141. }
  142. function createRawStringFromTemplateLiteral(quasi) {
  143. var strs = quasi.quasis.map(function (x) {
  144. return x.value.cooked;
  145. });
  146. var src = strs.reduce(function (arr, str, i) {
  147. arr.push(str);
  148. if (i !== strs.length - 1) {
  149. arr.push("xxx" + i + "xxx");
  150. }
  151. return arr;
  152. }, []).join('').trim();
  153. return src;
  154. }
  155. var invalidClassNameCharacters = /[!"#$%&'()*+,./:;<=>?@[\]^`|}~{]/g;
  156. var sanitizeLabelPart = function sanitizeLabelPart(labelPart) {
  157. return labelPart.trim().replace(invalidClassNameCharacters, '-');
  158. };
  159. function getLabel(identifierName, autoLabel, labelFormat, filename) {
  160. if (!identifierName || !autoLabel) return null;
  161. if (!labelFormat) return sanitizeLabelPart(identifierName);
  162. var parsedPath = nodePath.parse(filename);
  163. var localDirname = nodePath.basename(parsedPath.dir);
  164. var localFilename = parsedPath.name;
  165. if (localFilename === 'index') {
  166. localFilename = localDirname;
  167. }
  168. return labelFormat.replace(/\[local\]/gi, sanitizeLabelPart(identifierName)).replace(/\[filename\]/gi, sanitizeLabelPart(localFilename)).replace(/\[dirname\]/gi, sanitizeLabelPart(localDirname));
  169. }
  170. function getLabelFromPath(path, state, t) {
  171. return getLabel(getIdentifierName(path, t), state.opts.autoLabel === undefined ? process.env.NODE_ENV !== 'production' : state.opts.autoLabel, state.opts.labelFormat, state.file.opts.filename);
  172. }
  173. var pascalCaseRegex = /^[A-Z][A-Za-z]+/;
  174. function getDeclaratorName(path, t) {
  175. // $FlowFixMe
  176. var parent = path.findParent(function (p) {
  177. return p.isVariableDeclarator() || p.isFunctionDeclaration() || p.isFunctionExpression() || p.isArrowFunctionExpression() || p.isObjectProperty();
  178. });
  179. if (!parent) {
  180. return '';
  181. } // we probably have a css call assigned to a variable
  182. // so we'll just return the variable name
  183. if (parent.isVariableDeclarator()) {
  184. if (t.isIdentifier(parent.node.id)) {
  185. return parent.node.id.name;
  186. }
  187. return '';
  188. } // we probably have an inline css prop usage
  189. if (parent.isFunctionDeclaration()) {
  190. var _name = parent.node.id.name;
  191. if (pascalCaseRegex.test(_name)) {
  192. return _name;
  193. }
  194. return '';
  195. } // we could also have an object property
  196. if (parent.isObjectProperty() && !parent.node.computed) {
  197. return parent.node.key.name;
  198. }
  199. var variableDeclarator = path.findParent(function (p) {
  200. return p.isVariableDeclarator();
  201. });
  202. if (!variableDeclarator) {
  203. return '';
  204. }
  205. var name = variableDeclarator.node.id.name;
  206. if (pascalCaseRegex.test(name)) {
  207. return name;
  208. }
  209. return '';
  210. }
  211. function getIdentifierName(path, t) {
  212. var classOrClassPropertyParent;
  213. if (t.isObjectProperty(path.parentPath) && path.parentPath.node.computed === false && (t.isIdentifier(path.parentPath.node.key) || t.isStringLiteral(path.parentPath.node.key))) {
  214. return path.parentPath.node.key.name || path.parentPath.node.key.value;
  215. }
  216. if (path) {
  217. // $FlowFixMe
  218. classOrClassPropertyParent = path.findParent(function (p) {
  219. return t.isClassProperty(p) || t.isClass(p);
  220. });
  221. }
  222. if (classOrClassPropertyParent) {
  223. if (t.isClassProperty(classOrClassPropertyParent) && classOrClassPropertyParent.node.computed === false && t.isIdentifier(classOrClassPropertyParent.node.key)) {
  224. return classOrClassPropertyParent.node.key.name;
  225. }
  226. if (t.isClass(classOrClassPropertyParent) && classOrClassPropertyParent.node.id) {
  227. return t.isIdentifier(classOrClassPropertyParent.node.id) ? classOrClassPropertyParent.node.id.name : '';
  228. }
  229. }
  230. var declaratorName = getDeclaratorName(path, t); // if the name starts with _ it was probably generated by babel so we should ignore it
  231. if (declaratorName.charAt(0) === '_') {
  232. return '';
  233. }
  234. return declaratorName;
  235. }
  236. function getGeneratorOpts(file) {
  237. return file.opts.generatorOpts ? file.opts.generatorOpts : file.opts;
  238. }
  239. function makeSourceMapGenerator(file) {
  240. var generatorOpts = getGeneratorOpts(file);
  241. var filename = generatorOpts.sourceFileName;
  242. var generator = new sourceMap.SourceMapGenerator({
  243. file: filename,
  244. sourceRoot: generatorOpts.sourceRoot
  245. });
  246. generator.setSourceContent(filename, file.code);
  247. return generator;
  248. }
  249. function getSourceMap(offset, state) {
  250. var generator = makeSourceMapGenerator(state.file);
  251. var generatorOpts = getGeneratorOpts(state.file);
  252. if (generatorOpts.sourceFileName && generatorOpts.sourceFileName !== 'unknown') {
  253. generator.addMapping({
  254. generated: {
  255. line: 1,
  256. column: 0
  257. },
  258. source: generatorOpts.sourceFileName,
  259. original: offset
  260. });
  261. return convert.fromObject(generator).toComment({
  262. multiline: true
  263. });
  264. }
  265. return '';
  266. }
  267. var hashArray = function hashArray(arr) {
  268. return hashString(arr.join(''));
  269. };
  270. var unsafeRequire = require;
  271. var getPackageRootPath = memoize(function (filename) {
  272. return findRoot(filename);
  273. });
  274. var separator = new RegExp(escapeRegexp(nodePath.sep), 'g');
  275. var normalizePath = function normalizePath(path) {
  276. return nodePath.normalize(path).replace(separator, '/');
  277. };
  278. function getTargetClassName(state, t) {
  279. if (state.emotionTargetClassNameCount === undefined) {
  280. state.emotionTargetClassNameCount = 0;
  281. }
  282. var hasFilepath = state.file.opts.filename && state.file.opts.filename !== 'unknown';
  283. var filename = hasFilepath ? state.file.opts.filename : ''; // normalize the file path to ignore folder structure
  284. // outside the current node project and arch-specific delimiters
  285. var moduleName = '';
  286. var rootPath = filename;
  287. try {
  288. rootPath = getPackageRootPath(filename);
  289. moduleName = unsafeRequire(rootPath + '/package.json').name;
  290. } catch (err) {}
  291. var finalPath = filename === rootPath ? 'root' : filename.slice(rootPath.length);
  292. var positionInFile = state.emotionTargetClassNameCount++;
  293. var stuffToHash = [moduleName];
  294. if (finalPath) {
  295. stuffToHash.push(normalizePath(finalPath));
  296. } else {
  297. stuffToHash.push(state.file.code);
  298. }
  299. var stableClassName = "e" + hashArray(stuffToHash) + positionInFile;
  300. return stableClassName;
  301. }
  302. // it's meant to simplify the most common cases so i don't want to make it especially complex
  303. // also, this will be unnecessary when prepack is ready
  304. function simplifyObject(node, t) {
  305. var finalString = '';
  306. for (var i = 0; i < node.properties.length; i++) {
  307. var _ref;
  308. var property = node.properties[i];
  309. if (!t.isObjectProperty(property) || property.computed || !t.isIdentifier(property.key) && !t.isStringLiteral(property.key) || !t.isStringLiteral(property.value) && !t.isNumericLiteral(property.value) && !t.isObjectExpression(property.value)) {
  310. return node;
  311. }
  312. var key = property.key.name || property.key.value;
  313. if (key === 'styles') {
  314. return node;
  315. }
  316. if (t.isObjectExpression(property.value)) {
  317. var simplifiedChild = simplifyObject(property.value, t);
  318. if (!t.isStringLiteral(simplifiedChild)) {
  319. return node;
  320. }
  321. finalString += key + "{" + simplifiedChild.value + "}";
  322. continue;
  323. }
  324. var value = property.value.value;
  325. finalString += serialize.serializeStyles([(_ref = {}, _ref[key] = value, _ref)]).styles;
  326. }
  327. return t.stringLiteral(finalString);
  328. }
  329. function isTaggedTemplateExpressionTranspiledByTypeScript(path) {
  330. if (path.node.arguments.length !== 1) {
  331. return false;
  332. }
  333. var argPath = path.get('arguments')[0];
  334. return argPath.isLogicalExpression() && argPath.get('left').isIdentifier() && argPath.node.left.name.includes('templateObject') && argPath.get('right').isAssignmentExpression() && argPath.get('right').get('right').isCallExpression() && argPath.get('right').get('right').get('callee').isIdentifier() && argPath.node.right.right.callee.name.includes('makeTemplateObject') && argPath.node.right.right.arguments.length === 2;
  335. }
  336. var appendStringToArguments = function appendStringToArguments(path, string, t) {
  337. if (!string) {
  338. return;
  339. }
  340. var args = path.node.arguments;
  341. if (t.isStringLiteral(args[args.length - 1])) {
  342. args[args.length - 1].value += string;
  343. } else if (isTaggedTemplateExpressionTranspiledByTypeScript(path)) {
  344. var makeTemplateObjectCallPath = path.get('arguments')[0].get('right').get('right');
  345. makeTemplateObjectCallPath.get('arguments').forEach(function (argPath) {
  346. var elements = argPath.get('elements');
  347. var lastElement = elements[elements.length - 1];
  348. lastElement.replaceWith(t.stringLiteral(lastElement.node.value + string));
  349. });
  350. } else {
  351. args.push(t.stringLiteral(string));
  352. }
  353. };
  354. var joinStringLiterals = function joinStringLiterals(expressions, t) {
  355. return expressions.reduce(function (finalExpressions, currentExpression, i) {
  356. if (!t.isStringLiteral(currentExpression)) {
  357. finalExpressions.push(currentExpression);
  358. } else if (t.isStringLiteral(finalExpressions[finalExpressions.length - 1])) {
  359. finalExpressions[finalExpressions.length - 1].value += currentExpression.value;
  360. } else {
  361. finalExpressions.push(currentExpression);
  362. }
  363. return finalExpressions;
  364. }, []);
  365. };
  366. var CSS_OBJECT_STRINGIFIED_ERROR = "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; // with babel@6 fallback
  367. var cloneNode = function cloneNode(t, node) {
  368. return typeof t.cloneNode === 'function' ? t.cloneNode(node) : t.cloneDeep(node);
  369. };
  370. function createSourceMapConditional(t, production, development) {
  371. return t.conditionalExpression(t.binaryExpression('===', t.memberExpression(t.memberExpression(t.identifier('process'), t.identifier('env')), t.identifier('NODE_ENV')), t.stringLiteral('production')), production, development);
  372. }
  373. var transformExpressionWithStyles = function transformExpressionWithStyles(_ref) {
  374. var babel = _ref.babel,
  375. state = _ref.state,
  376. path = _ref.path,
  377. shouldLabel = _ref.shouldLabel,
  378. _ref$sourceMap = _ref.sourceMap,
  379. sourceMap = _ref$sourceMap === void 0 ? '' : _ref$sourceMap;
  380. var t = babel.types;
  381. if (t.isTaggedTemplateExpression(path)) {
  382. var expressions = getExpressionsFromTemplateLiteral(path.node.quasi, t);
  383. if (state.emotionSourceMap && path.node.quasi.loc !== undefined) {
  384. sourceMap = getSourceMap(path.node.quasi.loc.start, state);
  385. }
  386. path.replaceWith(t.callExpression(path.node.tag, expressions));
  387. }
  388. if (t.isCallExpression(path)) {
  389. var canAppendStrings = path.node.arguments.every(function (arg) {
  390. return arg.type !== 'SpreadElement';
  391. });
  392. if (canAppendStrings && shouldLabel) {
  393. var label = getLabelFromPath(path, state, t);
  394. if (label) {
  395. appendStringToArguments(path, ";label:" + label + ";", t);
  396. }
  397. }
  398. var isPure = true;
  399. path.get('arguments').forEach(function (node) {
  400. if (!node.isPure()) {
  401. isPure = false;
  402. }
  403. if (t.isObjectExpression(node)) {
  404. node.replaceWith(simplifyObject(node.node, t));
  405. }
  406. });
  407. path.node.arguments = joinStringLiterals(path.node.arguments, t);
  408. if (canAppendStrings && state.emotionSourceMap && !sourceMap && path.node.loc !== undefined) {
  409. sourceMap = getSourceMap(path.node.loc.start, state);
  410. }
  411. if (path.node.arguments.length === 1 && t.isStringLiteral(path.node.arguments[0])) {
  412. var cssString = path.node.arguments[0].value;
  413. var res = serialize.serializeStyles([cssString]);
  414. var prodNode = t.objectExpression([t.objectProperty(t.identifier('name'), t.stringLiteral(res.name)), t.objectProperty(t.identifier('styles'), t.stringLiteral(res.styles))]);
  415. var node = prodNode;
  416. if (sourceMap) {
  417. if (!state.emotionStringifiedCssId) {
  418. var uid = state.file.scope.generateUidIdentifier('__EMOTION_STRINGIFIED_CSS_ERROR__');
  419. state.emotionStringifiedCssId = uid;
  420. var cssObjectToString = t.functionDeclaration(uid, [], t.blockStatement([t.returnStatement(t.stringLiteral(CSS_OBJECT_STRINGIFIED_ERROR))]));
  421. cssObjectToString._compact = true;
  422. state.file.path.unshiftContainer('body', [cssObjectToString]);
  423. }
  424. var devNode = t.objectExpression([t.objectProperty(t.identifier('name'), t.stringLiteral(res.name)), t.objectProperty(t.identifier('styles'), t.stringLiteral(res.styles)), t.objectProperty(t.identifier('map'), t.stringLiteral(sourceMap)), t.objectProperty(t.identifier('toString'), cloneNode(t, state.emotionStringifiedCssId))]);
  425. node = createSourceMapConditional(t, prodNode, devNode);
  426. }
  427. return {
  428. node: node,
  429. isPure: true
  430. };
  431. }
  432. if (sourceMap) {
  433. var lastIndex = path.node.arguments.length - 1;
  434. var last = path.node.arguments[lastIndex];
  435. var sourceMapConditional = createSourceMapConditional(t, t.stringLiteral(''), t.stringLiteral(sourceMap));
  436. if (t.isStringLiteral(last)) {
  437. path.node.arguments[lastIndex] = t.binaryExpression('+', last, sourceMapConditional);
  438. } else if (isTaggedTemplateExpressionTranspiledByTypeScript(path)) {
  439. var makeTemplateObjectCallPath = path.get('arguments')[0].get('right').get('right');
  440. makeTemplateObjectCallPath.get('arguments').forEach(function (argPath) {
  441. var elements = argPath.get('elements');
  442. var lastElement = elements[elements.length - 1];
  443. lastElement.replaceWith(t.binaryExpression('+', lastElement.node, cloneNode(t, sourceMapConditional)));
  444. });
  445. } else {
  446. path.node.arguments.push(sourceMapConditional);
  447. }
  448. }
  449. return {
  450. node: undefined,
  451. isPure: isPure
  452. };
  453. }
  454. return {
  455. node: undefined,
  456. isPure: false
  457. };
  458. };
  459. var getStyledOptions = function getStyledOptions(t, path, state) {
  460. var properties = [t.objectProperty(t.identifier('target'), t.stringLiteral(getTargetClassName(state)))];
  461. var label = getLabelFromPath(path, state, t);
  462. if (label) {
  463. properties.push(t.objectProperty(t.identifier('label'), t.stringLiteral(label)));
  464. }
  465. var args = path.node.arguments;
  466. var optionsArgument = args.length >= 2 ? args[1] : null;
  467. if (optionsArgument) {
  468. if (!t.isObjectExpression(optionsArgument)) {
  469. return t.callExpression(state.file.addHelper('extends'), [t.objectExpression([]), t.objectExpression(properties), optionsArgument]);
  470. }
  471. properties.unshift.apply(properties, optionsArgument.properties);
  472. }
  473. return t.objectExpression( // $FlowFixMe
  474. properties);
  475. };
  476. var createEmotionMacro = function createEmotionMacro(instancePath) {
  477. return babelPluginMacros.createMacro(function macro(_ref) {
  478. var references = _ref.references,
  479. state = _ref.state,
  480. babel = _ref.babel,
  481. isEmotionCall = _ref.isEmotionCall;
  482. if (!isEmotionCall) {
  483. state.emotionSourceMap = true;
  484. }
  485. var t = babel.types;
  486. Object.keys(references).forEach(function (referenceKey) {
  487. var isPure = true;
  488. var runtimeNode = helperModuleImports.addNamed(state.file.path, referenceKey, instancePath);
  489. switch (referenceKey) {
  490. case 'injectGlobal':
  491. {
  492. isPure = false;
  493. }
  494. // eslint-disable-next-line no-fallthrough
  495. case 'css':
  496. case 'keyframes':
  497. {
  498. references[referenceKey].reverse().forEach(function (reference) {
  499. var path = reference.parentPath;
  500. reference.replaceWith(t.cloneDeep(runtimeNode));
  501. if (isPure) {
  502. path.addComment('leading', '#__PURE__');
  503. }
  504. var _transformExpressionW = transformExpressionWithStyles({
  505. babel: babel,
  506. state: state,
  507. path: path,
  508. shouldLabel: true
  509. }),
  510. node = _transformExpressionW.node;
  511. if (node) {
  512. path.node.arguments[0] = node;
  513. }
  514. });
  515. break;
  516. }
  517. default:
  518. {
  519. references[referenceKey].reverse().forEach(function (reference) {
  520. reference.replaceWith(t.cloneDeep(runtimeNode));
  521. });
  522. }
  523. }
  524. });
  525. });
  526. };
  527. var createStyledMacro = function createStyledMacro(_ref) {
  528. var importPath = _ref.importPath,
  529. _ref$originalImportPa = _ref.originalImportPath,
  530. originalImportPath = _ref$originalImportPa === void 0 ? importPath : _ref$originalImportPa,
  531. isWeb = _ref.isWeb;
  532. return babelPluginMacros.createMacro(function (_ref2) {
  533. var references = _ref2.references,
  534. state = _ref2.state,
  535. babel = _ref2.babel,
  536. isEmotionCall = _ref2.isEmotionCall;
  537. if (!isEmotionCall) {
  538. state.emotionSourceMap = true;
  539. }
  540. var t = babel.types;
  541. if (references["default"] && references["default"].length) {
  542. var _styledIdentifier;
  543. var getStyledIdentifier = function getStyledIdentifier() {
  544. if (_styledIdentifier === undefined) {
  545. _styledIdentifier = helperModuleImports.addDefault(state.file.path, importPath, {
  546. nameHint: 'styled'
  547. });
  548. }
  549. return t.cloneDeep(_styledIdentifier);
  550. };
  551. var originalImportPathStyledIdentifier;
  552. var getOriginalImportPathStyledIdentifier = function getOriginalImportPathStyledIdentifier() {
  553. if (originalImportPathStyledIdentifier === undefined) {
  554. originalImportPathStyledIdentifier = helperModuleImports.addDefault(state.file.path, originalImportPath, {
  555. nameHint: 'styled'
  556. });
  557. }
  558. return t.cloneDeep(originalImportPathStyledIdentifier);
  559. };
  560. if (importPath === originalImportPath) {
  561. getOriginalImportPathStyledIdentifier = getStyledIdentifier;
  562. }
  563. references["default"].forEach(function (reference) {
  564. var isCall = false;
  565. if (t.isMemberExpression(reference.parent) && reference.parent.computed === false) {
  566. isCall = true;
  567. if ( // checks if the first character is lowercase
  568. // becasue we don't want to transform the member expression if
  569. // it's in primitives/native
  570. reference.parent.property.name.charCodeAt(0) > 96) {
  571. reference.parentPath.replaceWith(t.callExpression(getStyledIdentifier(), [t.stringLiteral(reference.parent.property.name)]));
  572. } else {
  573. reference.replaceWith(getStyledIdentifier());
  574. }
  575. } else if (reference.parentPath && reference.parentPath.parentPath && t.isCallExpression(reference.parentPath) && reference.parent.callee === reference.node) {
  576. isCall = true;
  577. reference.replaceWith(getStyledIdentifier());
  578. } else {
  579. reference.replaceWith(getOriginalImportPathStyledIdentifier());
  580. }
  581. if (reference.parentPath && reference.parentPath.parentPath) {
  582. var styledCallPath = reference.parentPath.parentPath;
  583. var _transformExpressionW = transformExpressionWithStyles({
  584. path: styledCallPath,
  585. state: state,
  586. babel: babel,
  587. shouldLabel: false
  588. }),
  589. node = _transformExpressionW.node;
  590. if (node && isWeb) {
  591. // we know the argument length will be 1 since that's the only time we will have a node since it will be static
  592. styledCallPath.node.arguments[0] = node;
  593. }
  594. }
  595. if (isCall) {
  596. reference.addComment('leading', '#__PURE__');
  597. if (isWeb) {
  598. reference.parentPath.node.arguments[1] = getStyledOptions(t, reference.parentPath, state);
  599. }
  600. }
  601. });
  602. }
  603. Object.keys(references).filter(function (x) {
  604. return x !== 'default';
  605. }).forEach(function (referenceKey) {
  606. var runtimeNode = helperModuleImports.addNamed(state.file.path, referenceKey, importPath);
  607. references[referenceKey].reverse().forEach(function (reference) {
  608. reference.replaceWith(t.cloneDeep(runtimeNode));
  609. });
  610. });
  611. });
  612. };
  613. var transformCssCallExpression = function transformCssCallExpression(_ref) {
  614. var babel = _ref.babel,
  615. state = _ref.state,
  616. path = _ref.path,
  617. sourceMap = _ref.sourceMap;
  618. var _transformExpressionW = transformExpressionWithStyles({
  619. babel: babel,
  620. state: state,
  621. path: path,
  622. shouldLabel: true,
  623. sourceMap: sourceMap
  624. }),
  625. node = _transformExpressionW.node,
  626. isPure = _transformExpressionW.isPure;
  627. if (node) {
  628. path.replaceWith(node);
  629. if (isPure) {
  630. path.hoist();
  631. }
  632. } else {
  633. path.addComment('leading', '#__PURE__');
  634. }
  635. };
  636. var cssMacro = babelPluginMacros.createMacro(function (_ref2) {
  637. var references = _ref2.references,
  638. state = _ref2.state,
  639. babel = _ref2.babel,
  640. isEmotionCall = _ref2.isEmotionCall;
  641. if (!isEmotionCall) {
  642. state.emotionSourceMap = true;
  643. }
  644. var t = babel.types;
  645. if (references["default"] && references["default"].length) {
  646. references["default"].reverse().forEach(function (reference) {
  647. if (!state.cssIdentifier) {
  648. state.cssIdentifier = helperModuleImports.addDefault(reference, '@emotion/css', {
  649. nameHint: 'css'
  650. });
  651. }
  652. reference.replaceWith(t.cloneDeep(state.cssIdentifier));
  653. transformCssCallExpression({
  654. babel: babel,
  655. state: state,
  656. path: reference.parentPath
  657. });
  658. });
  659. }
  660. Object.keys(references).filter(function (x) {
  661. return x !== 'default';
  662. }).forEach(function (referenceKey) {
  663. var runtimeNode = helperModuleImports.addNamed(state.file.path, referenceKey, '@emotion/css', {
  664. nameHint: referenceKey
  665. });
  666. references[referenceKey].reverse().forEach(function (reference) {
  667. reference.replaceWith(t.cloneDeep(runtimeNode));
  668. });
  669. });
  670. });
  671. var webStyledMacro = createStyledMacro({
  672. importPath: '@emotion/styled-base',
  673. originalImportPath: '@emotion/styled',
  674. isWeb: true
  675. });
  676. var nativeStyledMacro = createStyledMacro({
  677. importPath: '@emotion/native',
  678. originalImportPath: '@emotion/native',
  679. isWeb: false
  680. });
  681. var primitivesStyledMacro = createStyledMacro({
  682. importPath: '@emotion/primitives',
  683. originalImportPath: '@emotion/primitives',
  684. isWeb: false
  685. });
  686. var macros = {
  687. createEmotionMacro: createEmotionMacro,
  688. css: cssMacro,
  689. createStyledMacro: createStyledMacro
  690. };
  691. var emotionCoreMacroThatsNotARealMacro = function emotionCoreMacroThatsNotARealMacro(_ref) {
  692. var references = _ref.references,
  693. state = _ref.state,
  694. babel = _ref.babel;
  695. Object.keys(references).forEach(function (refKey) {
  696. if (refKey === 'css') {
  697. references[refKey].forEach(function (path) {
  698. transformCssCallExpression({
  699. babel: babel,
  700. state: state,
  701. path: path.parentPath
  702. });
  703. });
  704. }
  705. });
  706. };
  707. emotionCoreMacroThatsNotARealMacro.keepImport = true;
  708. function getAbsolutePath(instancePath, rootPath) {
  709. if (instancePath.charAt(0) === '.') {
  710. var absoluteInstancePath = nodePath.resolve(rootPath, instancePath);
  711. return absoluteInstancePath;
  712. }
  713. return false;
  714. }
  715. function getInstancePathToCompare(instancePath, rootPath) {
  716. var absolutePath = getAbsolutePath(instancePath, rootPath);
  717. if (absolutePath === false) {
  718. return instancePath;
  719. }
  720. return absolutePath;
  721. }
  722. function index (babel) {
  723. var t = babel.types;
  724. return {
  725. name: 'emotion',
  726. inherits: require('babel-plugin-syntax-jsx'),
  727. visitor: {
  728. ImportDeclaration: function ImportDeclaration(path, state) {
  729. var hasFilepath = path.hub.file.opts.filename && path.hub.file.opts.filename !== 'unknown';
  730. var dirname = hasFilepath ? nodePath.dirname(path.hub.file.opts.filename) : '';
  731. if (!state.pluginMacros[path.node.source.value] && state.emotionInstancePaths.indexOf(getInstancePathToCompare(path.node.source.value, dirname)) !== -1) {
  732. state.pluginMacros[path.node.source.value] = createEmotionMacro(path.node.source.value);
  733. }
  734. var pluginMacros = state.pluginMacros; // most of this is from https://github.com/kentcdodds/babel-plugin-macros/blob/master/src/index.js
  735. if (pluginMacros[path.node.source.value] === undefined) {
  736. return;
  737. }
  738. if (t.isImportNamespaceSpecifier(path.node.specifiers[0])) {
  739. return;
  740. }
  741. var imports = path.node.specifiers.map(function (s) {
  742. return {
  743. localName: s.local.name,
  744. importedName: s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name
  745. };
  746. });
  747. var shouldExit = false;
  748. var hasReferences = false;
  749. var referencePathsByImportName = imports.reduce(function (byName, _ref2) {
  750. var importedName = _ref2.importedName,
  751. localName = _ref2.localName;
  752. var binding = path.scope.getBinding(localName);
  753. if (!binding) {
  754. shouldExit = true;
  755. return byName;
  756. }
  757. byName[importedName] = binding.referencePaths;
  758. hasReferences = hasReferences || Boolean(byName[importedName].length);
  759. return byName;
  760. }, {});
  761. if (!hasReferences || shouldExit) {
  762. return;
  763. }
  764. /**
  765. * Other plugins that run before babel-plugin-macros might use path.replace, where a path is
  766. * put into its own replacement. Apparently babel does not update the scope after such
  767. * an operation. As a remedy, the whole scope is traversed again with an empty "Identifier"
  768. * visitor - this makes the problem go away.
  769. *
  770. * See: https://github.com/kentcdodds/import-all.macro/issues/7
  771. */
  772. state.file.scope.path.traverse({
  773. Identifier: function Identifier() {}
  774. });
  775. pluginMacros[path.node.source.value]({
  776. references: referencePathsByImportName,
  777. state: state,
  778. babel: babel,
  779. isBabelMacrosCall: true,
  780. isEmotionCall: true
  781. });
  782. if (!pluginMacros[path.node.source.value].keepImport) {
  783. path.remove();
  784. }
  785. },
  786. Program: function Program(path, state) {
  787. state.emotionInstancePaths = (state.opts.instances || []).map(function (instancePath) {
  788. return getInstancePathToCompare(instancePath, process.cwd());
  789. });
  790. state.pluginMacros = {
  791. '@emotion/css': cssMacro,
  792. '@emotion/styled': webStyledMacro,
  793. '@emotion/core': emotionCoreMacroThatsNotARealMacro,
  794. '@emotion/primitives': primitivesStyledMacro,
  795. '@emotion/native': nativeStyledMacro,
  796. emotion: createEmotionMacro('emotion')
  797. };
  798. if (state.opts.cssPropOptimization === undefined) {
  799. for (var _iterator = path.node.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  800. var _ref3;
  801. if (_isArray) {
  802. if (_i >= _iterator.length) break;
  803. _ref3 = _iterator[_i++];
  804. } else {
  805. _i = _iterator.next();
  806. if (_i.done) break;
  807. _ref3 = _i.value;
  808. }
  809. var node = _ref3;
  810. if (t.isImportDeclaration(node) && node.source.value === '@emotion/core' && node.specifiers.some(function (x) {
  811. return t.isImportSpecifier(x) && x.imported.name === 'jsx';
  812. })) {
  813. state.transformCssProp = true;
  814. break;
  815. }
  816. }
  817. } else {
  818. state.transformCssProp = state.opts.cssPropOptimization;
  819. }
  820. if (state.opts.sourceMap === false) {
  821. state.emotionSourceMap = false;
  822. } else {
  823. state.emotionSourceMap = true;
  824. }
  825. },
  826. JSXAttribute: function JSXAttribute(path, state) {
  827. if (path.node.name.name !== 'css' || !state.transformCssProp) {
  828. return;
  829. }
  830. if (t.isJSXExpressionContainer(path.node.value) && (t.isObjectExpression(path.node.value.expression) || t.isArrayExpression(path.node.value.expression))) {
  831. var expressionPath = path.get('value.expression');
  832. var sourceMap = state.emotionSourceMap && path.node.loc !== undefined ? getSourceMap(path.node.loc.start, state) : '';
  833. expressionPath.replaceWith(t.callExpression( // the name of this identifier doesn't really matter at all
  834. // it'll never appear in generated code
  835. t.identifier('___shouldNeverAppearCSS'), [path.node.value.expression]));
  836. transformCssCallExpression({
  837. babel: babel,
  838. state: state,
  839. path: expressionPath,
  840. sourceMap: sourceMap
  841. });
  842. if (t.isCallExpression(expressionPath)) {
  843. if (!state.cssIdentifier) {
  844. state.cssIdentifier = helperModuleImports.addDefault(path, '@emotion/css', {
  845. nameHint: 'css'
  846. });
  847. }
  848. expressionPath.get('callee').replaceWith(t.cloneDeep(state.cssIdentifier));
  849. }
  850. }
  851. },
  852. CallExpression: {
  853. exit: function exit(path, state) {
  854. try {
  855. if (path.node.callee && path.node.callee.property && path.node.callee.property.name === 'withComponent') {
  856. switch (path.node.arguments.length) {
  857. case 1:
  858. case 2:
  859. {
  860. path.node.arguments[1] = getStyledOptions(t, path, state);
  861. }
  862. }
  863. }
  864. } catch (e) {
  865. throw path.buildCodeFrameError(e);
  866. }
  867. }
  868. }
  869. }
  870. };
  871. }
  872. exports.default = index;
  873. exports.macros = macros;