draft: refactor project so it sits on top of a standalone app

This commit is contained in:
2020-05-11 15:34:47 +02:00
parent a9ee5acc1c
commit f97e8455fc
13068 changed files with 1735502 additions and 866 deletions
+38
View File
@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class CssSyntaxError extends Error {
constructor(error) {
super(error);
const {
reason,
line,
column
} = error;
this.name = 'CssSyntaxError'; // Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
// We don't need `plugin` and `file` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== 'undefined') {
this.message += `(${line}:${column}) `;
}
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
} // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
exports.default = CssSyntaxError;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class Warning extends Error {
constructor(warning) {
super(warning);
const {
text,
line,
column
} = warning;
this.name = 'Warning'; // Based on https://github.com/postcss/postcss/blob/master/lib/warning.es6#L74
// We don't need `plugin` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== 'undefined') {
this.message += `(${line}:${column}) `;
}
this.message += `${text}`; // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
exports.default = Warning;
+5
View File
@@ -0,0 +1,5 @@
"use strict";
const loader = require('./index');
module.exports = loader.default;
+117
View File
@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loader;
var _schemaUtils = _interopRequireDefault(require("schema-utils"));
var _postcss = _interopRequireDefault(require("postcss"));
var _package = _interopRequireDefault(require("postcss/package.json"));
var _loaderUtils = require("loader-utils");
var _options = _interopRequireDefault(require("./options.json"));
var _plugins = require("./plugins");
var _utils = require("./utils");
var _Warning = _interopRequireDefault(require("./Warning"));
var _CssSyntaxError = _interopRequireDefault(require("./CssSyntaxError"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function loader(content, map, meta) {
const options = (0, _loaderUtils.getOptions)(this) || {};
(0, _schemaUtils.default)(_options.default, options, {
name: 'CSS Loader',
baseDataPath: 'options'
});
const callback = this.async();
const sourceMap = options.sourceMap || false;
const plugins = [];
if (options.modules) {
plugins.push(...(0, _utils.getModulesPlugins)(options, this));
}
const exportType = options.onlyLocals ? 'locals' : 'full';
plugins.push((0, _plugins.icssParser)());
if (options.import !== false && exportType === 'full') {
plugins.push((0, _plugins.importParser)({
filter: (0, _utils.getFilter)(options.import, this.resourcePath)
}));
}
if (options.url !== false && exportType === 'full') {
plugins.push((0, _plugins.urlParser)({
filter: (0, _utils.getFilter)(options.url, this.resourcePath, value => (0, _loaderUtils.isUrlRequest)(value))
}));
} // Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
if (meta) {
const {
ast
} = meta;
if (ast && ast.type === 'postcss' && ast.version === _package.default.version) {
// eslint-disable-next-line no-param-reassign
content = ast.root;
}
}
(0, _postcss.default)(plugins).process(content, {
from: this.remainingRequest.split('!').pop(),
to: this.currentRequest.split('!').pop(),
map: options.sourceMap ? {
// Some loaders (example `"postcss-loader": "1.x.x"`) always generates source map, we should remove it
prev: sourceMap && map ? (0, _utils.normalizeSourceMap)(map) : null,
inline: false,
annotation: false
} : false
}).then(result => {
result.warnings().forEach(warning => this.emitWarning(new _Warning.default(warning)));
const imports = [];
const exports = [];
const replacers = [];
for (const message of result.messages) {
// eslint-disable-next-line default-case
switch (message.type) {
case 'import':
imports.push(message.value);
break;
case 'export':
exports.push(message.value);
break;
case 'replacer':
replacers.push(message.value);
break;
}
}
const {
importLoaders,
localsConvention
} = options;
const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false;
const importCode = (0, _utils.getImportCode)(this, imports, exportType, sourceMap, importLoaders, esModule);
const moduleCode = (0, _utils.getModuleCode)(this, result, exportType, sourceMap, replacers);
const exportCode = (0, _utils.getExportCode)(this, exports, exportType, replacers, localsConvention, esModule);
return callback(null, [importCode, moduleCode, exportCode].join(''));
}).catch(error => {
callback(error.name === 'CssSyntaxError' ? new _CssSyntaxError.default(error) : error);
});
}
+104
View File
@@ -0,0 +1,104 @@
{
"additionalProperties": false,
"properties": {
"url": {
"description": "Enables/Disables 'url'/'image-set' functions handling (https://github.com/webpack-contrib/css-loader#url).",
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
]
},
"import": {
"description": "Enables/Disables '@import' at-rules handling (https://github.com/webpack-contrib/css-loader#import).",
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
]
},
"modules": {
"description": "Enables/Disables CSS Modules and their configuration (https://github.com/webpack-contrib/css-loader#modules).",
"anyOf": [
{
"type": "boolean"
},
{
"enum": ["local", "global", "pure"]
},
{
"type": "object",
"additionalProperties": false,
"properties": {
"mode": {
"enum": ["local", "global", "pure"]
},
"localIdentName": {
"type": "string"
},
"localIdentRegExp": {
"anyOf": [
{
"type": "string"
},
{
"instanceof": "RegExp"
}
]
},
"context": {
"type": "string"
},
"hashPrefix": {
"type": "string"
},
"getLocalIdent": {
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
]
}
}
}
]
},
"sourceMap": {
"description": "Enables/Disables generation of source maps (https://github.com/webpack-contrib/css-loader#sourcemap).",
"type": "boolean"
},
"importLoaders": {
"description": "Enables/Disables or setups number of loaders applied before CSS loader (https://github.com/webpack-contrib/css-loader#importloaders).",
"anyOf": [
{
"type": "boolean"
},
{
"type": "number"
}
]
},
"localsConvention": {
"description": "Style of exported classnames (https://github.com/webpack-contrib/css-loader#localsconvention).",
"enum": ["asIs", "camelCase", "camelCaseOnly", "dashes", "dashesOnly"]
},
"onlyLocals": {
"description": "Export only locals (https://github.com/webpack-contrib/css-loader#onlylocals).",
"type": "boolean"
},
"esModule": {
"description": "Use the ES modules syntax (https://github.com/webpack-contrib/css-loader#esmodule).",
"type": "boolean"
}
},
"type": "object"
}
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "importParser", {
enumerable: true,
get: function () {
return _postcssImportParser.default;
}
});
Object.defineProperty(exports, "icssParser", {
enumerable: true,
get: function () {
return _postcssIcssParser.default;
}
});
Object.defineProperty(exports, "urlParser", {
enumerable: true,
get: function () {
return _postcssUrlParser.default;
}
});
var _postcssImportParser = _interopRequireDefault(require("./postcss-import-parser"));
var _postcssIcssParser = _interopRequireDefault(require("./postcss-icss-parser"));
var _postcssUrlParser = _interopRequireDefault(require("./postcss-url-parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _icssUtils = require("icss-utils");
var _loaderUtils = require("loader-utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-icss-parser';
function normalizeIcssImports(icssImports) {
return Object.keys(icssImports).reduce((accumulator, url) => {
const tokensMap = icssImports[url];
const tokens = Object.keys(tokensMap);
if (tokens.length === 0) {
return accumulator;
}
const normalizedUrl = (0, _loaderUtils.urlToRequest)(url);
if (!accumulator[normalizedUrl]) {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = tokensMap;
} else {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = { ...accumulator[normalizedUrl],
...tokensMap
};
}
return accumulator;
}, {});
}
var _default = _postcss.default.plugin(pluginName, () => function process(css, result) {
const importReplacements = Object.create(null);
const {
icssImports,
icssExports
} = (0, _icssUtils.extractICSS)(css);
const normalizedIcssImports = normalizeIcssImports(icssImports);
Object.keys(normalizedIcssImports).forEach((url, importIndex) => {
const importName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}___`;
result.messages.push({
pluginName,
type: 'import',
value: {
type: 'icss-import',
importName,
url
}
});
const tokenMap = normalizedIcssImports[url];
const tokens = Object.keys(tokenMap);
tokens.forEach((token, replacementIndex) => {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}_REPLACEMENT_${replacementIndex}___`;
const localName = tokenMap[token];
importReplacements[token] = replacementName;
result.messages.push({
pluginName,
type: 'replacer',
value: {
type: 'icss-import',
importName,
replacementName,
localName
}
});
});
});
if (Object.keys(importReplacements).length > 0) {
(0, _icssUtils.replaceSymbols)(css, importReplacements);
}
Object.keys(icssExports).forEach(name => {
const value = (0, _icssUtils.replaceValueSymbols)(icssExports[name], importReplacements);
result.messages.push({
pluginName,
type: 'export',
value: {
name,
value
}
});
});
});
exports.default = _default;
@@ -0,0 +1,133 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _loaderUtils = require("loader-utils");
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-import-parser';
function getParsedValue(node) {
if (node.type === 'function' && node.value.toLowerCase() === 'url') {
const {
nodes
} = node;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
return {
url,
isStringValue
};
}
if (node.type === 'string') {
const url = node.value;
return {
url,
isStringValue: true
};
}
return null;
}
function parseImport(params) {
const {
nodes
} = (0, _postcssValueParser.default)(params);
if (nodes.length === 0) {
return null;
}
const value = getParsedValue(nodes[0]);
if (!value) {
return null;
}
let {
url
} = value;
if (url.trim().length === 0) {
return null;
}
if ((0, _loaderUtils.isUrlRequest)(url)) {
const {
isStringValue
} = value;
url = (0, _utils.normalizeUrl)(url, isStringValue);
}
return {
url,
media: _postcssValueParser.default.stringify(nodes.slice(1)).trim().toLowerCase()
};
}
function walkAtRules(css, result, filter) {
const items = [];
css.walkAtRules(/^import$/i, atRule => {
// Convert only top-level @import
if (atRule.parent.type !== 'root') {
return;
}
if (atRule.nodes) {
result.warn("It looks like you didn't end your @import statement correctly. " + 'Child nodes are attached to it.', {
node: atRule
});
return;
}
const parsed = parseImport(atRule.params);
if (!parsed) {
// eslint-disable-next-line consistent-return
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
node: atRule
});
}
if (filter && !filter(parsed)) {
return;
}
atRule.remove();
items.push(parsed);
});
return items;
}
var _default = _postcss.default.plugin(pluginName, options => function process(css, result) {
const items = walkAtRules(css, result, options.filter);
items.forEach(item => {
const {
url,
media
} = item;
result.messages.push({
pluginName,
type: 'import',
value: {
type: '@import',
url,
media
}
});
});
});
exports.default = _default;
+207
View File
@@ -0,0 +1,207 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-url-parser';
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDecl = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function walkUrls(parsed, callback) {
parsed.walk(node => {
if (node.type !== 'function') {
return;
}
if (isUrlFunc.test(node.value)) {
const {
nodes
} = node;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
callback(getNodeFromUrlFunc(node), url, false, isStringValue); // Do not traverse inside `url`
// eslint-disable-next-line consistent-return
return false;
}
if (isImageSetFunc.test(node.value)) {
node.nodes.forEach(nNode => {
const {
type,
value
} = nNode;
if (type === 'function' && isUrlFunc.test(value)) {
const {
nodes
} = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
callback(getNodeFromUrlFunc(nNode), url, false, isStringValue);
}
if (type === 'string') {
callback(nNode, value, true, true);
}
}); // Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
}
function getUrlsFromValue(value, result, filter, decl) {
if (!needParseDecl.test(value)) {
return;
}
const parsed = (0, _postcssValueParser.default)(value);
const urls = [];
walkUrls(parsed, (node, url, needQuotes, isStringValue) => {
if (url.trim().replace(/\\[\r\n]/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl ? decl.toString() : value}'`, {
node: decl
});
return;
}
if (filter && !filter(url)) {
return;
}
const splittedUrl = url.split(/(\?)?#/);
const [urlWithoutHash, singleQuery, hashValue] = splittedUrl;
const hash = singleQuery || hashValue ? `${singleQuery ? '?' : ''}${hashValue ? `#${hashValue}` : ''}` : '';
const normalizedUrl = (0, _utils.normalizeUrl)(urlWithoutHash, isStringValue);
urls.push({
node,
url: normalizedUrl,
hash,
needQuotes
});
}); // eslint-disable-next-line consistent-return
return {
parsed,
urls
};
}
function walkDecls(css, result, filter) {
const items = [];
css.walkDecls(decl => {
const item = getUrlsFromValue(decl.value, result, filter, decl);
if (!item || item.urls.length === 0) {
return;
}
items.push({
decl,
parsed: item.parsed,
urls: item.urls
});
});
return items;
}
function flatten(array) {
return array.reduce((a, b) => a.concat(b), []);
}
function collectUniqueUrlsWithNodes(array) {
return array.reduce((accumulator, currentValue) => {
const {
url,
needQuotes,
hash,
node
} = currentValue;
const found = accumulator.find(item => url === item.url && needQuotes === item.needQuotes && hash === item.hash);
if (!found) {
accumulator.push({
url,
hash,
needQuotes,
nodes: [node]
});
} else {
found.nodes.push(node);
}
return accumulator;
}, []);
}
var _default = _postcss.default.plugin(pluginName, options => function process(css, result) {
const traversed = walkDecls(css, result, options.filter);
const flattenTraversed = flatten(traversed.map(item => item.urls));
const urlsWithNodes = collectUniqueUrlsWithNodes(flattenTraversed);
const replacers = new Map();
urlsWithNodes.forEach((urlWithNodes, index) => {
const {
url,
hash,
needQuotes,
nodes
} = urlWithNodes;
const replacementName = `___CSS_LOADER_URL_REPLACEMENT_${index}___`;
result.messages.push({
pluginName,
type: 'import',
value: {
type: 'url',
replacementName,
url,
needQuotes,
hash
}
}, {
pluginName,
type: 'replacer',
value: {
type: 'url',
replacementName
}
});
nodes.forEach(node => {
replacers.set(node, replacementName);
});
});
traversed.forEach(item => {
walkUrls(item.parsed, node => {
const replacementName = replacers.get(node);
if (!replacementName) {
return;
} // eslint-disable-next-line no-param-reassign
node.type = 'word'; // eslint-disable-next-line no-param-reassign
node.value = replacementName;
}); // eslint-disable-next-line no-param-reassign
item.decl.value = item.parsed.toString();
});
});
exports.default = _default;
+94
View File
@@ -0,0 +1,94 @@
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join('');
}; // import a list of modules into the list
// eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) {
if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
if (dedupe) {
for (var i = 0; i < this.length; i++) {
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
+34
View File
@@ -0,0 +1,34 @@
"use strict";
module.exports = function (url, options) {
if (!options) {
// eslint-disable-next-line no-param-reassign
options = {};
} // eslint-disable-next-line no-underscore-dangle, no-param-reassign
url = url && url.__esModule ? url.default : url;
if (typeof url !== 'string') {
return url;
} // If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
// eslint-disable-next-line no-param-reassign
url = url.slice(1, -1);
}
if (options.hash) {
// eslint-disable-next-line no-param-reassign
url += options.hash;
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || options.needQuotes) {
return "\"".concat(url.replace(/"/g, '\\"').replace(/\n/g, '\\n'), "\"");
}
return url;
};
+397
View File
@@ -0,0 +1,397 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.normalizeUrl = normalizeUrl;
exports.getFilter = getFilter;
exports.getModulesPlugins = getModulesPlugins;
exports.normalizeSourceMap = normalizeSourceMap;
exports.getImportCode = getImportCode;
exports.getModuleCode = getModuleCode;
exports.getExportCode = getExportCode;
var _path = _interopRequireDefault(require("path"));
var _loaderUtils = _interopRequireWildcard(require("loader-utils"));
var _normalizePath = _interopRequireDefault(require("normalize-path"));
var _cssesc = _interopRequireDefault(require("cssesc"));
var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
var _postcssModulesLocalByDefault = _interopRequireDefault(require("postcss-modules-local-by-default"));
var _postcssModulesExtractImports = _interopRequireDefault(require("postcss-modules-extract-imports"));
var _postcssModulesScope = _interopRequireDefault(require("postcss-modules-scope"));
var _camelcase = _interopRequireDefault(require("camelcase"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
const whitespace = '[\\x20\\t\\r\\n\\f]';
const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, 'ig');
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
const high = `0x${escaped}` - 0x10000;
/* eslint-disable line-comment-position */
// NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
// eslint-disable-next-line no-self-compare
return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint
String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair)
// eslint-disable-next-line no-bitwise
String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
/* eslint-enable line-comment-position */
});
} // eslint-disable-next-line no-control-regex
const filenameReservedRegex = /[<>:"/\\|?*\x00-\x1F]/g; // eslint-disable-next-line no-control-regex
const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g;
const reRelativePath = /^\.+/;
function getLocalIdent(loaderContext, localIdentName, localName, options) {
if (!options.context) {
// eslint-disable-next-line no-param-reassign
options.context = loaderContext.rootContext;
}
const request = (0, _normalizePath.default)(_path.default.relative(options.context || '', loaderContext.resourcePath)); // eslint-disable-next-line no-param-reassign
options.content = `${options.hashPrefix + request}+${unescape(localName)}`; // Using `[path]` placeholder outputs `/` we need escape their
// Also directories can contains invalid characters for css we need escape their too
return (0, _cssesc.default)(_loaderUtils.default.interpolateName(loaderContext, localIdentName, options) // For `[hash]` placeholder
.replace(/^((-?[0-9])|--)/, '_$1').replace(filenameReservedRegex, '-').replace(reControlChars, '-').replace(reRelativePath, '-').replace(/\./g, '-'), {
isIdentifier: true
}).replace(/\\\[local\\\]/gi, localName);
}
function normalizeUrl(url, isStringValue) {
let normalizedUrl = url;
if (isStringValue && /\\[\n]/.test(normalizedUrl)) {
normalizedUrl = normalizedUrl.replace(/\\[\n]/g, '');
}
return (0, _loaderUtils.urlToRequest)(decodeURIComponent(unescape(normalizedUrl)));
}
function getFilter(filter, resourcePath, defaultFilter = null) {
return item => {
if (defaultFilter && !defaultFilter(item)) {
return false;
}
if (typeof filter === 'function') {
return filter(item, resourcePath);
}
return true;
};
}
function getModulesPlugins(options, loaderContext) {
let modulesOptions = {
mode: 'local',
localIdentName: '[hash:base64]',
getLocalIdent,
hashPrefix: '',
localIdentRegExp: null
};
if (typeof options.modules === 'boolean' || typeof options.modules === 'string') {
modulesOptions.mode = typeof options.modules === 'string' ? options.modules : 'local';
} else {
modulesOptions = Object.assign({}, modulesOptions, options.modules);
}
return [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
mode: modulesOptions.mode
}), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
generateScopedName: function generateScopedName(exportName) {
let localIdent = modulesOptions.getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
context: modulesOptions.context,
hashPrefix: modulesOptions.hashPrefix,
regExp: modulesOptions.localIdentRegExp
});
if (!localIdent) {
localIdent = getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
context: modulesOptions.context,
hashPrefix: modulesOptions.hashPrefix,
regExp: modulesOptions.localIdentRegExp
});
}
return localIdent;
}
})];
}
function normalizeSourceMap(map) {
let newMap = map; // Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === 'string') {
newMap = JSON.parse(newMap);
} // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
if (newMap.file) {
newMap.file = (0, _normalizePath.default)(newMap.file);
}
if (newMap.sourceRoot) {
newMap.sourceRoot = (0, _normalizePath.default)(newMap.sourceRoot);
}
if (newMap.sources) {
newMap.sources = newMap.sources.map(source => (0, _normalizePath.default)(source));
}
return newMap;
}
function getImportPrefix(loaderContext, importLoaders) {
if (importLoaders === false) {
return '';
}
const numberImportedLoaders = parseInt(importLoaders, 10) || 0;
const loadersRequest = loaderContext.loaders.slice(loaderContext.loaderIndex, loaderContext.loaderIndex + 1 + numberImportedLoaders).map(x => x.request).join('!');
return `-!${loadersRequest}!`;
}
function getImportCode(loaderContext, imports, exportType, sourceMap, importLoaders, esModule) {
const importItems = [];
const codeItems = [];
const atRuleImportNames = new Map();
const urlImportNames = new Map();
let importPrefix;
if (exportType === 'full') {
importItems.push(esModule ? `import ___CSS_LOADER_API_IMPORT___ from ${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/api'))};` : `var ___CSS_LOADER_API_IMPORT___ = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/api'))});`);
codeItems.push(esModule ? `var exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});` : `exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});`);
}
imports.forEach(item => {
// eslint-disable-next-line default-case
switch (item.type) {
case '@import':
{
const {
url,
media
} = item;
const preparedMedia = media ? `, ${JSON.stringify(media)}` : '';
if (!(0, _loaderUtils.isUrlRequest)(url)) {
codeItems.push(`exports.push([module.id, ${JSON.stringify(`@import url(${url});`)}${preparedMedia}]);`);
return;
}
let importName = atRuleImportNames.get(url);
if (!importName) {
if (!importPrefix) {
importPrefix = getImportPrefix(loaderContext, importLoaders);
}
importName = `___CSS_LOADER_AT_RULE_IMPORT_${atRuleImportNames.size}___`;
importItems.push(esModule ? `import ${importName} from ${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)};` : `var ${importName} = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)});`);
atRuleImportNames.set(url, importName);
}
codeItems.push(`exports.i(${importName}${preparedMedia});`);
}
break;
case 'url':
{
if (urlImportNames.size === 0) {
importItems.push(esModule ? `import ___CSS_LOADER_GET_URL_IMPORT___ from ${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/getUrl.js'))};` : `var ___CSS_LOADER_GET_URL_IMPORT___ = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/getUrl.js'))});`);
}
const {
replacementName,
url,
hash,
needQuotes
} = item;
let importName = urlImportNames.get(url);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlImportNames.size}___`;
importItems.push(esModule ? `import ${importName} from ${(0, _loaderUtils.stringifyRequest)(loaderContext, url)};` : `var ${importName} = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, url)});`);
urlImportNames.set(url, importName);
}
const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? 'needQuotes: true' : []);
const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '';
codeItems.push(`var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});`);
}
break;
case 'icss-import':
{
const {
importName,
url,
media
} = item;
const preparedMedia = media ? `, ${JSON.stringify(media)}` : ', ""';
if (!importPrefix) {
importPrefix = getImportPrefix(loaderContext, importLoaders);
}
importItems.push(esModule ? `import ${importName} from ${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)};` : `var ${importName} = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)});`);
if (exportType === 'full') {
codeItems.push(`exports.i(${importName}${preparedMedia}, true);`);
}
}
break;
}
});
const items = importItems.concat(codeItems);
return items.length > 0 ? `// Imports\n${items.join('\n')}\n` : '';
}
function getModuleCode(loaderContext, result, exportType, sourceMap, replacers) {
if (exportType !== 'full') {
return '';
}
const {
css,
map
} = result;
const sourceMapValue = sourceMap && map ? `,${map}` : '';
let cssCode = JSON.stringify(css);
replacers.forEach(replacer => {
const {
type,
replacementName
} = replacer;
if (type === 'url') {
cssCode = cssCode.replace(new RegExp(replacementName, 'g'), () => `" + ${replacementName} + "`);
}
if (type === 'icss-import') {
const {
importName,
localName
} = replacer;
cssCode = cssCode.replace(new RegExp(replacementName, 'g'), () => `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
}
});
return `// Module\nexports.push([module.id, ${cssCode}, ""${sourceMapValue}]);\n`;
}
function dashesCamelCase(str) {
return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
}
function getExportCode(loaderContext, exports, exportType, replacers, localsConvention, esModule) {
const exportItems = [];
let exportLocalsCode;
if (exports.length > 0) {
const exportLocals = [];
const addExportedLocal = (name, value) => {
exportLocals.push(`\t${JSON.stringify(name)}: ${JSON.stringify(value)}`);
};
exports.forEach(item => {
const {
name,
value
} = item;
switch (localsConvention) {
case 'camelCase':
{
addExportedLocal(name, value);
const modifiedName = (0, _camelcase.default)(name);
if (modifiedName !== name) {
addExportedLocal(modifiedName, value);
}
break;
}
case 'camelCaseOnly':
{
addExportedLocal((0, _camelcase.default)(name), value);
break;
}
case 'dashes':
{
addExportedLocal(name, value);
const modifiedName = dashesCamelCase(name);
if (modifiedName !== name) {
addExportedLocal(modifiedName, value);
}
break;
}
case 'dashesOnly':
{
addExportedLocal(dashesCamelCase(name), value);
break;
}
case 'asIs':
default:
addExportedLocal(name, value);
break;
}
});
exportLocalsCode = exportLocals.join(',\n');
replacers.forEach(replacer => {
if (replacer.type === 'icss-import') {
const {
replacementName,
importName,
localName
} = replacer;
exportLocalsCode = exportLocalsCode.replace(new RegExp(replacementName, 'g'), () => exportType === 'locals' ? `" + ${importName}[${JSON.stringify(localName)}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
}
});
}
if (exportType === 'locals') {
exportItems.push(`${esModule ? 'export default' : 'module.exports ='} ${exportLocalsCode ? `{\n${exportLocalsCode}\n}` : '{}'};`);
} else {
if (exportLocalsCode) {
exportItems.push(`exports.locals = {\n${exportLocalsCode}\n};`);
}
exportItems.push(`${esModule ? 'export default' : 'module.exports ='} exports;`);
}
return `// Exports\n${exportItems.join('\n')}\n`;
}