This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

21
frontend/node_modules/@emotion/babel-plugin/LICENSE generated vendored Normal 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
frontend/node_modules/@emotion/babel-plugin/README.md generated vendored Normal 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

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.

View File

@@ -0,0 +1 @@
export default function memoize<V>(fn: (arg: string) => V): (arg: string) => V;

View File

@@ -0,0 +1,3 @@
export * from "./declarations/src/index.js";
export { _default as default } from "./emotion-memoize.cjs.default.js";
//# sourceMappingURL=emotion-memoize.cjs.d.mts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"emotion-memoize.cjs.d.mts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}

View File

@@ -0,0 +1,3 @@
export * from "./declarations/src/index";
export { default } from "./declarations/src/index";
//# sourceMappingURL=emotion-memoize.cjs.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"emotion-memoize.cjs.d.ts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}

View File

@@ -0,0 +1 @@
export { default as _default } from "./declarations/src/index.js"

View File

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

View File

@@ -0,0 +1,13 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
exports["default"] = memoize;

View File

@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === "production") {
module.exports = require("./emotion-memoize.cjs.prod.js");
} else {
module.exports = require("./emotion-memoize.cjs.dev.js");
}

View File

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

View File

@@ -0,0 +1,13 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
exports["default"] = memoize;

View File

@@ -0,0 +1,9 @@
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
export { memoize as default };

View File

@@ -0,0 +1,32 @@
{
"name": "@emotion/memoize",
"version": "0.9.0",
"description": "emotion's memoize utility",
"main": "dist/emotion-memoize.cjs.js",
"module": "dist/emotion-memoize.esm.js",
"types": "dist/emotion-memoize.cjs.d.ts",
"license": "MIT",
"repository": "https://github.com/emotion-js/emotion/tree/main/packages/memoize",
"scripts": {
"test:typescript": "dtslint types"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@definitelytyped/dtslint": "0.0.112",
"typescript": "^5.4.5"
},
"files": [
"src",
"dist"
],
"exports": {
".": {
"module": "./dist/emotion-memoize.esm.js",
"import": "./dist/emotion-memoize.cjs.mjs",
"default": "./dist/emotion-memoize.cjs.js"
},
"./package.json": "./package.json"
}
}

View File

@@ -0,0 +1,8 @@
export default function memoize<V>(fn: (arg: string) => V): (arg: string) => V {
const cache: Record<string, V> = Object.create(null)
return (arg: string) => {
if (cache[arg] === undefined) cache[arg] = fn(arg)
return cache[arg]
}
}

View File

@@ -0,0 +1,23 @@
Copyright 2013 Thorsten Lorenz.
All rights reserved.
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.

View File

@@ -0,0 +1,123 @@
# convert-source-map [![Build Status][ci-image]][ci-url]
Converts a source-map from/to different formats and allows adding/changing properties.
```js
var convert = require('convert-source-map');
var json = convert
.fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();
var modified = convert
.fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.setProperty('sources', [ 'SRC/FOO.JS' ])
.toJSON();
console.log(json);
console.log(modified);
```
```json
{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
{"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
```
## API
### fromObject(obj)
Returns source map converter from given object.
### fromJSON(json)
Returns source map converter from given json string.
### fromBase64(base64)
Returns source map converter from given base64 encoded json string.
### fromComment(comment)
Returns source map converter from given base64 encoded json string prefixed with `//# sourceMappingURL=...`.
### fromMapFileComment(comment, mapFileDir)
Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`.
`filename` must point to a file that is found inside the `mapFileDir`. Most tools store this file right next to the
generated file, i.e. the one containing the source map.
### fromSource(source)
Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found.
### fromMapFileSource(source, mapFileDir)
Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was
found.
The sourcemap will be read from the map file found by parsing `# sourceMappingURL=file` comment. For more info see
fromMapFileComment.
### toObject()
Returns a copy of the underlying source map.
### toJSON([space])
Converts source map to json string. If `space` is given (optional), this will be passed to
[JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the
JSON string is generated.
### toBase64()
Converts source map to base64 encoded json string.
### toComment([options])
Converts source map to an inline comment that can be appended to the source-file.
By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would
normally see in a JS source file.
When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
### addProperty(key, value)
Adds given property to the source map. Throws an error if property already exists.
### setProperty(key, value)
Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated.
### getProperty(key)
Gets given property of the source map.
### removeComments(src)
Returns `src` with all source map comments removed
### removeMapFileComments(src)
Returns `src` with all source map comments pointing to map files removed.
### commentRegex
Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments.
### mapFileCommentRegex
Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files.
### generateMapFileComment(file, [options])
Returns a comment that links to an external source map via `file`.
By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file.
When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
[ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci
[ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square

View File

@@ -0,0 +1,179 @@
'use strict';
var fs = require('fs');
var path = require('path');
Object.defineProperty(exports, 'commentRegex', {
get: function getCommentRegex () {
return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg;
}
});
Object.defineProperty(exports, 'mapFileCommentRegex', {
get: function getMapFileCommentRegex () {
// Matches sourceMappingURL in either // or /* comment styles.
return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg;
}
});
var decodeBase64;
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
decodeBase64 = decodeBase64WithBufferFrom;
} else {
decodeBase64 = decodeBase64WithNewBuffer;
}
} else {
decodeBase64 = decodeBase64WithAtob;
}
function decodeBase64WithBufferFrom(base64) {
return Buffer.from(base64, 'base64').toString();
}
function decodeBase64WithNewBuffer(base64) {
if (typeof value === 'number') {
throw new TypeError('The value to decode must not be of type number.');
}
return new Buffer(base64, 'base64').toString();
}
function decodeBase64WithAtob(base64) {
return decodeURIComponent(escape(atob(base64)));
}
function stripComment(sm) {
return sm.split(',').pop();
}
function readFromFileMap(sm, dir) {
// NOTE: this will only work on the server since it attempts to read the map file
var r = exports.mapFileCommentRegex.exec(sm);
// for some odd reason //# .. captures in 1 and /* .. */ in 2
var filename = r[1] || r[2];
var filepath = path.resolve(dir, filename);
try {
return fs.readFileSync(filepath, 'utf8');
} catch (e) {
throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
}
}
function Converter (sm, opts) {
opts = opts || {};
if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
if (opts.hasComment) sm = stripComment(sm);
if (opts.isEncoded) sm = decodeBase64(sm);
if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
this.sourcemap = sm;
}
Converter.prototype.toJSON = function (space) {
return JSON.stringify(this.sourcemap, null, space);
};
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
} else {
Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
}
} else {
Converter.prototype.toBase64 = encodeBase64WithBtoa;
}
function encodeBase64WithBufferFrom() {
var json = this.toJSON();
return Buffer.from(json, 'utf8').toString('base64');
}
function encodeBase64WithNewBuffer() {
var json = this.toJSON();
if (typeof json === 'number') {
throw new TypeError('The json to encode must not be of type number.');
}
return new Buffer(json, 'utf8').toString('base64');
}
function encodeBase64WithBtoa() {
var json = this.toJSON();
return btoa(unescape(encodeURIComponent(json)));
}
Converter.prototype.toComment = function (options) {
var base64 = this.toBase64();
var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};
// returns copy instead of original
Converter.prototype.toObject = function () {
return JSON.parse(this.toJSON());
};
Converter.prototype.addProperty = function (key, value) {
if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
return this.setProperty(key, value);
};
Converter.prototype.setProperty = function (key, value) {
this.sourcemap[key] = value;
return this;
};
Converter.prototype.getProperty = function (key) {
return this.sourcemap[key];
};
exports.fromObject = function (obj) {
return new Converter(obj);
};
exports.fromJSON = function (json) {
return new Converter(json, { isJSON: true });
};
exports.fromBase64 = function (base64) {
return new Converter(base64, { isEncoded: true });
};
exports.fromComment = function (comment) {
comment = comment
.replace(/^\/\*/g, '//')
.replace(/\*\/$/g, '');
return new Converter(comment, { isEncoded: true, hasComment: true });
};
exports.fromMapFileComment = function (comment, dir) {
return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromSource = function (content) {
var m = content.match(exports.commentRegex);
return m ? exports.fromComment(m.pop()) : null;
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromMapFileSource = function (content, dir) {
var m = content.match(exports.mapFileCommentRegex);
return m ? exports.fromMapFileComment(m.pop(), dir) : null;
};
exports.removeComments = function (src) {
return src.replace(exports.commentRegex, '');
};
exports.removeMapFileComments = function (src) {
return src.replace(exports.mapFileCommentRegex, '');
};
exports.generateMapFileComment = function (file, options) {
var data = 'sourceMappingURL=' + file;
return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};

View File

@@ -0,0 +1,41 @@
{
"name": "convert-source-map",
"version": "1.9.0",
"description": "Converts a source-map from/to different formats and allows adding/changing properties.",
"main": "index.js",
"scripts": {
"test": "tap test/*.js --color"
},
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/convert-source-map.git"
},
"homepage": "https://github.com/thlorenz/convert-source-map",
"devDependencies": {
"inline-source-map": "~0.6.2",
"tap": "~9.0.0"
},
"keywords": [
"convert",
"sourcemap",
"source",
"map",
"browser",
"debug"
],
"author": {
"name": "Thorsten Lorenz",
"email": "thlorenz@gmx.de",
"url": "http://thlorenz.com"
},
"license": "MIT",
"engine": {
"node": ">=0.6"
},
"files": [
"index.js"
],
"browser": {
"fs": false
}
}

View File

@@ -0,0 +1,301 @@
# Change Log
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

View File

@@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,729 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source.
* `column`: The column number in the generated source.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available.
* `column`: The column number in the original source, or null if this
information is not available.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source.
* `column`: The column number in the original source.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null.
* `column`: The column number in the generated source, or null.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source.
* `column`: Optional. The column number in the original source.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null.
* `column`: The column number in the generated source, or null.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,121 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = hasNativeMap ? new Map() : Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
if (hasNativeMap) {
this._set.set(aStr, idx);
} else {
this._set[sStr] = idx;
}
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
if (hasNativeMap) {
return this._set.has(aStr);
} else {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
}
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (hasNativeMap) {
var idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
} else {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;

View File

@@ -0,0 +1,140 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};

View File

@@ -0,0 +1,67 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return (charCode - bigA);
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return (charCode - littleA + littleOffset);
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return (charCode - zero + numberOffset);
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};

View File

@@ -0,0 +1,111 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
}
else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};

View File

@@ -0,0 +1,79 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;

View File

@@ -0,0 +1,114 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,416 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
var MappingList = require('./mapping-list').MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source)
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
// When aOriginal is truthy but has empty values for .line and .column,
// it is most likely a programmer error. In this case we throw a very
// specific error message to try to guide them the right way.
// For example: https://github.com/Polymer/polymer-bundler/pull/519
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
throw new Error(
'original.line and original.column are not numbers -- you probably meant to omit ' +
'the original mapping entirely and only map the generated position. If so, pass ' +
'null for the original mapping instead of an object with empty or null values.'
);
}
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = ''
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;

View File

@@ -0,0 +1,413 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are accessed by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var remainingLinesIndex = 0;
var shiftNextLine = function() {
var lineContents = getNextLine();
// The last line of a file might not have a newline.
var newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[remainingLinesIndex];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[remainingLinesIndex];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;

View File

@@ -0,0 +1,417 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = (function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}());
function identity (s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;

View File

@@ -0,0 +1,72 @@
{
"name": "source-map",
"description": "Generates and consumes source maps",
"version": "0.5.7",
"homepage": "https://github.com/mozilla/source-map",
"author": "Nick Fitzgerald <nfitzgerald@mozilla.com>",
"contributors": [
"Tobias Koppers <tobias.koppers@googlemail.com>",
"Duncan Beevers <duncan@dweebd.com>",
"Stephen Crane <scrane@mozilla.com>",
"Ryan Seddon <seddon.ryan@gmail.com>",
"Miles Elam <miles.elam@deem.com>",
"Mihai Bazon <mihai.bazon@gmail.com>",
"Michael Ficarra <github.public.email@michael.ficarra.me>",
"Todd Wolfson <todd@twolfson.com>",
"Alexander Solovyov <alexander@solovyov.net>",
"Felix Gnass <fgnass@gmail.com>",
"Conrad Irwin <conrad.irwin@gmail.com>",
"usrbincc <usrbincc@yahoo.com>",
"David Glasser <glasser@davidglasser.net>",
"Chase Douglas <chase@newrelic.com>",
"Evan Wallace <evan.exe@gmail.com>",
"Heather Arthur <fayearthur@gmail.com>",
"Hugh Kennedy <hughskennedy@gmail.com>",
"David Glasser <glasser@davidglasser.net>",
"Simon Lydell <simon.lydell@gmail.com>",
"Jmeas Smith <jellyes2@gmail.com>",
"Michael Z Goddard <mzgoddard@gmail.com>",
"azu <azu@users.noreply.github.com>",
"John Gozde <john@gozde.ca>",
"Adam Kirkton <akirkton@truefitinnovation.com>",
"Chris Montgomery <christopher.montgomery@dowjones.com>",
"J. Ryan Stinnett <jryans@gmail.com>",
"Jack Herrington <jherrington@walmartlabs.com>",
"Chris Truter <jeffpalentine@gmail.com>",
"Daniel Espeset <daniel@danielespeset.com>",
"Jamie Wong <jamie.lf.wong@gmail.com>",
"Eddy Bruël <ejpbruel@mozilla.com>",
"Hawken Rives <hawkrives@gmail.com>",
"Gilad Peleg <giladp007@gmail.com>",
"djchie <djchie.dev@gmail.com>",
"Gary Ye <garysye@gmail.com>",
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
],
"repository": {
"type": "git",
"url": "http://github.com/mozilla/source-map.git"
},
"main": "./source-map.js",
"files": [
"source-map.js",
"lib/",
"dist/source-map.debug.js",
"dist/source-map.js",
"dist/source-map.min.js",
"dist/source-map.min.js.map"
],
"engines": {
"node": ">=0.10.0"
},
"license": "BSD-3-Clause",
"scripts": {
"test": "npm run build && node test/run-tests.js",
"build": "webpack --color",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"devDependencies": {
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
},
"typings": "source-map"
}

View File

@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;

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"
}
}

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 })

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'

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
}

21
frontend/node_modules/@emotion/cache/LICENSE generated vendored Normal 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.

62
frontend/node_modules/@emotion/cache/README.md generated vendored Normal file
View File

@@ -0,0 +1,62 @@
# @emotion/cache
### createCache
`createCache` allows for low level customization of how styles get inserted by emotion. It's intended to be used with the [`<CacheProvider/>`](https://emotion.sh/docs/cache-provider) component to override the default cache, which is created with sensible defaults for most applications.
```javascript
import createCache from '@emotion/cache'
export const myCache = createCache({
key: 'my-prefix-key',
stylisPlugins: [
/* your plugins here */
]
})
```
### Primary use cases
- Using emotion in embedded contexts such as an `<iframe/>`
- Setting a [nonce](#nonce-string) on any `<style/>` tag emotion creates for security purposes
- Using emotion with a developer defined `<style/>` tag
- Using emotion with custom Stylis plugins
## Options
### `nonce`
`string`
A nonce that will be set on each style tag that emotion inserts for [Content Security Policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP).
### `stylisPlugins`
`Array<Function>`
A Stylis plugins that will be run by Stylis during preprocessing. [Read the Stylis docs to find out more](https://github.com/thysultan/stylis.js#middleware). This can be used for many purposes such as RTL.
> Note:
>
> Prefixer is just a plugin which happens to be put in default `stylisPlugins`. If you plan to use custom `stylisPlugins` and you want to have your styles prefixed automatically you must include prefixer in your custom `stylisPlugins`. You can import `prefixer` from the `stylis` module to do that (`import { prefixer } from 'stylis'`);
### `key`
`string (Pattern: [^a-z-])`
The prefix before class names. It will also be set as the value of the `data-emotion` attribute on the style tags that emotion inserts and it's used in the attribute name that marks style elements in `renderStylesToString` and `renderStylesToNodeStream`. This is **required if using multiple emotion caches in the same app**.
### `container`
`Node`
A DOM node that emotion will insert all of its style tags into. This is useful for inserting styles into iframes or windows.
### `prepend`
`boolean`
A boolean representing whether to prepend rather than append style tags into the specified container DOM node.

View File

@@ -0,0 +1,16 @@
import type { EmotionCache } from '@emotion/utils';
import { StylisPlugin } from "./types.js";
export interface Options {
nonce?: string;
stylisPlugins?: Array<StylisPlugin>;
key: string;
container?: Node;
speedy?: boolean;
/** @deprecate use `insertionPoint` instead */
prepend?: boolean;
insertionPoint?: HTMLElement;
}
declare let createCache: (options: Options) => EmotionCache;
export default createCache;
export type { EmotionCache };
export type { StylisElement, StylisPlugin, StylisPluginCallback } from "./types.js";

View File

@@ -0,0 +1,14 @@
export interface StylisElement {
type: string;
value: string;
props: Array<string> | string;
root: StylisElement | null;
parent: StylisElement | null;
children: Array<StylisElement> | string;
line: number;
column: number;
length: number;
return: string;
}
export type StylisPluginCallback = (element: StylisElement, index: number, children: Array<StylisElement>, callback: StylisPluginCallback) => string | void;
export type StylisPlugin = (element: StylisElement, index: number, children: Array<StylisElement>, callback: StylisPluginCallback) => string | void;

View File

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

View File

@@ -0,0 +1,442 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sheet = require('@emotion/sheet');
var stylis = require('stylis');
require('@emotion/weak-memoize');
require('@emotion/memoize');
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = stylis.peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (stylis.token(character)) {
break;
}
stylis.next();
}
return stylis.slice(begin, stylis.position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (stylis.token(character)) {
case 0:
// &\f
if (character === 38 && stylis.peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(stylis.position - 1, points, index);
break;
case 2:
parsed[index] += stylis.delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = stylis.peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += stylis.from(character);
}
} while (character = stylis.next());
return parsed;
};
var getRules = function getRules(value, points) {
return stylis.dealloc(toRules(stylis.alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (stylis.hash(value, length)) {
// color-adjust
case 5103:
return stylis.WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return stylis.WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return stylis.WEBKIT + value + stylis.MOZ + value + stylis.MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return stylis.WEBKIT + value + stylis.MS + value + value;
// order
case 6165:
return stylis.WEBKIT + value + stylis.MS + 'flex-' + value + value;
// align-items
case 5187:
return stylis.WEBKIT + value + stylis.replace(value, /(\w+).+(:[^]+)/, stylis.WEBKIT + 'box-$1$2' + stylis.MS + 'flex-$1$2') + value;
// align-self
case 5443:
return stylis.WEBKIT + value + stylis.MS + 'flex-item-' + stylis.replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return stylis.WEBKIT + value + stylis.MS + 'flex-line-pack' + stylis.replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return stylis.WEBKIT + 'box-' + stylis.replace(value, '-grow', '') + stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return stylis.WEBKIT + stylis.replace(value, /([^-])(transform)/g, '$1' + stylis.WEBKIT + '$2') + value;
// cursor
case 6187:
return stylis.replace(stylis.replace(stylis.replace(value, /(zoom-|grab)/, stylis.WEBKIT + '$1'), /(image-set)/, stylis.WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return stylis.replace(value, /(image-set\([^]*)/, stylis.WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return stylis.replace(stylis.replace(value, /(.+:)(flex-)?(.*)/, stylis.WEBKIT + 'box-pack:$3' + stylis.MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + stylis.WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return stylis.replace(value, /(.+)-inline(.+)/, stylis.WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (stylis.strlen(value) - 1 - length > 6) switch (stylis.charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (stylis.charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return stylis.replace(value, /(.+:)(.+)-([^]+)/, '$1' + stylis.WEBKIT + '$2-$3' + '$1' + stylis.MOZ + (stylis.charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~stylis.indexof(value, 'stretch') ? prefix(stylis.replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (stylis.charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (stylis.charat(value, stylis.strlen(value) - 3 - (~stylis.indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return stylis.replace(value, ':', ':' + stylis.WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return stylis.replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + stylis.WEBKIT + (stylis.charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + stylis.WEBKIT + '$2$3' + '$1' + stylis.MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (stylis.charat(value, length + 11)) {
// vertical-l(r)
case 114:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return stylis.WEBKIT + value + stylis.MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case stylis.DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case stylis.KEYFRAMES:
return stylis.serialize([stylis.copy(element, {
value: stylis.replace(element.value, '@', '@' + stylis.WEBKIT)
})], callback);
case stylis.RULESET:
if (element.length) return stylis.combine(element.props, function (value) {
switch (stylis.match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(read-\w+)/, ':' + stylis.MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.WEBKIT + 'input-$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.MOZ + '$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, stylis.MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
var currentSheet;
var finalizingPlugins = [stylis.stringify, stylis.rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis$1 = function stylis$1(styles) {
return stylis.serialize(stylis.compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis$1(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new sheet.StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
exports["default"] = createCache;

View File

@@ -0,0 +1,2 @@
import "./emotion-cache.browser.cjs.js";
export { _default as default } from "./emotion-cache.browser.cjs.default.js";

View File

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

View File

@@ -0,0 +1,600 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sheet = require('@emotion/sheet');
var stylis = require('stylis');
require('@emotion/weak-memoize');
require('@emotion/memoize');
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = stylis.peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (stylis.token(character)) {
break;
}
stylis.next();
}
return stylis.slice(begin, stylis.position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (stylis.token(character)) {
case 0:
// &\f
if (character === 38 && stylis.peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(stylis.position - 1, points, index);
break;
case 2:
parsed[index] += stylis.delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = stylis.peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += stylis.from(character);
}
} while (character = stylis.next());
return parsed;
};
var getRules = function getRules(value, points) {
return stylis.dealloc(toRules(stylis.alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (stylis.hash(value, length)) {
// color-adjust
case 5103:
return stylis.WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return stylis.WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return stylis.WEBKIT + value + stylis.MOZ + value + stylis.MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return stylis.WEBKIT + value + stylis.MS + value + value;
// order
case 6165:
return stylis.WEBKIT + value + stylis.MS + 'flex-' + value + value;
// align-items
case 5187:
return stylis.WEBKIT + value + stylis.replace(value, /(\w+).+(:[^]+)/, stylis.WEBKIT + 'box-$1$2' + stylis.MS + 'flex-$1$2') + value;
// align-self
case 5443:
return stylis.WEBKIT + value + stylis.MS + 'flex-item-' + stylis.replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return stylis.WEBKIT + value + stylis.MS + 'flex-line-pack' + stylis.replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return stylis.WEBKIT + 'box-' + stylis.replace(value, '-grow', '') + stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return stylis.WEBKIT + stylis.replace(value, /([^-])(transform)/g, '$1' + stylis.WEBKIT + '$2') + value;
// cursor
case 6187:
return stylis.replace(stylis.replace(stylis.replace(value, /(zoom-|grab)/, stylis.WEBKIT + '$1'), /(image-set)/, stylis.WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return stylis.replace(value, /(image-set\([^]*)/, stylis.WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return stylis.replace(stylis.replace(value, /(.+:)(flex-)?(.*)/, stylis.WEBKIT + 'box-pack:$3' + stylis.MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + stylis.WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return stylis.replace(value, /(.+)-inline(.+)/, stylis.WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (stylis.strlen(value) - 1 - length > 6) switch (stylis.charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (stylis.charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return stylis.replace(value, /(.+:)(.+)-([^]+)/, '$1' + stylis.WEBKIT + '$2-$3' + '$1' + stylis.MOZ + (stylis.charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~stylis.indexof(value, 'stretch') ? prefix(stylis.replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (stylis.charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (stylis.charat(value, stylis.strlen(value) - 3 - (~stylis.indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return stylis.replace(value, ':', ':' + stylis.WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return stylis.replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + stylis.WEBKIT + (stylis.charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + stylis.WEBKIT + '$2$3' + '$1' + stylis.MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (stylis.charat(value, length + 11)) {
// vertical-l(r)
case 114:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return stylis.WEBKIT + value + stylis.MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case stylis.DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case stylis.KEYFRAMES:
return stylis.serialize([stylis.copy(element, {
value: stylis.replace(element.value, '@', '@' + stylis.WEBKIT)
})], callback);
case stylis.RULESET:
if (element.length) return stylis.combine(element.props, function (value) {
switch (stylis.match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(read-\w+)/, ':' + stylis.MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.WEBKIT + 'input-$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.MOZ + '$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, stylis.MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [prefixer];
var getSourceMap;
{
var sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
getSourceMap = function getSourceMap(styles) {
var matches = styles.match(sourceMapPattern);
if (!matches) return;
return matches[matches.length - 1];
};
}
var createCache = function createCache(options) {
var key = options.key;
if (!key) {
throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
}
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
{
if (/[^a-z-]/.test(key)) {
throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
}
}
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
omnipresentPlugins.push(createUnsafeSelectorsAlarm({
get compat() {
return cache.compat;
}
}), incorrectImportAlarm);
}
{
var currentSheet;
var finalizingPlugins = [stylis.stringify, function (element) {
if (!element.root) {
if (element["return"]) {
currentSheet.insert(element["return"]);
} else if (element.value && element.type !== stylis.COMMENT) {
// insert empty rule in non-production environments
// so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
currentSheet.insert(element.value + "{}");
}
}
} ];
var serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis$1 = function stylis$1(styles) {
return stylis.serialize(stylis.compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
currentSheet = {
insert: function insert(rule) {
sheet.insert(rule + sourceMap);
}
};
}
}
stylis$1(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new sheet.StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
exports["default"] = createCache;

View File

@@ -0,0 +1,2 @@
import "./emotion-cache.browser.development.cjs.js";
export { _default as default } from "./emotion-cache.browser.development.cjs.default.js";

View File

@@ -0,0 +1,596 @@
import { StyleSheet } from '@emotion/sheet';
import { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, middleware, stringify, COMMENT, compile } from 'stylis';
import '@emotion/weak-memoize';
import '@emotion/memoize';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [prefixer];
var getSourceMap;
{
var sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
getSourceMap = function getSourceMap(styles) {
var matches = styles.match(sourceMapPattern);
if (!matches) return;
return matches[matches.length - 1];
};
}
var createCache = function createCache(options) {
var key = options.key;
if (!key) {
throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
}
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
{
if (/[^a-z-]/.test(key)) {
throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
}
}
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
omnipresentPlugins.push(createUnsafeSelectorsAlarm({
get compat() {
return cache.compat;
}
}), incorrectImportAlarm);
}
{
var currentSheet;
var finalizingPlugins = [stringify, function (element) {
if (!element.root) {
if (element["return"]) {
currentSheet.insert(element["return"]);
} else if (element.value && element.type !== COMMENT) {
// insert empty rule in non-production environments
// so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
currentSheet.insert(element.value + "{}");
}
}
} ];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
currentSheet = {
insert: function insert(rule) {
sheet.insert(rule + sourceMap);
}
};
}
}
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
export { createCache as default };

View File

@@ -0,0 +1,438 @@
import { StyleSheet } from '@emotion/sheet';
import { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, stringify, rulesheet, middleware, compile } from 'stylis';
import '@emotion/weak-memoize';
import '@emotion/memoize';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
var currentSheet;
var finalizingPlugins = [stringify, rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
export { createCache as default };

View File

@@ -0,0 +1,3 @@
export * from "./declarations/src/index.js";
export { _default as default } from "./emotion-cache.cjs.default.js";
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW1vdGlvbi1jYWNoZS5janMuZC5tdHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuL2RlY2xhcmF0aW9ucy9zcmMvaW5kZXguZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSJ9

View File

@@ -0,0 +1,3 @@
export * from "./declarations/src/index";
export { default } from "./declarations/src/index";
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW1vdGlvbi1jYWNoZS5janMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4vZGVjbGFyYXRpb25zL3NyYy9pbmRleC5kLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0=

View File

@@ -0,0 +1 @@
export { default as _default } from "./declarations/src/index.js"

View File

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

View File

@@ -0,0 +1,503 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sheet = require('@emotion/sheet');
var stylis = require('stylis');
var weakMemoize = require('@emotion/weak-memoize');
var memoize = require('@emotion/memoize');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
var weakMemoize__default = /*#__PURE__*/_interopDefault(weakMemoize);
var memoize__default = /*#__PURE__*/_interopDefault(memoize);
var isBrowser = typeof document !== 'undefined';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = stylis.peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (stylis.token(character)) {
break;
}
stylis.next();
}
return stylis.slice(begin, stylis.position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (stylis.token(character)) {
case 0:
// &\f
if (character === 38 && stylis.peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(stylis.position - 1, points, index);
break;
case 2:
parsed[index] += stylis.delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = stylis.peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += stylis.from(character);
}
} while (character = stylis.next());
return parsed;
};
var getRules = function getRules(value, points) {
return stylis.dealloc(toRules(stylis.alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (stylis.hash(value, length)) {
// color-adjust
case 5103:
return stylis.WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return stylis.WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return stylis.WEBKIT + value + stylis.MOZ + value + stylis.MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return stylis.WEBKIT + value + stylis.MS + value + value;
// order
case 6165:
return stylis.WEBKIT + value + stylis.MS + 'flex-' + value + value;
// align-items
case 5187:
return stylis.WEBKIT + value + stylis.replace(value, /(\w+).+(:[^]+)/, stylis.WEBKIT + 'box-$1$2' + stylis.MS + 'flex-$1$2') + value;
// align-self
case 5443:
return stylis.WEBKIT + value + stylis.MS + 'flex-item-' + stylis.replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return stylis.WEBKIT + value + stylis.MS + 'flex-line-pack' + stylis.replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return stylis.WEBKIT + 'box-' + stylis.replace(value, '-grow', '') + stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return stylis.WEBKIT + stylis.replace(value, /([^-])(transform)/g, '$1' + stylis.WEBKIT + '$2') + value;
// cursor
case 6187:
return stylis.replace(stylis.replace(stylis.replace(value, /(zoom-|grab)/, stylis.WEBKIT + '$1'), /(image-set)/, stylis.WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return stylis.replace(value, /(image-set\([^]*)/, stylis.WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return stylis.replace(stylis.replace(value, /(.+:)(flex-)?(.*)/, stylis.WEBKIT + 'box-pack:$3' + stylis.MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + stylis.WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return stylis.replace(value, /(.+)-inline(.+)/, stylis.WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (stylis.strlen(value) - 1 - length > 6) switch (stylis.charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (stylis.charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return stylis.replace(value, /(.+:)(.+)-([^]+)/, '$1' + stylis.WEBKIT + '$2-$3' + '$1' + stylis.MOZ + (stylis.charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~stylis.indexof(value, 'stretch') ? prefix(stylis.replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (stylis.charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (stylis.charat(value, stylis.strlen(value) - 3 - (~stylis.indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return stylis.replace(value, ':', ':' + stylis.WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return stylis.replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + stylis.WEBKIT + (stylis.charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + stylis.WEBKIT + '$2$3' + '$1' + stylis.MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (stylis.charat(value, length + 11)) {
// vertical-l(r)
case 114:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return stylis.WEBKIT + value + stylis.MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case stylis.DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case stylis.KEYFRAMES:
return stylis.serialize([stylis.copy(element, {
value: stylis.replace(element.value, '@', '@' + stylis.WEBKIT)
})], callback);
case stylis.RULESET:
if (element.length) return stylis.combine(element.props, function (value) {
switch (stylis.match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(read-\w+)/, ':' + stylis.MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.WEBKIT + 'input-$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.MOZ + '$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, stylis.MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = isBrowser ? undefined : weakMemoize__default["default"](function () {
return memoize__default["default"](function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (isBrowser && key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
var nodesToHydrate = [];
if (isBrowser) {
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stylis.stringify, stylis.rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis$1 = function stylis$1(styles) {
return stylis.serialize(stylis.compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis$1(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stylis.stringify];
var _serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return stylis.serialize(stylis.compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new sheet.StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
exports["default"] = createCache;

View File

@@ -0,0 +1,2 @@
import "./emotion-cache.cjs.js";
export { _default as default } from "./emotion-cache.cjs.default.js";

View File

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

View File

@@ -0,0 +1,669 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sheet = require('@emotion/sheet');
var stylis = require('stylis');
var weakMemoize = require('@emotion/weak-memoize');
var memoize = require('@emotion/memoize');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
var weakMemoize__default = /*#__PURE__*/_interopDefault(weakMemoize);
var memoize__default = /*#__PURE__*/_interopDefault(memoize);
var isBrowser = typeof document !== 'undefined';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = stylis.peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (stylis.token(character)) {
break;
}
stylis.next();
}
return stylis.slice(begin, stylis.position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (stylis.token(character)) {
case 0:
// &\f
if (character === 38 && stylis.peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(stylis.position - 1, points, index);
break;
case 2:
parsed[index] += stylis.delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = stylis.peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += stylis.from(character);
}
} while (character = stylis.next());
return parsed;
};
var getRules = function getRules(value, points) {
return stylis.dealloc(toRules(stylis.alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (stylis.hash(value, length)) {
// color-adjust
case 5103:
return stylis.WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return stylis.WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return stylis.WEBKIT + value + stylis.MOZ + value + stylis.MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return stylis.WEBKIT + value + stylis.MS + value + value;
// order
case 6165:
return stylis.WEBKIT + value + stylis.MS + 'flex-' + value + value;
// align-items
case 5187:
return stylis.WEBKIT + value + stylis.replace(value, /(\w+).+(:[^]+)/, stylis.WEBKIT + 'box-$1$2' + stylis.MS + 'flex-$1$2') + value;
// align-self
case 5443:
return stylis.WEBKIT + value + stylis.MS + 'flex-item-' + stylis.replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return stylis.WEBKIT + value + stylis.MS + 'flex-line-pack' + stylis.replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return stylis.WEBKIT + 'box-' + stylis.replace(value, '-grow', '') + stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return stylis.WEBKIT + stylis.replace(value, /([^-])(transform)/g, '$1' + stylis.WEBKIT + '$2') + value;
// cursor
case 6187:
return stylis.replace(stylis.replace(stylis.replace(value, /(zoom-|grab)/, stylis.WEBKIT + '$1'), /(image-set)/, stylis.WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return stylis.replace(value, /(image-set\([^]*)/, stylis.WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return stylis.replace(stylis.replace(value, /(.+:)(flex-)?(.*)/, stylis.WEBKIT + 'box-pack:$3' + stylis.MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + stylis.WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return stylis.replace(value, /(.+)-inline(.+)/, stylis.WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (stylis.strlen(value) - 1 - length > 6) switch (stylis.charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (stylis.charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return stylis.replace(value, /(.+:)(.+)-([^]+)/, '$1' + stylis.WEBKIT + '$2-$3' + '$1' + stylis.MOZ + (stylis.charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~stylis.indexof(value, 'stretch') ? prefix(stylis.replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (stylis.charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (stylis.charat(value, stylis.strlen(value) - 3 - (~stylis.indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return stylis.replace(value, ':', ':' + stylis.WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return stylis.replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + stylis.WEBKIT + (stylis.charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + stylis.WEBKIT + '$2$3' + '$1' + stylis.MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (stylis.charat(value, length + 11)) {
// vertical-l(r)
case 114:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return stylis.WEBKIT + value + stylis.MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case stylis.DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case stylis.KEYFRAMES:
return stylis.serialize([stylis.copy(element, {
value: stylis.replace(element.value, '@', '@' + stylis.WEBKIT)
})], callback);
case stylis.RULESET:
if (element.length) return stylis.combine(element.props, function (value) {
switch (stylis.match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(read-\w+)/, ':' + stylis.MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.WEBKIT + 'input-$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.MOZ + '$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, stylis.MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = isBrowser ? undefined : weakMemoize__default["default"](function () {
return memoize__default["default"](function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var getSourceMap;
{
var sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
getSourceMap = function getSourceMap(styles) {
var matches = styles.match(sourceMapPattern);
if (!matches) return;
return matches[matches.length - 1];
};
}
var createCache = function createCache(options) {
var key = options.key;
if (!key) {
throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
}
if (isBrowser && key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
{
if (/[^a-z-]/.test(key)) {
throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
}
}
var inserted = {};
var container;
var nodesToHydrate = [];
if (isBrowser) {
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
omnipresentPlugins.push(createUnsafeSelectorsAlarm({
get compat() {
return cache.compat;
}
}), incorrectImportAlarm);
}
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stylis.stringify, function (element) {
if (!element.root) {
if (element["return"]) {
currentSheet.insert(element["return"]);
} else if (element.value && element.type !== stylis.COMMENT) {
// insert empty rule in non-production environments
// so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
currentSheet.insert(element.value + "{}");
}
}
} ];
var serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis$1 = function stylis$1(styles) {
return stylis.serialize(stylis.compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
currentSheet = {
insert: function insert(rule) {
sheet.insert(rule + sourceMap);
}
};
}
}
stylis$1(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stylis.stringify];
var _serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return stylis.serialize(stylis.compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
return rules + sourceMap;
}
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new sheet.StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
exports["default"] = createCache;

View File

@@ -0,0 +1,2 @@
import "./emotion-cache.development.cjs.js";
export { _default as default } from "./emotion-cache.development.cjs.default.js";

View File

@@ -0,0 +1 @@
exports._default = require("./emotion-cache.development.edge-light.cjs.js").default;

View File

@@ -0,0 +1,628 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sheet = require('@emotion/sheet');
var stylis = require('stylis');
var weakMemoize = require('@emotion/weak-memoize');
var memoize = require('@emotion/memoize');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
var weakMemoize__default = /*#__PURE__*/_interopDefault(weakMemoize);
var memoize__default = /*#__PURE__*/_interopDefault(memoize);
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = stylis.peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (stylis.token(character)) {
break;
}
stylis.next();
}
return stylis.slice(begin, stylis.position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (stylis.token(character)) {
case 0:
// &\f
if (character === 38 && stylis.peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(stylis.position - 1, points, index);
break;
case 2:
parsed[index] += stylis.delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = stylis.peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += stylis.from(character);
}
} while (character = stylis.next());
return parsed;
};
var getRules = function getRules(value, points) {
return stylis.dealloc(toRules(stylis.alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (stylis.hash(value, length)) {
// color-adjust
case 5103:
return stylis.WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return stylis.WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return stylis.WEBKIT + value + stylis.MOZ + value + stylis.MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return stylis.WEBKIT + value + stylis.MS + value + value;
// order
case 6165:
return stylis.WEBKIT + value + stylis.MS + 'flex-' + value + value;
// align-items
case 5187:
return stylis.WEBKIT + value + stylis.replace(value, /(\w+).+(:[^]+)/, stylis.WEBKIT + 'box-$1$2' + stylis.MS + 'flex-$1$2') + value;
// align-self
case 5443:
return stylis.WEBKIT + value + stylis.MS + 'flex-item-' + stylis.replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return stylis.WEBKIT + value + stylis.MS + 'flex-line-pack' + stylis.replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return stylis.WEBKIT + 'box-' + stylis.replace(value, '-grow', '') + stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return stylis.WEBKIT + stylis.replace(value, /([^-])(transform)/g, '$1' + stylis.WEBKIT + '$2') + value;
// cursor
case 6187:
return stylis.replace(stylis.replace(stylis.replace(value, /(zoom-|grab)/, stylis.WEBKIT + '$1'), /(image-set)/, stylis.WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return stylis.replace(value, /(image-set\([^]*)/, stylis.WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return stylis.replace(stylis.replace(value, /(.+:)(flex-)?(.*)/, stylis.WEBKIT + 'box-pack:$3' + stylis.MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + stylis.WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return stylis.replace(value, /(.+)-inline(.+)/, stylis.WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (stylis.strlen(value) - 1 - length > 6) switch (stylis.charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (stylis.charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return stylis.replace(value, /(.+:)(.+)-([^]+)/, '$1' + stylis.WEBKIT + '$2-$3' + '$1' + stylis.MOZ + (stylis.charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~stylis.indexof(value, 'stretch') ? prefix(stylis.replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (stylis.charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (stylis.charat(value, stylis.strlen(value) - 3 - (~stylis.indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return stylis.replace(value, ':', ':' + stylis.WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return stylis.replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + stylis.WEBKIT + (stylis.charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + stylis.WEBKIT + '$2$3' + '$1' + stylis.MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (stylis.charat(value, length + 11)) {
// vertical-l(r)
case 114:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return stylis.WEBKIT + value + stylis.MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case stylis.DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case stylis.KEYFRAMES:
return stylis.serialize([stylis.copy(element, {
value: stylis.replace(element.value, '@', '@' + stylis.WEBKIT)
})], callback);
case stylis.RULESET:
if (element.length) return stylis.combine(element.props, function (value) {
switch (stylis.match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(read-\w+)/, ':' + stylis.MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.WEBKIT + 'input-$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.MOZ + '$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, stylis.MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = weakMemoize__default["default"](function () {
return memoize__default["default"](function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var getSourceMap;
{
var sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
getSourceMap = function getSourceMap(styles) {
var matches = styles.match(sourceMapPattern);
if (!matches) return;
return matches[matches.length - 1];
};
}
var createCache = function createCache(options) {
var key = options.key;
if (!key) {
throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
{
if (/[^a-z-]/.test(key)) {
throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
}
}
var inserted = {};
var container;
var nodesToHydrate = [];
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
omnipresentPlugins.push(createUnsafeSelectorsAlarm({
get compat() {
return cache.compat;
}
}), incorrectImportAlarm);
}
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stylis.stringify, function (element) {
if (!element.root) {
if (element["return"]) {
currentSheet.insert(element["return"]);
} else if (element.value && element.type !== stylis.COMMENT) {
// insert empty rule in non-production environments
// so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
currentSheet.insert(element.value + "{}");
}
}
} ];
var serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis$1 = function stylis$1(styles) {
return stylis.serialize(stylis.compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
currentSheet = {
insert: function insert(rule) {
sheet.insert(rule + sourceMap);
}
};
}
}
stylis$1(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stylis.stringify];
var _serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return stylis.serialize(stylis.compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
return rules + sourceMap;
}
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new sheet.StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
exports["default"] = createCache;

View File

@@ -0,0 +1,2 @@
import "./emotion-cache.development.edge-light.cjs.js";
export { _default as default } from "./emotion-cache.development.edge-light.cjs.default.js";

View File

@@ -0,0 +1,619 @@
import { StyleSheet } from '@emotion/sheet';
import { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, middleware, stringify, COMMENT, compile } from 'stylis';
import weakMemoize from '@emotion/weak-memoize';
import memoize from '@emotion/memoize';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = weakMemoize(function () {
return memoize(function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var getSourceMap;
{
var sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
getSourceMap = function getSourceMap(styles) {
var matches = styles.match(sourceMapPattern);
if (!matches) return;
return matches[matches.length - 1];
};
}
var createCache = function createCache(options) {
var key = options.key;
if (!key) {
throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
{
if (/[^a-z-]/.test(key)) {
throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
}
}
var inserted = {};
var container;
var nodesToHydrate = [];
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
omnipresentPlugins.push(createUnsafeSelectorsAlarm({
get compat() {
return cache.compat;
}
}), incorrectImportAlarm);
}
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stringify, function (element) {
if (!element.root) {
if (element["return"]) {
currentSheet.insert(element["return"]);
} else if (element.value && element.type !== COMMENT) {
// insert empty rule in non-production environments
// so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
currentSheet.insert(element.value + "{}");
}
}
} ];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
currentSheet = {
insert: function insert(rule) {
sheet.insert(rule + sourceMap);
}
};
}
}
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stringify];
var _serializer = middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return serialize(compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
return rules + sourceMap;
}
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
export { createCache as default };

View File

@@ -0,0 +1,660 @@
import { StyleSheet } from '@emotion/sheet';
import { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, middleware, stringify, COMMENT, compile } from 'stylis';
import weakMemoize from '@emotion/weak-memoize';
import memoize from '@emotion/memoize';
var isBrowser = typeof document !== 'undefined';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = isBrowser ? undefined : weakMemoize(function () {
return memoize(function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var getSourceMap;
{
var sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
getSourceMap = function getSourceMap(styles) {
var matches = styles.match(sourceMapPattern);
if (!matches) return;
return matches[matches.length - 1];
};
}
var createCache = function createCache(options) {
var key = options.key;
if (!key) {
throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
}
if (isBrowser && key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
{
if (/[^a-z-]/.test(key)) {
throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
}
}
var inserted = {};
var container;
var nodesToHydrate = [];
if (isBrowser) {
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
{
omnipresentPlugins.push(createUnsafeSelectorsAlarm({
get compat() {
return cache.compat;
}
}), incorrectImportAlarm);
}
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stringify, function (element) {
if (!element.root) {
if (element["return"]) {
currentSheet.insert(element["return"]);
} else if (element.value && element.type !== COMMENT) {
// insert empty rule in non-production environments
// so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
currentSheet.insert(element.value + "{}");
}
}
} ];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
currentSheet = {
insert: function insert(rule) {
sheet.insert(rule + sourceMap);
}
};
}
}
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stringify];
var _serializer = middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return serialize(compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
if (getSourceMap) {
var sourceMap = getSourceMap(serialized.styles);
if (sourceMap) {
return rules + sourceMap;
}
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
export { createCache as default };

View File

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

View File

@@ -0,0 +1,462 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sheet = require('@emotion/sheet');
var stylis = require('stylis');
var weakMemoize = require('@emotion/weak-memoize');
var memoize = require('@emotion/memoize');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
var weakMemoize__default = /*#__PURE__*/_interopDefault(weakMemoize);
var memoize__default = /*#__PURE__*/_interopDefault(memoize);
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = stylis.peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (stylis.token(character)) {
break;
}
stylis.next();
}
return stylis.slice(begin, stylis.position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (stylis.token(character)) {
case 0:
// &\f
if (character === 38 && stylis.peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(stylis.position - 1, points, index);
break;
case 2:
parsed[index] += stylis.delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = stylis.peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += stylis.from(character);
}
} while (character = stylis.next());
return parsed;
};
var getRules = function getRules(value, points) {
return stylis.dealloc(toRules(stylis.alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (stylis.hash(value, length)) {
// color-adjust
case 5103:
return stylis.WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return stylis.WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return stylis.WEBKIT + value + stylis.MOZ + value + stylis.MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return stylis.WEBKIT + value + stylis.MS + value + value;
// order
case 6165:
return stylis.WEBKIT + value + stylis.MS + 'flex-' + value + value;
// align-items
case 5187:
return stylis.WEBKIT + value + stylis.replace(value, /(\w+).+(:[^]+)/, stylis.WEBKIT + 'box-$1$2' + stylis.MS + 'flex-$1$2') + value;
// align-self
case 5443:
return stylis.WEBKIT + value + stylis.MS + 'flex-item-' + stylis.replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return stylis.WEBKIT + value + stylis.MS + 'flex-line-pack' + stylis.replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return stylis.WEBKIT + 'box-' + stylis.replace(value, '-grow', '') + stylis.WEBKIT + value + stylis.MS + stylis.replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return stylis.WEBKIT + stylis.replace(value, /([^-])(transform)/g, '$1' + stylis.WEBKIT + '$2') + value;
// cursor
case 6187:
return stylis.replace(stylis.replace(stylis.replace(value, /(zoom-|grab)/, stylis.WEBKIT + '$1'), /(image-set)/, stylis.WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return stylis.replace(value, /(image-set\([^]*)/, stylis.WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return stylis.replace(stylis.replace(value, /(.+:)(flex-)?(.*)/, stylis.WEBKIT + 'box-pack:$3' + stylis.MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + stylis.WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return stylis.replace(value, /(.+)-inline(.+)/, stylis.WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (stylis.strlen(value) - 1 - length > 6) switch (stylis.charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (stylis.charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return stylis.replace(value, /(.+:)(.+)-([^]+)/, '$1' + stylis.WEBKIT + '$2-$3' + '$1' + stylis.MOZ + (stylis.charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~stylis.indexof(value, 'stretch') ? prefix(stylis.replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (stylis.charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (stylis.charat(value, stylis.strlen(value) - 3 - (~stylis.indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return stylis.replace(value, ':', ':' + stylis.WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return stylis.replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + stylis.WEBKIT + (stylis.charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + stylis.WEBKIT + '$2$3' + '$1' + stylis.MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (stylis.charat(value, length + 11)) {
// vertical-l(r)
case 114:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return stylis.WEBKIT + value + stylis.MS + stylis.replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return stylis.WEBKIT + value + stylis.MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case stylis.DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case stylis.KEYFRAMES:
return stylis.serialize([stylis.copy(element, {
value: stylis.replace(element.value, '@', '@' + stylis.WEBKIT)
})], callback);
case stylis.RULESET:
if (element.length) return stylis.combine(element.props, function (value) {
switch (stylis.match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(read-\w+)/, ':' + stylis.MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return stylis.serialize([stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.WEBKIT + 'input-$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, ':' + stylis.MOZ + '$1')]
}), stylis.copy(element, {
props: [stylis.replace(value, /:(plac\w+)/, stylis.MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = weakMemoize__default["default"](function () {
return memoize__default["default"](function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
var nodesToHydrate = [];
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stylis.stringify, stylis.rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis$1 = function stylis$1(styles) {
return stylis.serialize(stylis.compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis$1(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stylis.stringify];
var _serializer = stylis.middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return stylis.serialize(stylis.compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new sheet.StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
exports["default"] = createCache;

View File

@@ -0,0 +1,2 @@
import "./emotion-cache.edge-light.cjs.js";
export { _default as default } from "./emotion-cache.edge-light.cjs.default.js";

View File

@@ -0,0 +1,453 @@
import { StyleSheet } from '@emotion/sheet';
import { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, stringify, rulesheet, middleware, compile } from 'stylis';
import weakMemoize from '@emotion/weak-memoize';
import memoize from '@emotion/memoize';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = weakMemoize(function () {
return memoize(function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
var nodesToHydrate = [];
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stringify, rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stringify];
var _serializer = middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return serialize(compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
export { createCache as default };

View File

@@ -0,0 +1,494 @@
import { StyleSheet } from '@emotion/sheet';
import { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, stringify, rulesheet, middleware, compile } from 'stylis';
import weakMemoize from '@emotion/weak-memoize';
import memoize from '@emotion/memoize';
var isBrowser = typeof document !== 'undefined';
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var getServerStylisCache = isBrowser ? undefined : weakMemoize(function () {
return memoize(function () {
return {};
});
});
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (isBrowser && key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
var nodesToHydrate = [];
if (isBrowser) {
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (!getServerStylisCache) {
var currentSheet;
var finalizingPlugins = [stringify, rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
} else {
var _finalizingPlugins = [stringify];
var _serializer = middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
var _stylis = function _stylis(styles) {
return serialize(compile(styles), _serializer);
};
var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
if (cache.compat === undefined) {
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
return rules;
} else {
// in compat mode, we put the styles on the inserted cache so
// that emotion-server can pull out the styles
// except when we don't want to cache it which was in Global but now
// is nowhere but we don't want to do a major right now
// and just in case we're going to leave the case here
// it's also not affecting client side bundle size
// so it's really not a big deal
if (shouldCache) {
cache.inserted[name] = rules;
} else {
return rules;
}
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
export { createCache as default };

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.

View File

@@ -0,0 +1 @@
export default function memoize<V>(fn: (arg: string) => V): (arg: string) => V;

View File

@@ -0,0 +1,3 @@
export * from "./declarations/src/index.js";
export { _default as default } from "./emotion-memoize.cjs.default.js";
//# sourceMappingURL=emotion-memoize.cjs.d.mts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"emotion-memoize.cjs.d.mts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}

View File

@@ -0,0 +1,3 @@
export * from "./declarations/src/index";
export { default } from "./declarations/src/index";
//# sourceMappingURL=emotion-memoize.cjs.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"emotion-memoize.cjs.d.ts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}

View File

@@ -0,0 +1 @@
export { default as _default } from "./declarations/src/index.js"

Some files were not shown because too many files have changed in this diff Show More