@css-components/cli
Version:
CLI Interface for interacting with CSS Component Modules - CCM
1,946 lines (1,687 loc) • 719 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path$8 = require('path');
var require$$2 = require('url');
var require$$0$1 = require('fs');
var require$$1 = require('crypto');
var require$$0$2 = require('util');
var require$$4 = require('events');
var require$$6 = require('assert');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
});
}
n['default'] = e;
return Object.freeze(n);
}
var path__default = /*#__PURE__*/_interopDefaultLegacy(path$8);
var path__namespace = /*#__PURE__*/_interopNamespace(path$8);
var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
var require$$0__namespace = /*#__PURE__*/_interopNamespace(require$$0$1);
var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
var minimist = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {}, unknownFn: null };
if (typeof opts['unknown'] === 'function') {
flags.unknownFn = opts['unknown'];
}
if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
flags.allBools = true;
} else {
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
}
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
if (aliases[key]) {
flags.strings[aliases[key]] = true;
}
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function argDefined(key, arg) {
return (flags.allBools && /^--[^=]+$/.test(arg)) ||
flags.strings[key] || flags.bools[key] || aliases[key];
}
function setArg (key, val, arg) {
if (arg && flags.unknownFn && !argDefined(key, arg)) {
if (flags.unknownFn(arg) === false) return;
}
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
function setKey (obj, keys, value) {
var o = obj;
for (var i = 0; i < keys.length-1; i++) {
var key = keys[i];
if (key === '__proto__') return;
if (o[key] === undefined) o[key] = {};
if (o[key] === Object.prototype || o[key] === Number.prototype
|| o[key] === String.prototype) o[key] = {};
if (o[key] === Array.prototype) o[key] = [];
o = o[key];
}
var key = keys[keys.length - 1];
if (key === '__proto__') return;
if (o === Object.prototype || o === Number.prototype
|| o === String.prototype) o = {};
if (o === Array.prototype) o = [];
if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function aliasIsBoolean(key) {
return aliases[key].some(function (x) {
return flags.bools[x];
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
var key = m[1];
var value = m[2];
if (flags.bools[key]) {
value = value !== 'false';
}
setArg(key, value, arg);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& !flags.allBools
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next, arg);
continue;
}
if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
setArg(letters[j], next.split('=')[1], arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next, arg);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2), arg);
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i+1], arg);
i++;
}
else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
setArg(key, args[i+1] === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
}
else {
if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
if (opts.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1));
break;
}
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
if (opts['--']) {
argv['--'] = new Array();
notFlags.forEach(function(key) {
argv['--'].push(key);
});
}
else {
notFlags.forEach(function(key) {
argv._.push(key);
});
}
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
var colorette$1 = {};
let enabled =
!("NO_COLOR" in process.env) &&
("FORCE_COLOR" in process.env ||
process.platform === "win32" ||
(process.stdout != null &&
process.stdout.isTTY &&
process.env.TERM &&
process.env.TERM !== "dumb"));
const raw = (open, close, searchRegex, replaceValue) => (s) =>
enabled
? open +
(~(s += "").indexOf(close, 4) // skip opening \x1b[
? s.replace(searchRegex, replaceValue)
: s) +
close
: s;
const init = (open, close) => {
return raw(
`\x1b[${open}m`,
`\x1b[${close}m`,
new RegExp(`\\x1b\\[${close}m`, "g"),
`\x1b[${open}m`
)
};
colorette$1.options = Object.defineProperty({}, "enabled", {
get: () => enabled,
set: (value) => (enabled = value),
});
colorette$1.reset = init(0, 0);
colorette$1.bold = raw("\x1b[1m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[1m");
colorette$1.dim = raw("\x1b[2m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[2m");
colorette$1.italic = init(3, 23);
colorette$1.underline = init(4, 24);
colorette$1.inverse = init(7, 27);
colorette$1.hidden = init(8, 28);
colorette$1.strikethrough = init(9, 29);
colorette$1.black = init(30, 39);
colorette$1.red = init(31, 39);
colorette$1.green = init(32, 39);
colorette$1.yellow = init(33, 39);
colorette$1.blue = init(34, 39);
colorette$1.magenta = init(35, 39);
colorette$1.cyan = init(36, 39);
colorette$1.white = init(37, 39);
colorette$1.gray = init(90, 39);
colorette$1.bgBlack = init(40, 49);
colorette$1.bgRed = init(41, 49);
colorette$1.bgGreen = init(42, 49);
colorette$1.bgYellow = init(43, 49);
colorette$1.bgBlue = init(44, 49);
colorette$1.bgMagenta = init(45, 49);
colorette$1.bgCyan = init(46, 49);
colorette$1.bgWhite = init(47, 49);
colorette$1.blackBright = init(90, 39);
colorette$1.redBright = init(91, 39);
colorette$1.greenBright = init(92, 39);
colorette$1.yellowBright = init(93, 39);
colorette$1.blueBright = init(94, 39);
colorette$1.magentaBright = init(95, 39);
colorette$1.cyanBright = init(96, 39);
colorette$1.whiteBright = init(97, 39);
colorette$1.bgBlackBright = init(100, 49);
colorette$1.bgRedBright = init(101, 49);
colorette$1.bgGreenBright = init(102, 49);
colorette$1.bgYellowBright = init(103, 49);
colorette$1.bgBlueBright = init(104, 49);
colorette$1.bgMagentaBright = init(105, 49);
colorette$1.bgCyanBright = init(106, 49);
colorette$1.bgWhiteBright = init(107, 49);
const SINGLE_QUOTE = "'".charCodeAt(0);
const DOUBLE_QUOTE = '"'.charCodeAt(0);
const BACKSLASH = '\\'.charCodeAt(0);
const SLASH = '/'.charCodeAt(0);
const NEWLINE = '\n'.charCodeAt(0);
const SPACE = ' '.charCodeAt(0);
const FEED = '\f'.charCodeAt(0);
const TAB = '\t'.charCodeAt(0);
const CR = '\r'.charCodeAt(0);
const OPEN_SQUARE = '['.charCodeAt(0);
const CLOSE_SQUARE = ']'.charCodeAt(0);
const OPEN_PARENTHESES = '('.charCodeAt(0);
const CLOSE_PARENTHESES = ')'.charCodeAt(0);
const OPEN_CURLY = '{'.charCodeAt(0);
const CLOSE_CURLY = '}'.charCodeAt(0);
const SEMICOLON = ';'.charCodeAt(0);
const ASTERISK = '*'.charCodeAt(0);
const COLON = ':'.charCodeAt(0);
const AT = '@'.charCodeAt(0);
const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
const RE_BAD_BRACKET = /.[\n"'(/\\]/;
const RE_HEX_ESCAPE = /[\da-f]/i;
var tokenize$1 = function tokenizer(input, options = {}) {
let css = input.css.valueOf();
let ignore = options.ignoreErrors;
let code, next, quote, content, escape;
let escaped, escapePos, prev, n, currentToken;
let length = css.length;
let pos = 0;
let buffer = [];
let returned = [];
function position() {
return pos
}
function unclosed(what) {
throw input.error('Unclosed ' + what, pos)
}
function endOfFile() {
return returned.length === 0 && pos >= length
}
function nextToken(opts) {
if (returned.length) return returned.pop()
if (pos >= length) return
let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
code = css.charCodeAt(pos);
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED: {
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
} while (
code === SPACE ||
code === NEWLINE ||
code === TAB ||
code === CR ||
code === FEED
)
currentToken = ['space', css.slice(pos, next)];
pos = next - 1;
break
}
case OPEN_SQUARE:
case CLOSE_SQUARE:
case OPEN_CURLY:
case CLOSE_CURLY:
case COLON:
case SEMICOLON:
case CLOSE_PARENTHESES: {
let controlChar = String.fromCharCode(code);
currentToken = [controlChar, controlChar, pos];
break
}
case OPEN_PARENTHESES: {
prev = buffer.length ? buffer.pop()[1] : '';
n = css.charCodeAt(pos + 1);
if (
prev === 'url' &&
n !== SINGLE_QUOTE &&
n !== DOUBLE_QUOTE &&
n !== SPACE &&
n !== NEWLINE &&
n !== TAB &&
n !== FEED &&
n !== CR
) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos;
break
} else {
unclosed('bracket');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped)
currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
currentToken = ['(', '(', pos];
} else {
currentToken = ['brackets', content, pos, next];
pos = next;
}
}
break
}
case SINGLE_QUOTE:
case DOUBLE_QUOTE: {
quote = code === SINGLE_QUOTE ? "'" : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos + 1;
break
} else {
unclosed('string');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped)
currentToken = ['string', css.slice(pos, next + 1), pos, next];
pos = next;
break
}
case AT: {
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
pos = next;
break
}
case BACKSLASH: {
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (
escape &&
code !== SLASH &&
code !== SPACE &&
code !== NEWLINE &&
code !== TAB &&
code !== CR &&
code !== FEED
) {
next += 1;
if (RE_HEX_ESCAPE.test(css.charAt(next))) {
while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
next += 1;
}
if (css.charCodeAt(next + 1) === SPACE) {
next += 1;
}
}
}
currentToken = ['word', css.slice(pos, next + 1), pos, next];
pos = next;
break
}
default: {
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1;
if (next === 0) {
if (ignore || ignoreUnclosed) {
next = css.length;
} else {
unclosed('comment');
}
}
currentToken = ['comment', css.slice(pos, next + 1), pos, next];
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
currentToken = ['word', css.slice(pos, next + 1), pos, next];
buffer.push(currentToken);
pos = next;
}
break
}
}
pos++;
return currentToken
}
function back(token) {
returned.push(token);
}
return {
back,
nextToken,
endOfFile,
position
}
};
let { cyan, gray: gray$1, green, yellow, magenta } = colorette$1;
let tokenizer$1 = tokenize$1;
let Input$4;
function registerInput(dependant) {
Input$4 = dependant;
}
const HIGHLIGHT_THEME = {
'brackets': cyan,
'at-word': cyan,
'comment': gray$1,
'string': green,
'class': yellow,
'hash': magenta,
'call': cyan,
'(': cyan,
')': cyan,
'{': yellow,
'}': yellow,
'[': yellow,
']': yellow,
':': yellow,
';': yellow
};
function getTokenType([type, value], processor) {
if (type === 'word') {
if (value[0] === '.') {
return 'class'
}
if (value[0] === '#') {
return 'hash'
}
}
if (!processor.endOfFile()) {
let next = processor.nextToken();
processor.back(next);
if (next[0] === 'brackets' || next[0] === '(') return 'call'
}
return type
}
function terminalHighlight$2(css) {
let processor = tokenizer$1(new Input$4(css), { ignoreErrors: true });
let result = '';
while (!processor.endOfFile()) {
let token = processor.nextToken();
let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
if (color) {
result += token[1]
.split(/\r?\n/)
.map(i => color(i))
.join('\n');
} else {
result += token[1];
}
}
return result
}
terminalHighlight$2.registerInput = registerInput;
var terminalHighlight_1 = terminalHighlight$2;
let { red, bold, gray, options: colorette } = colorette$1;
let terminalHighlight$1 = terminalHighlight_1;
class CssSyntaxError$3 extends Error {
constructor(message, line, column, source, file, plugin) {
super(message);
this.name = 'CssSyntaxError';
this.reason = message;
if (file) {
this.file = file;
}
if (source) {
this.source = source;
}
if (plugin) {
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
this.line = line;
this.column = column;
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError$3);
}
}
setMessage() {
this.message = this.plugin ? this.plugin + ': ' : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column;
}
this.message += ': ' + this.reason;
}
showSourceCode(color) {
if (!this.source) return ''
let css = this.source;
if (color == null) color = colorette.enabled;
if (terminalHighlight$1) {
if (color) css = terminalHighlight$1(css);
}
let lines = css.split(/\r?\n/);
let start = Math.max(this.line - 3, 0);
let end = Math.min(this.line + 2, lines.length);
let maxWidth = String(end).length;
let mark, aside;
if (color) {
mark = text => bold(red(text));
aside = text => gray(text);
} else {
mark = aside = str => str;
}
return lines
.slice(start, end)
.map((line, index) => {
let number = start + 1 + index;
let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
if (number === this.line) {
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
}
return ' ' + aside(gutter) + line
})
.join('\n')
}
toString() {
let code = this.showSourceCode();
if (code) {
code = '\n\n' + code + '\n';
}
return this.name + ': ' + this.message + code
}
}
var cssSyntaxError = CssSyntaxError$3;
CssSyntaxError$3.default = CssSyntaxError$3;
var symbols = {};
symbols.isClean = Symbol('isClean');
symbols.my = Symbol('my');
const DEFAULT_RAW = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' ',
semicolon: false
};
function capitalize$1(str) {
return str[0].toUpperCase() + str.slice(1)
}
class Stringifier$2 {
constructor(builder) {
this.builder = builder;
}
stringify(node, semicolon) {
/* istanbul ignore if */
if (!this[node.type]) {
throw new Error(
'Unknown AST node type ' +
node.type +
'. ' +
'Maybe you need to change PostCSS stringifier.'
)
}
this[node.type](node, semicolon);
}
document(node) {
this.body(node);
}
root(node) {
this.body(node);
if (node.raws.after) this.builder(node.raws.after);
}
comment(node) {
let left = this.raw(node, 'left', 'commentLeft');
let right = this.raw(node, 'right', 'commentRight');
this.builder('/*' + left + node.text + right + '*/', node);
}
decl(node, semicolon) {
let between = this.raw(node, 'between', 'colon');
let string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += node.raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(string, node);
}
rule(node) {
this.block(node, this.rawValue(node, 'selector'));
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end');
}
}
atrule(node, semicolon) {
let name = '@' + node.name;
let params = node.params ? this.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
if (node.nodes) {
this.block(node, name + params);
} else {
let end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(name + params + end, node);
}
}
body(node) {
let last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== 'comment') break
last -= 1;
}
let semicolon = this.raw(node, 'semicolon');
for (let i = 0; i < node.nodes.length; i++) {
let child = node.nodes[i];
let before = this.raw(child, 'before');
if (before) this.builder(before);
this.stringify(child, last !== i || semicolon);
}
}
block(node, start) {
let between = this.raw(node, 'between', 'beforeOpen');
this.builder(start + between + '{', node, 'start');
let after;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
}
raw(node, own, detect) {
let value;
if (!detect) detect = own;
// Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value
}
let parent = node.parent;
if (detect === 'before') {
// Hack for first rule in CSS
if (!parent || (parent.type === 'root' && parent.first === node)) {
return ''
}
// `root` nodes in `document` should use only their own raws
if (parent && parent.type === 'document') {
return ''
}
}
// Floating child without parent
if (!parent) return DEFAULT_RAW[detect]
// Detect style by other nodes
let root = node.root();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect]
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect)
} else {
let method = 'raw' + capitalize$1(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(i => {
value = i.raws[own];
if (typeof value !== 'undefined') return false
});
}
}
if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
root.rawCache[detect] = value;
return value
}
rawSemicolon(root) {
let value;
root.walk(i => {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false
}
});
return value
}
rawEmptyBody(root) {
let value;
root.walk(i => {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false
}
});
return value
}
rawIndent(root) {
if (root.raws.indent) return root.raws.indent
let value;
root.walk(i => {
let p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
let parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/\S/g, '');
return false
}
}
});
return value
}
rawBeforeComment(root, node) {
let value;
root.walkComments(i => {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
} else if (value) {
value = value.replace(/\S/g, '');
}
return value
}
rawBeforeDecl(root, node) {
let value;
root.walkDecls(i => {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
} else if (value) {
value = value.replace(/\S/g, '');
}
return value
}
rawBeforeRule(root) {
let value;
root.walk(i => {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
}
});
if (value) value = value.replace(/\S/g, '');
return value
}
rawBeforeClose(root) {
let value;
root.walk(i => {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
}
});
if (value) value = value.replace(/\S/g, '');
return value
}
rawBeforeOpen(root) {
let value;
root.walk(i => {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false
}
});
return value
}
rawColon(root) {
let value;
root.walkDecls(i => {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false
}
});
return value
}
beforeAfter(node, detect) {
let value;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
let buf = node.parent;
let depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.includes('\n')) {
let indent = this.raw(node, null, 'indent');
if (indent.length) {
for (let step = 0; step < depth; step++) value += indent;
}
}
return value
}
rawValue(node, prop) {
let value = node[prop];
let raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw
}
return value
}
}
var stringifier = Stringifier$2;
let Stringifier$1 = stringifier;
function stringify$9(node, builder) {
let str = new Stringifier$1(builder);
str.stringify(node);
}
var stringify_1$2 = stringify$9;
stringify$9.default = stringify$9;
let { isClean: isClean$2, my: my$2 } = symbols;
let CssSyntaxError$2 = cssSyntaxError;
let Stringifier = stringifier;
let stringify$8 = stringify_1$2;
function cloneNode(obj, parent) {
let cloned = new obj.constructor();
for (let i in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, i)) {
// istanbul ignore next
continue
}
if (i === 'proxyCache') continue
let value = obj[i];
let type = typeof value;
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent;
} else if (i === 'source') {
cloned[i] = value;
} else if (Array.isArray(value)) {
cloned[i] = value.map(j => cloneNode(j, cloned));
} else {
if (type === 'object' && value !== null) value = cloneNode(value);
cloned[i] = value;
}
}
return cloned
}
class Node$4 {
constructor(defaults = {}) {
this.raws = {};
this[isClean$2] = false;
this[my$2] = true;
for (let name in defaults) {
if (name === 'nodes') {
this.nodes = [];
for (let node of defaults[name]) {
if (typeof node.clone === 'function') {
this.append(node.clone());
} else {
this.append(node);
}
}
} else {
this[name] = defaults[name];
}
}
}
error(message, opts = {}) {
if (this.source) {
let pos = this.positionBy(opts);
return this.source.input.error(message, pos.line, pos.column, opts)
}
return new CssSyntaxError$2(message)
}
warn(result, text, opts) {
let data = { node: this };
for (let i in opts) data[i] = opts[i];
return result.warn(text, data)
}
remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this
}
toString(stringifier = stringify$8) {
if (stringifier.stringify) stringifier = stringifier.stringify;
let result = '';
stringifier(this, i => {
result += i;
});
return result
}
assign(overrides = {}) {
for (let name in overrides) {
this[name] = overrides[name];
}
return this
}
clone(overrides = {}) {
let cloned = cloneNode(this);
for (let name in overrides) {
cloned[name] = overrides[name];
}
return cloned
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned
}
replaceWith(...nodes) {
if (this.parent) {
let bookmark = this;
let foundSelf = false;
for (let node of nodes) {
if (node === this) {
foundSelf = true;
} else if (foundSelf) {
this.parent.insertAfter(bookmark, node);
bookmark = node;
} else {
this.parent.insertBefore(bookmark, node);
}
}
if (!foundSelf) {
this.remove();
}
}
return this
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this);
return this.parent.nodes[index + 1]
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this);
return this.parent.nodes[index - 1]
}
before(add) {
this.parent.insertBefore(this, add);
return this
}
after(add) {
this.parent.insertAfter(this, add);
return this
}
root() {
let result = this;
while (result.parent && result.parent.type !== 'document') {
result = result.parent;
}
return result
}
raw(prop, defaultType) {
let str = new Stringifier();
return str.raw(this, prop, defaultType)
}
cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
}
toJSON(_, inputs) {
let fixed = {};
let emitInputs = inputs == null;
inputs = inputs || new Map();
let inputsNextIndex = 0;
for (let name in this) {
if (!Object.prototype.hasOwnProperty.call(this, name)) {
// istanbul ignore next
continue
}
if (name === 'parent' || name === 'proxyCache') continue
let value = this[name];
if (Array.isArray(value)) {
fixed[name] = value.map(i => {
if (typeof i === 'object' && i.toJSON) {
return i.toJSON(null, inputs)
} else {
return i
}
});
} else if (typeof value === 'object' && value.toJSON) {
fixed[name] = value.toJSON(null, inputs);
} else if (name === 'source') {
let inputId = inputs.get(value.input);
if (inputId == null) {
inputId = inputsNextIndex;
inputs.set(value.input, inputsNextIndex);
inputsNextIndex++;
}
fixed[name] = {
inputId,
start: value.start,
end: value.end
};
} else {
fixed[name] = value;
}
}
if (emitInputs) {
fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
}
return fixed
}
positionInside(index) {
let string = this.toString();
let column = this.source.start.column;
let line = this.source.start.line;
for (let i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { line, column }
}
positionBy(opts) {
let pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
let index = this.toString().indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos
}
getProxyProcessor() {
return {
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value;
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
prop === 'text'
) {
node.markDirty();
}
return true
},
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
}
}
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor());
}
return this.proxyCache
}
addToError(error) {
error.postcssNode = this;
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source;
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
);
}
return error
}
markDirty() {
if (this[isClean$2]) {
this[isClean$2] = false;
let next = this;
while ((next = next.parent)) {
next[isClean$2] = false;
}
}
}
get proxyOf() {
return this
}
}
var node_1 = Node$4;
Node$4.default = Node$4;
let Node$3 = node_1;
class Declaration$4 extends Node$3 {
constructor(defaults) {
if (
defaults &&
typeof defaults.value !== 'undefined' &&
typeof defaults.value !== 'string'
) {
defaults = { ...defaults, value: String(defaults.value) };
}
super(defaults);
this.type = 'decl';
}
get variable() {
return this.prop.startsWith('--') || this.prop[0] === '$'
}
}
var declaration = Declaration$4;
Declaration$4.default = Declaration$4;
var sourceMap = {};
var sourceMapGenerator = {};
var base64Vlq = {};
var base64$1 = {};
/* -*- 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.
*/
base64$1.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.
*/
base64$1.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;
};
/* -*- 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 = base64$1;
// 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.
*/
base64Vlq.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.
*/
base64Vlq.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;
};
var util$8 = {};
/* -*- Mode: js; js-indent-level: 2; -*- */
(function (exports) {
/*
* 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+))?(.*)$/;
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;
var MAX_CACHED_INPUTS = 32;
/**
* Takes some function `f(input) -> result` and returns a memoized version of
* `f`.
*
* We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
* memoization is a dumb-simple, linear least-recently-used cache.
*/
function lruMemoize(f) {
var cache = [];
return function(input) {
for (var i = 0; i < cache.length; i++) {
if (cache[i].input === input) {
var temp = cache[0];
cache[0] = cache[i];
cache[i] = temp;
return cache[0].result;
}
}
var result = f(input);
cache.unshift({
input,
result,
});
if (cache.length > MAX_CACHED_INPUTS) {
cache.pop();
}
return result;
};
}
/**
* 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.
*/
var normalize = lruMemoize(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);
// Split the path into parts between `/` characters. This is much faster than
// using `.split(/\/+/g)`.
var parts = [];
var start = 0;
var i = 0;
while (true) {
start = i;
i = path.indexOf("/", start);
if (i === -1) {
parts.push(path.slice(start));
break;
} else {
parts.push(path.slice(start, i));
while (i < path.length && path[i] === "/") {
i++;
}
}
}
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'