This commit is contained in:
root
2025-11-25 09:56:15 +03:00
commit 68c8f0e80d
23717 changed files with 3200521 additions and 0 deletions

21
mc_test/node_modules/@emotion/babel-plugin/LICENSE generated vendored Executable file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Emotion team and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

346
mc_test/node_modules/@emotion/babel-plugin/README.md generated vendored Executable file
View File

@ -0,0 +1,346 @@
# @emotion/babel-plugin
> Babel plugin for the minification and optimization of emotion styles.
`@emotion/babel-plugin` is highly recommended, but not required in version 8 and
above of Emotion.
## Features
<table>
<thead>
<tr>
<th>Feature/Syntax</th>
<th>Native</th>
<th>Babel Plugin Required</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>css``</code></td>
<td align="center">✅</td>
<td align="center"></td>
<td></td>
</tr>
<tr>
<td><code>css(...)</code></td>
<td align="center">✅</td>
<td align="center"></td>
<td>Generally used for object styles.</td>
</tr>
<tr>
<td>components as selectors</td>
<td align="center"></td>
<td align="center">✅</td>
<td>Allows an emotion component to be <a href="https://emotion.sh/docs/styled#targeting-another-emotion-component">used as a CSS selector</a>.</td>
</tr>
<tr>
<td>Minification</td>
<td align="center"></td>
<td align="center">✅</td>
<td>Any leading/trailing space between properties in your <code>css</code> and <code>styled</code> blocks is removed. This can reduce the size of your final bundle.</td>
</tr>
<tr>
<td>Dead Code Elimination</td>
<td align="center"></td>
<td align="center">✅</td>
<td>Uglifyjs will use the injected <code>/*#__PURE__*/</code> flag comments to mark your <code>css</code> and <code>styled</code> blocks as candidates for dead code elimination.</td>
</tr>
<tr>
<td>Source Maps</td>
<td align="center"></td>
<td align="center">✅</td>
<td>When enabled, navigate directly to the style declaration in your javascript file.</td>
</tr>
<tr>
<td>Contextual Class Names</td>
<td align="center"></td>
<td align="center">✅</td>
<td>Generated class names include the name of the variable or component they were defined in.</td>
</tr>
</tbody>
</table>
## Example
**In**
```javascript
const myStyles = css`
font-size: 20px;
@media (min-width: 420px) {
color: blue;
${css`
width: 96px;
height: 96px;
`};
line-height: 26px;
}
background: green;
${{ backgroundColor: 'hotpink' }};
`
```
**Out**
```javascript
const myStyles = /* #__PURE__ */ css(
'font-size:20px;@media(min-width:420px){color:blue;',
/* #__PURE__ */ css('width:96px;height:96px;'),
';line-height:26px;}background:green;',
{ backgroundColor: 'hotpink' },
';'
)
```
## Installation
```bash
yarn add --dev @emotion/babel-plugin
```
or if you prefer npm
```bash
npm install --save-dev @emotion/babel-plugin
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
Without options:
```json
{
"plugins": ["@emotion"]
}
```
With options:
_Defaults Shown_
```js
{
"plugins": [
[
"@emotion",
{
// sourceMap is on by default but source maps are dead code eliminated in production
"sourceMap": true,
"autoLabel": "dev-only",
"labelFormat": "[local]",
"cssPropOptimization": true
}
]
]
}
```
Recommended Setup
**.babelrc**
```json
{
"plugins": ["@emotion"]
}
```
### Via CLI
```bash
babel --plugins @emotion/babel-plugin script.js
```
### Via Node API
```javascript
require('@babel/core').transform('code', {
plugins: ['@emotion/babel-plugin']
})
```
## Options
### `sourceMap`
`boolean`, defaults to `true`.
This option enables the following:
- Injected source maps for use in browser dev tools
[**Documentation**](https://emotion.sh/docs/source-maps)
> Note:
>
> Source maps are on by default in @emotion/babel-plugin but they will be removed in production builds
### `autoLabel`
`'dev-only' | 'always' | 'never'`, defaults to `dev-only`.
This option enables the following:
- Automatically adds the `label` property to styles so that class names
generated by `css` or `styled` include the name of the variable the result is
assigned to.
- Please note that non word characters in the variable will be removed
(Eg. `iconStyles$1` will become `iconStyles1`) because `$` is not valid
[CSS ClassName Selector](https://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors#449000)
Each possible value for this option produces different output code:
- with `dev-only` we optimize the production code, so there are no labels added there, but at the same time we keep labels for development environments,
- with `always` we always add labels when possible,
- with `never` we disable this entirely and no labels are added.
#### css
**In**
```javascript
const brownStyles = css({ color: 'brown' })
```
**Out**
```javascript
const brownStyles = /*#__PURE__*/ css({ color: 'brown' }, 'label:brownStyles;')
```
`brownStyles`'s value would be `css-1q8eu9e-brownStyles`
### `labelFormat`
`string`, defaults to `"[local]"`.
This option only works when `autoLabel` is set to `'dev-only'` or `'always'`. It allows you to
define the format of the resulting `label`. The format is defined via string where
variable parts are enclosed in square brackets `[]`.
For example `labelFormat: "my-classname--[local]"`, where `[local]` will be replaced
with the name of the variable the result is assigned to.
Allowed values:
- `[local]` - the name of the variable the result of the `css` or `styled` expression is assigned to.
- `[filename]` - name of the file (without extension) where `css` or `styled` expression is located.
- `[dirname]` - name of the directory containing the file where `css` or `styled` expression is located.
This format only affects the label property of the expression, meaning that the `css` prefix and hash will
be prepended automatically.
#### css
**In**
```javascript
// BrownView.js
// autoLabel: 'dev-only'
// labelFormat: '[filename]--[local]'
const brownStyles = css({ color: 'brown' })
```
**Out**
```javascript
const brownStyles = /*#__PURE__*/ css(
{ color: 'brown' },
'label:BrownView--brownStyles;'
)
```
`BrownView--brownStyles`'s value would be `css-hash-BrownView--brownStyles`
#### styled
**In**
```javascript
const H1 = styled.h1({
borderRadius: '50%',
transition: 'transform 400ms ease-in-out',
boxSizing: 'border-box',
display: 'flex',
':hover': {
transform: 'scale(1.2)'
}
})
```
**Out**
```javascript
const H1 = /*#__PURE__*/ styled('h1', {
label: 'H1'
})({
borderRadius: '50%',
transition: 'transform 400ms ease-in-out',
boxSizing: 'border-box',
display: 'flex',
':hover': {
transform: 'scale(1.2)'
}
})
```
`H1`'s class name attribute would be `css-hash-H1`
### `cssPropOptimization`
`boolean`, defaults to `true`.
This option assumes that you are using something to make `@emotion/react`'s `jsx` function work for all jsx. If you are not doing so and you do not want such optimizations to occur, disable this option.
### `importMap`
This option allows you to tell @emotion/babel-plugin what imports it should look at to determine what it should transform so if you re-export Emotion's exports, you can still use the Babel transforms
An example file:
```js
import { anotherExport } from 'my-package'
import { someExport, thisIsTheJsxExport } from 'some-package'
```
An example config:
```json
{
"my-package": {
"anotherExport": {
"canonicalImport": ["@emotion/styled", "default"],
"styledBaseImport": ["my-package/base", "anotherExport"]
}
},
"some-package": {
"someExport": {
"canonicalImport": ["@emotion/react", "css"]
},
"thisIsTheJsxExport": {
"canonicalImport": ["@emotion/react", "jsx"]
}
}
}
```
## Babel Macros
Instead of using `@emotion/babel-plugin`, you can use emotion with [`babel-plugin-macros`](https://github.com/kentcdodds/babel-plugin-macros). Add `babel-plugin-macros` to your babel config (which is included in Create React App 2.0) and use the imports/packages shown below.
```jsx
import {
css,
keyframes,
injectGlobal,
flush,
hydrate
} from '@emotion/css/macro'
import { jsx, css, Global, keyframes } from '@emotion/react/macro'
import styled from '@emotion/styled/macro'
```

View File

@ -0,0 +1 @@
exports._default = require("./emotion-babel-plugin.cjs.js").default;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,4 @@
export {
macros
} from "./emotion-babel-plugin.cjs.js";
export { _default as default } from "./emotion-babel-plugin.cjs.default.js";

File diff suppressed because it is too large Load Diff

55
mc_test/node_modules/@emotion/babel-plugin/package.json generated vendored Executable file
View File

@ -0,0 +1,55 @@
{
"name": "@emotion/babel-plugin",
"version": "11.13.5",
"description": "A recommended babel preprocessing plugin for emotion, The Next Generation of CSS-in-JS.",
"main": "dist/emotion-babel-plugin.cjs.js",
"module": "dist/emotion-babel-plugin.esm.js",
"exports": {
".": {
"types": {
"import": "./dist/emotion-babel-plugin.cjs.mjs",
"default": "./dist/emotion-babel-plugin.cjs.js"
},
"module": "./dist/emotion-babel-plugin.esm.js",
"import": "./dist/emotion-babel-plugin.cjs.mjs",
"default": "./dist/emotion-babel-plugin.cjs.js"
},
"./package.json": "./package.json"
},
"files": [
"src",
"lib",
"dist"
],
"dependencies": {
"@babel/helper-module-imports": "^7.16.7",
"@babel/runtime": "^7.18.3",
"@emotion/hash": "^0.9.2",
"@emotion/memoize": "^0.9.0",
"@emotion/serialize": "^1.3.3",
"babel-plugin-macros": "^3.1.0",
"convert-source-map": "^1.5.0",
"escape-string-regexp": "^4.0.0",
"find-root": "^1.1.0",
"source-map": "^0.5.7",
"stylis": "4.2.0"
},
"devDependencies": {
"@babel/core": "^7.18.5",
"babel-check-duplicated-nodes": "^1.0.0"
},
"author": "Kye Hohenberger",
"homepage": "https://emotion.sh",
"license": "MIT",
"repository": "https://github.com/emotion-js/emotion/tree/main/packages/babel-plugin",
"keywords": [
"styles",
"emotion",
"react",
"css",
"css-in-js"
],
"bugs": {
"url": "https://github.com/emotion-js/emotion/issues"
}
}

182
mc_test/node_modules/@emotion/babel-plugin/src/core-macro.js generated vendored Executable file
View File

@ -0,0 +1,182 @@
import {
transformExpressionWithStyles,
createTransformerMacro,
getSourceMap,
addImport
} from './utils'
export const transformCssCallExpression = (
{ state, babel, path, sourceMap, annotateAsPure = true } /*: {
state: *,
babel: *,
path: *,
sourceMap?: string,
annotateAsPure?: boolean
} */
) => {
let node = transformExpressionWithStyles({
babel,
state,
path,
shouldLabel: true,
sourceMap
})
if (node) {
path.replaceWith(node)
path.hoist()
} else if (annotateAsPure && path.isCallExpression()) {
path.addComment('leading', '#__PURE__')
}
}
export const transformCsslessArrayExpression = (
{ state, babel, path } /*: {
babel: *,
state: *,
path: *
} */
) => {
let t = babel.types
let expressionPath = path.get('value.expression')
let sourceMap =
state.emotionSourceMap && path.node.loc !== undefined
? getSourceMap(path.node.loc.start, state)
: ''
expressionPath.replaceWith(
t.callExpression(
// the name of this identifier doesn't really matter at all
// it'll never appear in generated code
t.identifier('___shouldNeverAppearCSS'),
path.node.value.expression.elements
)
)
transformCssCallExpression({
babel,
state,
path: expressionPath,
sourceMap,
annotateAsPure: false
})
if (t.isCallExpression(expressionPath)) {
expressionPath.replaceWith(t.arrayExpression(expressionPath.node.arguments))
}
}
export const transformCsslessObjectExpression = (
{ state, babel, path, cssImport } /*: {
babel: *,
state: *,
path: *,
cssImport: { importSource: string, cssExport: string }
} */
) => {
let t = babel.types
let expressionPath = path.get('value.expression')
let sourceMap =
state.emotionSourceMap && path.node.loc !== undefined
? getSourceMap(path.node.loc.start, state)
: ''
expressionPath.replaceWith(
t.callExpression(
// the name of this identifier doesn't really matter at all
// it'll never appear in generated code
t.identifier('___shouldNeverAppearCSS'),
[path.node.value.expression]
)
)
transformCssCallExpression({
babel,
state,
path: expressionPath,
sourceMap
})
if (t.isCallExpression(expressionPath)) {
expressionPath
.get('callee')
.replaceWith(
addImport(state, cssImport.importSource, cssImport.cssExport, 'css')
)
}
}
let cssTransformer = (
{ state, babel, reference } /*: {
state: any,
babel: any,
reference: any
} */
) => {
transformCssCallExpression({ babel, state, path: reference.parentPath })
}
let globalTransformer = (
{ state, babel, reference, importSource, options } /*: {
state: any,
babel: any,
reference: any,
importSource: string,
options: { cssExport?: string }
} */
) => {
const t = babel.types
if (
!t.isJSXIdentifier(reference.node) ||
!t.isJSXOpeningElement(reference.parentPath.node)
) {
return
}
const stylesPropPath = reference.parentPath
.get('attributes')
.find(p => t.isJSXAttribute(p.node) && p.node.name.name === 'styles')
if (!stylesPropPath) {
return
}
if (t.isJSXExpressionContainer(stylesPropPath.node.value)) {
if (t.isArrayExpression(stylesPropPath.node.value.expression)) {
transformCsslessArrayExpression({
state,
babel,
path: stylesPropPath
})
} else if (t.isObjectExpression(stylesPropPath.node.value.expression)) {
transformCsslessObjectExpression({
state,
babel,
path: stylesPropPath,
cssImport:
options.cssExport !== undefined
? {
importSource,
cssExport: options.cssExport
}
: {
importSource: '@emotion/react',
cssExport: 'css'
}
})
}
}
}
export const transformers = {
// this is an empty function because this transformer is never called
// we don't run any transforms on `jsx` directly
// instead we use it as a hint to enable css prop optimization
jsx: () => {},
css: cssTransformer,
Global: globalTransformer
}
export default createTransformerMacro(transformers, {
importSource: '@emotion/react'
})

View File

@ -0,0 +1,64 @@
import { transformExpressionWithStyles, createTransformerMacro } from './utils'
const isAlreadyTranspiled = path => {
if (!path.isCallExpression()) {
return false
}
const firstArgPath = path.get('arguments.0')
if (!firstArgPath) {
return false
}
if (!firstArgPath.isConditionalExpression()) {
return false
}
const alternatePath = firstArgPath.get('alternate')
if (!alternatePath.isObjectExpression()) {
return false
}
const properties = new Set(
alternatePath.get('properties').map(p => p.node.key.name)
)
return ['name', 'styles'].every(p => properties.has(p))
}
let createEmotionTransformer =
(isPure /*: boolean */) =>
(
{ state, babel, importSource, reference, importSpecifierName } /*: Object */
) => {
const path = reference.parentPath
if (isAlreadyTranspiled(path)) {
return
}
if (isPure) {
path.addComment('leading', '#__PURE__')
}
let node = transformExpressionWithStyles({
babel,
state,
path,
shouldLabel: true
})
if (node) {
path.node.arguments[0] = node
}
}
export let transformers = {
css: createEmotionTransformer(true),
injectGlobal: createEmotionTransformer(false),
keyframes: createEmotionTransformer(true)
}
export let createEmotionMacro = (importSource /*: string */) =>
createTransformerMacro(transformers, { importSource })

314
mc_test/node_modules/@emotion/babel-plugin/src/index.js generated vendored Executable file
View File

@ -0,0 +1,314 @@
import {
createEmotionMacro,
transformers as vanillaTransformers
} from './emotion-macro'
import { createStyledMacro, styledTransformer } from './styled-macro'
import coreMacro, {
transformers as coreTransformers,
transformCsslessArrayExpression,
transformCsslessObjectExpression
} from './core-macro'
import { getStyledOptions, createTransformerMacro } from './utils'
const getCssExport = (reexported, importSource, mapping) => {
const cssExport = Object.keys(mapping).find(localExportName => {
const [packageName, exportName] = mapping[localExportName].canonicalImport
return packageName === '@emotion/react' && exportName === 'css'
})
if (!cssExport) {
throw new Error(
`You have specified that '${importSource}' re-exports '${reexported}' from '@emotion/react' but it doesn't also re-export 'css' from '@emotion/react', 'css' is necessary for certain optimisations, please re-export it from '${importSource}'`
)
}
return cssExport
}
let webStyledMacro = createStyledMacro({
importSource: '@emotion/styled/base',
originalImportSource: '@emotion/styled',
isWeb: true
})
let nativeStyledMacro = createStyledMacro({
importSource: '@emotion/native',
originalImportSource: '@emotion/native',
isWeb: false
})
let primitivesStyledMacro = createStyledMacro({
importSource: '@emotion/primitives',
originalImportSource: '@emotion/primitives',
isWeb: false
})
let vanillaEmotionMacro = createEmotionMacro('@emotion/css')
let transformersSource = {
'@emotion/css': vanillaTransformers,
'@emotion/react': coreTransformers,
'@emotion/styled': {
default: [
styledTransformer,
{ styledBaseImport: ['@emotion/styled/base', 'default'], isWeb: true }
]
},
'@emotion/primitives': {
default: [styledTransformer, { isWeb: false }]
},
'@emotion/native': {
default: [styledTransformer, { isWeb: false }]
}
}
export const macros = {
core: coreMacro,
nativeStyled: nativeStyledMacro,
primitivesStyled: primitivesStyledMacro,
webStyled: webStyledMacro,
vanillaEmotion: vanillaEmotionMacro
}
/*
export type BabelPath = any
export type EmotionBabelPluginPass = any
*/
const AUTO_LABEL_VALUES = ['dev-only', 'never', 'always']
export default function (babel, options) {
if (
options.autoLabel !== undefined &&
!AUTO_LABEL_VALUES.includes(options.autoLabel)
) {
throw new Error(
`The 'autoLabel' option must be undefined, or one of the following: ${AUTO_LABEL_VALUES.map(
s => `"${s}"`
).join(', ')}`
)
}
let t = babel.types
return {
name: '@emotion',
// https://github.com/babel/babel/blob/0c97749e0fe8ad845b902e0b23a24b308b0bf05d/packages/babel-plugin-syntax-jsx/src/index.ts#L9-L18
manipulateOptions(opts, parserOpts) {
const { plugins } = parserOpts
if (
plugins.some(p => {
const plugin = Array.isArray(p) ? p[0] : p
return plugin === 'typescript' || plugin === 'jsx'
})
) {
return
}
plugins.push('jsx')
},
visitor: {
ImportDeclaration(path, state) {
const macro = state.pluginMacros[path.node.source.value]
// most of this is from https://github.com/kentcdodds/babel-plugin-macros/blob/main/src/index.js
if (macro === undefined) {
return
}
if (t.isImportNamespaceSpecifier(path.node.specifiers[0])) {
return
}
const imports = path.node.specifiers.map(s => ({
localName: s.local.name,
importedName:
s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name
}))
let shouldExit = false
let hasReferences = false
const referencePathsByImportName = imports.reduce(
(byName, { importedName, localName }) => {
let binding = path.scope.getBinding(localName)
if (!binding) {
shouldExit = true
return byName
}
byName[importedName] = binding.referencePaths
hasReferences =
hasReferences || Boolean(byName[importedName].length)
return byName
},
{}
)
if (!hasReferences || shouldExit) {
return
}
/**
* Other plugins that run before babel-plugin-macros might use path.replace, where a path is
* put into its own replacement. Apparently babel does not update the scope after such
* an operation. As a remedy, the whole scope is traversed again with an empty "Identifier"
* visitor - this makes the problem go away.
*
* See: https://github.com/kentcdodds/import-all.macro/issues/7
*/
state.file.scope.path.traverse({
Identifier() {}
})
macro({
path,
references: referencePathsByImportName,
state,
babel,
isEmotionCall: true,
isBabelMacrosCall: true
})
},
Program(path, state) {
let macros = {}
let jsxReactImports /*: Array<{
importSource: string,
export: string,
cssExport: string
}> */ = [
{ importSource: '@emotion/react', export: 'jsx', cssExport: 'css' }
]
state.jsxReactImport = jsxReactImports[0]
Object.keys(state.opts.importMap || {}).forEach(importSource => {
let value = state.opts.importMap[importSource]
let transformers = {}
Object.keys(value).forEach(localExportName => {
let { canonicalImport, ...options } = value[localExportName]
let [packageName, exportName] = canonicalImport
if (packageName === '@emotion/react' && exportName === 'jsx') {
jsxReactImports.push({
importSource,
export: localExportName,
cssExport: getCssExport('jsx', importSource, value)
})
return
}
let packageTransformers = transformersSource[packageName]
if (packageTransformers === undefined) {
throw new Error(
`There is no transformer for the export '${exportName}' in '${packageName}'`
)
}
let extraOptions
if (packageName === '@emotion/react' && exportName === 'Global') {
// this option is not supposed to be set in importMap
extraOptions = {
cssExport: getCssExport('Global', importSource, value)
}
} else if (
packageName === '@emotion/styled' &&
exportName === 'default'
) {
// this is supposed to override defaultOptions value
// and let correct value to be set if coming in options
extraOptions = {
styledBaseImport: undefined
}
}
let [exportTransformer, defaultOptions] = Array.isArray(
packageTransformers[exportName]
)
? packageTransformers[exportName]
: [packageTransformers[exportName]]
transformers[localExportName] = [
exportTransformer,
{
...defaultOptions,
...extraOptions,
...options
}
]
})
macros[importSource] = createTransformerMacro(transformers, {
importSource
})
})
state.pluginMacros = {
'@emotion/styled': webStyledMacro,
'@emotion/react': coreMacro,
'@emotion/primitives': primitivesStyledMacro,
'@emotion/native': nativeStyledMacro,
'@emotion/css': vanillaEmotionMacro,
...macros
}
for (const node of path.node.body) {
if (t.isImportDeclaration(node)) {
let jsxReactImport = jsxReactImports.find(
thing =>
node.source.value === thing.importSource &&
node.specifiers.some(
x =>
t.isImportSpecifier(x) && x.imported.name === thing.export
)
)
if (jsxReactImport) {
state.jsxReactImport = jsxReactImport
break
}
}
}
if (state.opts.cssPropOptimization === false) {
state.transformCssProp = false
} else {
state.transformCssProp = true
}
if (state.opts.sourceMap === false) {
state.emotionSourceMap = false
} else {
state.emotionSourceMap = true
}
},
JSXAttribute(path, state) {
if (path.node.name.name !== 'css' || !state.transformCssProp) {
return
}
if (t.isJSXExpressionContainer(path.node.value)) {
if (t.isArrayExpression(path.node.value.expression)) {
transformCsslessArrayExpression({
state,
babel,
path
})
} else if (t.isObjectExpression(path.node.value.expression)) {
transformCsslessObjectExpression({
state,
babel,
path,
cssImport: state.jsxReactImport
})
}
}
},
CallExpression: {
exit(path /*: BabelPath */, state /*: EmotionBabelPluginPass */) {
try {
if (
path.node.callee &&
path.node.callee.property &&
path.node.callee.property.name === 'withComponent'
) {
switch (path.node.arguments.length) {
case 1:
case 2: {
path.node.arguments[1] = getStyledOptions(t, path, state)
}
}
}
} catch (e) {
throw path.buildCodeFrameError(e)
}
}
}
}
}
}

View File

@ -0,0 +1,144 @@
import {
transformExpressionWithStyles,
getStyledOptions,
addImport,
createTransformerMacro
} from './utils'
const getReferencedSpecifier = (path, specifierName) => {
const specifiers = path.get('specifiers')
return specifierName === 'default'
? specifiers.find(p => p.isImportDefaultSpecifier())
: specifiers.find(p => p.node.local.name === specifierName)
}
export let styledTransformer = (
{
state,
babel,
path,
importSource,
reference,
importSpecifierName,
options: { styledBaseImport, isWeb }
} /*: {
state: Object,
babel: Object,
path: any,
importSource: string,
importSpecifierName: string,
reference: Object,
options: { styledBaseImport?: [string, string], isWeb: boolean }
} */
) => {
let t = babel.types
let getStyledIdentifier = () => {
if (
!styledBaseImport ||
(styledBaseImport[0] === importSource &&
styledBaseImport[1] === importSpecifierName)
) {
return t.cloneNode(reference.node)
}
if (path.node) {
const referencedSpecifier = getReferencedSpecifier(
path,
importSpecifierName
)
if (referencedSpecifier) {
referencedSpecifier.remove()
}
if (!path.get('specifiers').length) {
path.remove()
}
}
const [baseImportSource, baseSpecifierName] = styledBaseImport
return addImport(state, baseImportSource, baseSpecifierName, 'styled')
}
let createStyledComponentPath = null
if (
t.isMemberExpression(reference.parent) &&
reference.parent.computed === false
) {
if (
// checks if the first character is lowercase
// becasue we don't want to transform the member expression if
// it's in primitives/native
reference.parent.property.name.charCodeAt(0) > 96
) {
reference.parentPath.replaceWith(
t.callExpression(getStyledIdentifier(), [
t.stringLiteral(reference.parent.property.name)
])
)
} else {
reference.replaceWith(getStyledIdentifier())
}
createStyledComponentPath = reference.parentPath
} else if (
reference.parentPath &&
t.isCallExpression(reference.parentPath) &&
reference.parent.callee === reference.node
) {
reference.replaceWith(getStyledIdentifier())
createStyledComponentPath = reference.parentPath
}
if (!createStyledComponentPath) {
return
}
const styledCallLikeWithStylesPath = createStyledComponentPath.parentPath
let node = transformExpressionWithStyles({
path: styledCallLikeWithStylesPath,
state,
babel,
shouldLabel: false
})
if (node && isWeb) {
// we know the argument length will be 1 since that's the only time we will have a node since it will be static
styledCallLikeWithStylesPath.node.arguments[0] = node
}
styledCallLikeWithStylesPath.addComment('leading', '#__PURE__')
if (isWeb) {
createStyledComponentPath.node.arguments[1] = getStyledOptions(
t,
createStyledComponentPath,
state
)
}
}
export let createStyledMacro = (
{
importSource,
originalImportSource = importSource,
baseImportName = 'default',
isWeb
} /*: {
importSource: string,
originalImportSource?: string,
baseImportName?: string,
isWeb: boolean
} */
) =>
createTransformerMacro(
{
default: [
styledTransformer,
{ styledBaseImport: [importSource, baseImportName], isWeb }
]
},
{ importSource: originalImportSource }
)

View File

@ -0,0 +1,30 @@
import { addDefault, addNamed } from '@babel/helper-module-imports'
export function addImport(
state,
importSource /*: string */,
importedSpecifier /*: string */,
nameHint /* ?: string */
) {
let cacheKey = ['import', importSource, importedSpecifier].join(':')
if (state[cacheKey] === undefined) {
let importIdentifier
if (importedSpecifier === 'default') {
importIdentifier = addDefault(state.file.path, importSource, { nameHint })
} else {
importIdentifier = addNamed(
state.file.path,
importedSpecifier,
importSource,
{
nameHint
}
)
}
state[cacheKey] = importIdentifier.name
}
return {
type: 'Identifier',
name: state[cacheKey]
}
}

View File

@ -0,0 +1,14 @@
export default function createNodeEnvConditional(t, production, development) {
return t.conditionalExpression(
t.binaryExpression(
'===',
t.memberExpression(
t.memberExpression(t.identifier('process'), t.identifier('env')),
t.identifier('NODE_ENV')
),
t.stringLiteral('production')
),
production,
development
)
}

View File

@ -0,0 +1,102 @@
import { getLabelFromPath } from './label'
import { getTargetClassName } from './get-target-class-name'
import createNodeEnvConditional from './create-node-env-conditional'
const getKnownProperties = (t, node) =>
new Set(
node.properties
.filter(n => t.isObjectProperty(n) && !n.computed)
.map(n => (t.isIdentifier(n.key) ? n.key.name : n.key.value))
)
const createObjectSpreadLike = (t, file, ...objs) =>
t.callExpression(file.addHelper('extends'), [t.objectExpression([]), ...objs])
export let getStyledOptions = (t, path, state) => {
const autoLabel = state.opts.autoLabel || 'dev-only'
let args = path.node.arguments
let optionsArgument = args.length >= 2 ? args[1] : null
let prodProperties = []
let devProperties = null
let knownProperties =
optionsArgument && t.isObjectExpression(optionsArgument)
? getKnownProperties(t, optionsArgument)
: new Set()
if (!knownProperties.has('target')) {
prodProperties.push(
t.objectProperty(
t.identifier('target'),
t.stringLiteral(getTargetClassName(state, t))
)
)
}
let label =
autoLabel !== 'never' && !knownProperties.has('label')
? getLabelFromPath(path, state, t)
: null
if (label) {
const labelNode = t.objectProperty(
t.identifier('label'),
t.stringLiteral(label)
)
switch (autoLabel) {
case 'always':
prodProperties.push(labelNode)
break
case 'dev-only':
devProperties = [labelNode]
break
}
}
if (optionsArgument) {
// for some reason `.withComponent` transformer gets requeued
// so check if this has been already transpiled to avoid double wrapping
if (
t.isConditionalExpression(optionsArgument) &&
t.isBinaryExpression(optionsArgument.test) &&
t.buildMatchMemberExpression('process.env.NODE_ENV')(
optionsArgument.test.left
)
) {
return optionsArgument
}
if (!t.isObjectExpression(optionsArgument)) {
const prodNode = createObjectSpreadLike(
t,
state.file,
t.objectExpression(prodProperties),
optionsArgument
)
return devProperties
? createNodeEnvConditional(
t,
prodNode,
t.cloneNode(
createObjectSpreadLike(
t,
state.file,
t.objectExpression(prodProperties.concat(devProperties)),
optionsArgument
)
)
)
: prodNode
}
prodProperties.unshift(...optionsArgument.properties)
}
return devProperties
? createNodeEnvConditional(
t,
t.objectExpression(prodProperties),
t.cloneNode(t.objectExpression(prodProperties.concat(devProperties)))
)
: t.objectExpression(prodProperties)
}

View File

@ -0,0 +1,51 @@
import findRoot from 'find-root'
import memoize from '@emotion/memoize'
import nodePath from 'path'
import hashString from '@emotion/hash'
import escapeRegexp from 'escape-string-regexp'
let hashArray = (arr /*: Array<string> */) => hashString(arr.join(''))
const unsafeRequire = require
const getPackageRootPath = memoize(filename => findRoot(filename))
const separator = new RegExp(escapeRegexp(nodePath.sep), 'g')
const normalizePath = path => nodePath.normalize(path).replace(separator, '/')
export function getTargetClassName(state, t) {
if (state.emotionTargetClassNameCount === undefined) {
state.emotionTargetClassNameCount = 0
}
const hasFilepath =
state.file.opts.filename && state.file.opts.filename !== 'unknown'
const filename = hasFilepath ? state.file.opts.filename : ''
// normalize the file path to ignore folder structure
// outside the current node project and arch-specific delimiters
let moduleName = ''
let rootPath = filename
try {
rootPath = getPackageRootPath(filename)
moduleName = unsafeRequire(rootPath + '/package.json').name
} catch (err) {}
const finalPath =
filename === rootPath ? 'root' : filename.slice(rootPath.length)
const positionInFile = state.emotionTargetClassNameCount++
const stuffToHash = [moduleName]
if (finalPath) {
stuffToHash.push(normalizePath(finalPath))
} else {
stuffToHash.push(state.file.code)
}
const stableClassName = `e${hashArray(stuffToHash)}${positionInFile}`
return stableClassName
}

View File

@ -0,0 +1,12 @@
export { getLabelFromPath } from './label'
export { getSourceMap } from './source-maps'
export { getTargetClassName } from './get-target-class-name'
export { simplifyObject } from './object-to-string'
export { transformExpressionWithStyles } from './transform-expression-with-styles'
export { getStyledOptions } from './get-styled-options'
export {
appendStringReturningExpressionToArguments,
joinStringLiterals
} from './strings'
export { addImport } from './add-import'
export { createTransformerMacro } from './transformer-macro'

192
mc_test/node_modules/@emotion/babel-plugin/src/utils/label.js generated vendored Executable file
View File

@ -0,0 +1,192 @@
import nodePath from 'path'
/*
type LabelFormatOptions = {
name: string,
path: string
}
*/
const invalidClassNameCharacters = /[!"#$%&'()*+,./:;<=>?@[\]^`|}~{]/g
const sanitizeLabelPart = (labelPart /*: string */) =>
labelPart.trim().replace(invalidClassNameCharacters, '-')
function getLabel(
identifierName /* ?: string */,
labelFormat /* ?: string | (LabelFormatOptions => string) */,
filename /*: string */
) {
if (!identifierName) return null
const sanitizedName = sanitizeLabelPart(identifierName)
if (!labelFormat) {
return sanitizedName
}
if (typeof labelFormat === 'function') {
return labelFormat({
name: sanitizedName,
path: filename
})
}
const parsedPath = nodePath.parse(filename)
let localDirname = nodePath.basename(parsedPath.dir)
let localFilename = parsedPath.name
if (localFilename === 'index') {
localFilename = localDirname
}
return labelFormat
.replace(/\[local\]/gi, sanitizedName)
.replace(/\[filename\]/gi, sanitizeLabelPart(localFilename))
.replace(/\[dirname\]/gi, sanitizeLabelPart(localDirname))
}
export function getLabelFromPath(path, state, t) {
return getLabel(
getIdentifierName(path, t),
state.opts.labelFormat,
state.file.opts.filename
)
}
const getObjPropertyLikeName = (path, t) => {
if (
(!t.isObjectProperty(path) && !t.isObjectMethod(path)) ||
path.node.computed
) {
return null
}
if (t.isIdentifier(path.node.key)) {
return path.node.key.name
}
if (t.isStringLiteral(path.node.key)) {
return path.node.key.value.replace(/\s+/g, '-')
}
return null
}
function getDeclaratorName(path, t) {
const parent = path.findParent(
p =>
p.isVariableDeclarator() ||
p.isAssignmentExpression() ||
p.isFunctionDeclaration() ||
p.isFunctionExpression() ||
p.isArrowFunctionExpression() ||
p.isObjectProperty() ||
p.isObjectMethod()
)
if (!parent) {
return ''
}
// we probably have a css call assigned to a variable
// so we'll just return the variable name
if (parent.isVariableDeclarator()) {
if (t.isIdentifier(parent.node.id)) {
return parent.node.id.name
}
return ''
}
if (parent.isAssignmentExpression()) {
let { left } = parent.node
if (t.isIdentifier(left)) {
return left.name
}
if (t.isMemberExpression(left)) {
let memberExpression = left
let name = ''
while (true) {
if (!t.isIdentifier(memberExpression.property)) {
return ''
}
name = `${memberExpression.property.name}${name ? `-${name}` : ''}`
if (t.isIdentifier(memberExpression.object)) {
return `${memberExpression.object.name}-${name}`
}
if (!t.isMemberExpression(memberExpression.object)) {
return ''
}
memberExpression = memberExpression.object
}
}
return ''
}
// we probably have an inline css prop usage
if (parent.isFunctionDeclaration()) {
return parent.node.id.name || ''
}
if (parent.isFunctionExpression()) {
if (parent.node.id) {
return parent.node.id.name || ''
}
return getDeclaratorName(parent, t)
}
if (parent.isArrowFunctionExpression()) {
return getDeclaratorName(parent, t)
}
// we could also have an object property
const objPropertyLikeName = getObjPropertyLikeName(parent, t)
if (objPropertyLikeName) {
return objPropertyLikeName
}
let variableDeclarator = parent.findParent(p => p.isVariableDeclarator())
if (!variableDeclarator || !variableDeclarator.get('id').isIdentifier()) {
return ''
}
return variableDeclarator.node.id.name
}
function getIdentifierName(path, t) {
let objPropertyLikeName = getObjPropertyLikeName(path.parentPath, t)
if (objPropertyLikeName) {
return objPropertyLikeName
}
let classOrClassPropertyParent = path.findParent(
p => t.isClassProperty(p) || t.isClass(p)
)
if (classOrClassPropertyParent) {
if (
t.isClassProperty(classOrClassPropertyParent) &&
classOrClassPropertyParent.node.computed === false &&
t.isIdentifier(classOrClassPropertyParent.node.key)
) {
return classOrClassPropertyParent.node.key.name
}
if (
t.isClass(classOrClassPropertyParent) &&
classOrClassPropertyParent.node.id
) {
return t.isIdentifier(classOrClassPropertyParent.node.id)
? classOrClassPropertyParent.node.id.name
: ''
}
}
let declaratorName = getDeclaratorName(path, t)
// if the name starts with _ it was probably generated by babel so we should ignore it
if (declaratorName.charAt(0) === '_') {
return ''
}
return declaratorName
}

View File

@ -0,0 +1,153 @@
import { compile } from 'stylis'
const haveSameLocation = (element1, element2) => {
return element1.line === element2.line && element1.column === element2.column
}
const isAutoInsertedRule = element =>
element.type === 'rule' &&
element.parent &&
haveSameLocation(element, element.parent)
const toInputTree = (elements, tree) => {
for (let i = 0; i < elements.length; i++) {
const element = elements[i]
const { parent, children } = element
if (!parent) {
tree.push(element)
} else if (!isAutoInsertedRule(element)) {
parent.children.push(element)
}
if (Array.isArray(children)) {
element.children = []
toInputTree(children, tree)
}
}
return tree
}
var stringifyTree = elements => {
return elements
.map(element => {
switch (element.type) {
case 'import':
case 'decl':
return element.value
case 'comm':
// When we encounter a standard multi-line CSS comment and it contains a '@'
// character, we keep the comment. Some Stylis plugins, such as
// the stylis-rtl via the cssjanus plugin, use this special comment syntax
// to control behavior (such as: /* @noflip */). We can do this
// with standard CSS comments because they will work with compression,
// as opposed to non-standard single-line comments that will break compressed CSS.
return element.props === '/' && element.value.includes('@')
? element.value
: ''
case 'rule':
return `${element.value.replace(/&\f/g, '&')}{${stringifyTree(
element.children
)}}`
default: {
return `${element.value}{${stringifyTree(element.children)}}`
}
}
})
.join('')
}
const interleave = (strings /*: Array<*> */, interpolations /*: Array<*> */) =>
interpolations.reduce(
(array, interp, i) => array.concat([interp], strings[i + 1]),
[strings[0]]
)
function getDynamicMatches(str /*: string */) {
const re = /xxx(\d+):xxx/gm
let match
const matches = []
while ((match = re.exec(str)) !== null) {
if (match !== null) {
matches.push({
value: match[0],
p1: parseInt(match[1], 10),
index: match.index
})
}
}
return matches
}
function replacePlaceholdersWithExpressions(
str /*: string */,
expressions /*: Array<*> */,
t
) {
const matches = getDynamicMatches(str)
if (matches.length === 0) {
if (str === '') {
return []
}
return [t.stringLiteral(str)]
}
const strings = []
const finalExpressions = []
let cursor = 0
matches.forEach(({ value, p1, index }, i) => {
const preMatch = str.substring(cursor, index)
cursor = cursor + preMatch.length + value.length
if (!preMatch && i === 0) {
strings.push(t.stringLiteral(''))
} else {
strings.push(t.stringLiteral(preMatch))
}
finalExpressions.push(expressions[p1])
if (i === matches.length - 1) {
strings.push(t.stringLiteral(str.substring(index + value.length)))
}
})
return interleave(strings, finalExpressions).filter(
(node /*: { value: string } */) => {
return node.value !== ''
}
)
}
function createRawStringFromTemplateLiteral(
quasi /*: {
quasis: Array<{ value: { cooked: string } }>
} */
) {
let strs = quasi.quasis.map(x => x.value.cooked)
const src = strs
.reduce((arr, str, i) => {
arr.push(str)
if (i !== strs.length - 1) {
arr.push(`xxx${i}:xxx`)
}
return arr
}, [])
.join('')
.trim()
return src
}
export default function minify(path, t) {
const quasi = path.node.quasi
const raw = createRawStringFromTemplateLiteral(quasi)
const minified = stringifyTree(toInputTree(compile(raw), []))
const expressions = replacePlaceholdersWithExpressions(
minified,
quasi.expressions || [],
t
)
path.replaceWith(t.callExpression(path.node.tag, expressions))
}

View File

@ -0,0 +1,39 @@
import { serializeStyles } from '@emotion/serialize'
// to anyone looking at this, this isn't intended to simplify every single case
// it's meant to simplify the most common cases so i don't want to make it especially complex
// also, this will be unnecessary when prepack is ready
export function simplifyObject(node, t /*: Object */) {
let finalString = ''
for (let i = 0; i < node.properties.length; i++) {
let property = node.properties[i]
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))
) {
return node
}
let key = property.key.name || property.key.value
if (key === 'styles') {
return node
}
if (t.isObjectExpression(property.value)) {
let simplifiedChild = simplifyObject(property.value, t)
if (!t.isStringLiteral(simplifiedChild)) {
return node
}
finalString += `${key}{${simplifiedChild.value}}`
continue
}
let value = property.value.value
finalString += serializeStyles([{ [key]: value }]).styles
}
return t.stringLiteral(finalString)
}

View File

@ -0,0 +1,44 @@
import { SourceMapGenerator } from 'source-map'
import convert from 'convert-source-map'
function getGeneratorOpts(file) {
return file.opts.generatorOpts ? file.opts.generatorOpts : file.opts
}
export function makeSourceMapGenerator(file) {
const generatorOpts = getGeneratorOpts(file)
const filename = generatorOpts.sourceFileName
const generator = new SourceMapGenerator({
file: filename,
sourceRoot: generatorOpts.sourceRoot
})
generator.setSourceContent(filename, file.code)
return generator
}
export function getSourceMap(
offset /*: {
line: number,
column: number
} */,
state
) /*: string */ {
const generator = makeSourceMapGenerator(state.file)
const generatorOpts = getGeneratorOpts(state.file)
if (
generatorOpts.sourceFileName &&
generatorOpts.sourceFileName !== 'unknown'
) {
generator.addMapping({
generated: {
line: 1,
column: 0
},
source: generatorOpts.sourceFileName,
original: offset
})
return convert.fromObject(generator).toComment({ multiline: true })
}
return ''
}

View File

@ -0,0 +1,60 @@
import {
getTypeScriptMakeTemplateObjectPath,
isTaggedTemplateTranspiledByBabel
} from './transpiled-output-utils'
export const appendStringReturningExpressionToArguments = (
t,
path,
expression
) => {
let lastIndex = path.node.arguments.length - 1
let last = path.node.arguments[lastIndex]
if (t.isStringLiteral(last)) {
if (typeof expression === 'string') {
path.node.arguments[lastIndex].value += expression
} else {
path.node.arguments[lastIndex] = t.binaryExpression('+', last, expression)
}
} else {
const makeTemplateObjectCallPath = getTypeScriptMakeTemplateObjectPath(path)
if (makeTemplateObjectCallPath) {
makeTemplateObjectCallPath.get('arguments').forEach(argPath => {
const elements = argPath.get('elements')
const lastElement = elements[elements.length - 1]
if (typeof expression === 'string') {
lastElement.replaceWith(
t.stringLiteral(lastElement.node.value + expression)
)
} else {
lastElement.replaceWith(
t.binaryExpression('+', lastElement.node, t.cloneNode(expression))
)
}
})
} else if (!isTaggedTemplateTranspiledByBabel(path)) {
if (typeof expression === 'string') {
path.node.arguments.push(t.stringLiteral(expression))
} else {
path.node.arguments.push(expression)
}
}
}
}
export const joinStringLiterals = (expressions /*: Array<*> */, t) => {
return expressions.reduce((finalExpressions, currentExpression, i) => {
if (!t.isStringLiteral(currentExpression)) {
finalExpressions.push(currentExpression)
} else if (
t.isStringLiteral(finalExpressions[finalExpressions.length - 1])
) {
finalExpressions[finalExpressions.length - 1].value +=
currentExpression.value
} else {
finalExpressions.push(currentExpression)
}
return finalExpressions
}, [])
}

View File

@ -0,0 +1,144 @@
import { serializeStyles } from '@emotion/serialize'
import minify from './minify'
import { getLabelFromPath } from './label'
import { getSourceMap } from './source-maps'
import { simplifyObject } from './object-to-string'
import {
appendStringReturningExpressionToArguments,
joinStringLiterals
} from './strings'
import createNodeEnvConditional from './create-node-env-conditional'
const 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)."
export let transformExpressionWithStyles = (
{ babel, state, path, shouldLabel, sourceMap = '' } /*: {
babel,
state,
path,
shouldLabel: boolean,
sourceMap?: string
} */
) => {
const autoLabel = state.opts.autoLabel || 'dev-only'
let t = babel.types
if (t.isTaggedTemplateExpression(path)) {
if (
!sourceMap &&
state.emotionSourceMap &&
path.node.quasi.loc !== undefined
) {
sourceMap = getSourceMap(path.node.quasi.loc.start, state)
}
minify(path, t)
}
if (t.isCallExpression(path)) {
const canAppendStrings = path.node.arguments.every(
arg => arg.type !== 'SpreadElement'
)
path.get('arguments').forEach(node => {
if (t.isObjectExpression(node)) {
node.replaceWith(simplifyObject(node.node, t))
}
})
path.node.arguments = joinStringLiterals(path.node.arguments, t)
if (
!sourceMap &&
canAppendStrings &&
state.emotionSourceMap &&
path.node.loc !== undefined
) {
sourceMap = getSourceMap(path.node.loc.start, state)
}
const label =
shouldLabel && autoLabel !== 'never'
? getLabelFromPath(path, state, t)
: null
if (
path.node.arguments.length === 1 &&
t.isStringLiteral(path.node.arguments[0])
) {
let cssString = path.node.arguments[0].value.replace(/;$/, '')
let res = serializeStyles([
`${cssString}${
label && autoLabel === 'always' ? `;label:${label};` : ''
}`
])
let prodNode = t.objectExpression([
t.objectProperty(t.identifier('name'), t.stringLiteral(res.name)),
t.objectProperty(t.identifier('styles'), t.stringLiteral(res.styles))
])
if (!state.emotionStringifiedCssId) {
const uid = state.file.scope.generateUidIdentifier(
'__EMOTION_STRINGIFIED_CSS_ERROR__'
)
state.emotionStringifiedCssId = uid
const cssObjectToString = t.functionDeclaration(
uid,
[],
t.blockStatement([
t.returnStatement(t.stringLiteral(CSS_OBJECT_STRINGIFIED_ERROR))
])
)
cssObjectToString._compact = true
state.file.path.unshiftContainer('body', [cssObjectToString])
}
if (label && autoLabel === 'dev-only') {
res = serializeStyles([`${cssString};label:${label};`])
}
let devNode = t.objectExpression(
[
t.objectProperty(t.identifier('name'), t.stringLiteral(res.name)),
t.objectProperty(
t.identifier('styles'),
t.stringLiteral(res.styles + sourceMap)
),
t.objectProperty(
t.identifier('toString'),
t.cloneNode(state.emotionStringifiedCssId)
)
].filter(Boolean)
)
return createNodeEnvConditional(t, prodNode, devNode)
}
if (canAppendStrings && label) {
const labelString = `;label:${label};`
switch (autoLabel) {
case 'dev-only': {
const labelConditional = createNodeEnvConditional(
t,
t.stringLiteral(''),
t.stringLiteral(labelString)
)
appendStringReturningExpressionToArguments(t, path, labelConditional)
break
}
case 'always':
appendStringReturningExpressionToArguments(t, path, labelString)
break
}
}
if (sourceMap) {
let sourceMapConditional = createNodeEnvConditional(
t,
t.stringLiteral(''),
t.stringLiteral(sourceMap)
)
appendStringReturningExpressionToArguments(t, path, sourceMapConditional)
}
}
}

View File

@ -0,0 +1,59 @@
import { createMacro } from 'babel-plugin-macros'
/*
type Transformer = Function
*/
export function createTransformerMacro(
transformers /*: { [key: string]: Transformer | [Transformer, Object] } */,
{ importSource } /*: { importSource: string } */
) {
let macro = createMacro(
({ path, source, references, state, babel, isEmotionCall }) => {
if (!path) {
path = state.file.scope.path
.get('body')
.find(p => p.isImportDeclaration() && p.node.source.value === source)
}
if (/\/macro$/.test(source)) {
path
.get('source')
.replaceWith(
babel.types.stringLiteral(source.replace(/\/macro$/, ''))
)
}
if (!isEmotionCall) {
state.emotionSourceMap = true
}
Object.keys(references).forEach(importSpecifierName => {
if (transformers[importSpecifierName]) {
references[importSpecifierName].reverse().forEach(reference => {
let options
let transformer
if (Array.isArray(transformers[importSpecifierName])) {
transformer = transformers[importSpecifierName][0]
options = transformers[importSpecifierName][1]
} else {
transformer = transformers[importSpecifierName]
options = {}
}
transformer({
state,
babel,
path,
importSource,
importSpecifierName,
options,
reference
})
})
}
})
return { keepImports: true }
}
)
macro.transformers = transformers
return macro
}

View File

@ -0,0 +1,78 @@
// this only works correctly in modules, but we don't run on scripts anyway, so it's fine
// the difference is that in modules template objects are being cached per call site
export function getTypeScriptMakeTemplateObjectPath(path) {
if (path.node.arguments.length === 0) {
return null
}
const firstArgPath = path.get('arguments')[0]
if (
firstArgPath.isLogicalExpression() &&
firstArgPath.get('left').isIdentifier() &&
firstArgPath.get('right').isAssignmentExpression() &&
firstArgPath.get('right.right').isCallExpression() &&
firstArgPath.get('right.right.callee').isIdentifier() &&
firstArgPath.node.right.right.callee.name.includes('makeTemplateObject') &&
firstArgPath.node.right.right.arguments.length === 2
) {
return firstArgPath.get('right.right')
}
return null
}
// this is only used to prevent appending strings/expressions to arguments incorectly
// we could push them to found array expressions, as we do it for TS-transpile output ¯\_(ツ)_/¯
// it seems overly complicated though - mainly because we'd also have to check against existing stuff of a particular type (source maps & labels)
// considering Babel double-transpilation as a valid use case seems rather far-fetched
export function isTaggedTemplateTranspiledByBabel(path) {
if (path.node.arguments.length === 0) {
return false
}
const firstArgPath = path.get('arguments')[0]
if (
!firstArgPath.isCallExpression() ||
!firstArgPath.get('callee').isIdentifier()
) {
return false
}
const calleeName = firstArgPath.node.callee.name
if (!calleeName.includes('templateObject')) {
return false
}
const bindingPath = path.scope.getBinding(calleeName).path
if (!bindingPath.isFunction()) {
return false
}
const functionBody = bindingPath.get('body.body')
if (!functionBody[0].isVariableDeclaration()) {
return false
}
const declarationInit = functionBody[0].get('declarations')[0].get('init')
if (!declarationInit.isCallExpression()) {
return false
}
const declarationInitArguments = declarationInit.get('arguments')
if (
declarationInitArguments.length === 0 ||
declarationInitArguments.length > 2 ||
declarationInitArguments.some(argPath => !argPath.isArrayExpression())
) {
return false
}
return true
}