create a function that can be passed to `map` for a collection of critical css rules. The function will match original rules against the selector of the critical css declarations, concatenate them together, and then keep only the unique ones
554713
function replaceDecls(originalRules, criticalRule){
		// find all the rules in the original CSS that have the same selectors and
		// then create an array of all the associated declarations. Note that this
		// works with mutiple duplicate selectors on the original CSS
		var originalDecls = _.flatten(
			originalRules
				.filter(function(rule){
					return _.isEqual(rule.selectors, criticalRule.selectors);
				})
				.map(function(rule){
					return rule.declarations;
				})
		);

		// take all the declarations that were found from the original CSS and use
		// them here, make sure that we de-dup any declarations from the original CSS
		criticalRule.declarations =
			_.uniqBy(criticalRule.declarations.concat(originalDecls),	function(decl){
				return decl.property + ":" + decl.value;
			});

		return criticalRule;
	}
829392
function compile_fancy(block, scope) {
    var fns= block.toString().replace(css_matcher, function(src, tag_name, classes, hash, empty){
      var result= src.replace(classes, ''), tag_start,
          class_names= (classes || "").split(' ').join('').split('.').splice(1).join(' ');
      if(!tagset[tag_name]) {
        result= src;
      } else if(class_names !== "") {
        tag_start= tag_name +'({"class":"'+ class_names +'"';
        if(hash) {
          result= tag_start +', '+ result.substring((result.indexOf('{') + 1));
        } else if(empty) {
          result= tag_start +'})';
        } else {
          result= tag_start +'},'+ result.substring((result.indexOf('(') + 1));
        }
      } 
      return result;
    });
    return compile_scope(fns, scope);
  }
907900
function styleLayer(layer) {
    var groups = _.map(layer, ruleGroup => {
        var groupedRules =  _.chain(ruleGroup.rules)
            .map(rule => {
                // Add conditions to each rule, if any
                var conditions = getConditions(rule);
                if (conditions && conditions.length > 0) {
                    rule.conditions = conditions;
                }
                return rule;
            })
            .groupBy(subRule => {
                // Group by conditions
                return stringify(subRule.conditions);
            })
            .value();
        return _.values(groupedRules);
    });

    return groups.map(ruleGroup => {
        try {
            return ruleGroup.map(ruleSubgroup => {
                return styleRuleGroup(ruleSubgroup);
            });
        }
        catch (e) {
            console.warn(e);
            return null;
        }
    });
}
769256
function getCSSRules(doc) {
    var styles = doc.getElementsByTagName('style'),
        allRules = { },
        rules;

    // very crude parsing of style contents
    for (var i = 0, len = styles.length; i < len; i++) {
      var styleContents = styles[0].textContent;

      // remove comments
      styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');

      rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
      rules = rules.map(function(rule) { return rule.trim() });

      rules.forEach(function(rule) {
        var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/),
            rule = match[1],
            declaration = match[2].trim(),
            propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/);

        if (!allRules[rule]) {
          allRules[rule] = { };
        }

        for (var i = 0, len = propertyValuePairs.length; i < len; i++) {
          var pair = propertyValuePairs[i].split(/\s*:\s*/),
              property = pair[0],
              value = pair[1];

          allRules[rule][property] = value;
        }
      });
    }

    return allRules;
  }
670241
function _mergeCSS($p, &$t)
	{
		// Save Cascading CSS e.g. "div.topic p" at this block level
		if (isset($p) && $p) {
			if ($t) {
				$t = $this->array_merge_recursive_unique($t, $p);
			} else {
				$t = $p;
			}
		}
	}
275911
function buildStyleAttribute(styleMap) {
  var styleAttribute = [];
  for (var property in styleMap) {
    styleAttribute.push(property + ': ' + styleMap[property] + ';');
  }
  return styleAttribute.join(' ');
}
21006
function createAtRules(css, rule, queries) {
  var parent = rule.parent;
  var prev = rule;

  for(var k in queries) {
    var q = queries[k];
    var at = postcss.atRule({name: 'media', params: q.arg, source: rule.source});
    var qr = postcss.rule ({selector: q.sel, source: rule.source});

    at.append(qr);

    for (var i = 0; i < q.props.length; i++) {
      var prop = q.props[i];
      qr.append(prop.decl.remove());
    };

    // Again we keep track of the previous insert and insert after it, to maintain the original order
    // and CSS specificity.
    parent.insertAfter(prev, at);
    prev = at;
  }

}
875625
function mapStyleAttr(node, text, maps, id, nodeId, isComponent)
  {
    var styles = text.match(__matchStyles),
        isFullStyle = (styles && styles[0].match(__matchText) && styles.length === 1),
        mapText,
        mapValues,
        style,
        title,
        value,
        item,
        len = styles.length,
        titleMap,
        localMap,
        x = 0,
        lenn,
        i = 0;
    
    if(isFullStyle)
    {
      item = styles[0];
      if(item.match(__matchInsert))
      {
        localMap = new mapObject({
            local_id: id,
            node_id: nodeId,
            mapIndex: maps.length,
            mapTextIndex: 0,
            text: item,
            maps: maps,
            mapText: [item],
            type: 'style',
            isInsert: true,
            property: 'style',
            local: node.style,
            node: node,
            isInlineStyle: true,
            isFullStyle: true,
            isPointer: isComponent
          })
          maps.push(localMap)
          localMap.mapText = [maps[(maps.length - 1)]];
      }
      else if(item.match(__matchText))
      {
        localMap = new mapObject({
            local_id: id,
            node_id: nodeId,
            mapIndex: maps.length,
            mapTextIndex: 0,
            text: item,
            maps: maps,
            mapText: [item],
            type: 'style',
            property: 'style',
            listener: 'style',
            local: node.style,
            node: node,
            isInlineStyle: true,
            isFullStyle: true,
            isPointer: isComponent
          })
          maps.push(localMap)
          localMap.mapText = [maps[(maps.length - 1)]];
      }
    }
    else
    {
      for(x;x<len;x++)
      {
        if(styles[x].indexOf(':') === -1)
        {
          title = styles[x];
          value = '';
        }
        else
        {
          style = styles[x].split(':');
          title = style[0];
          value = style[1];
        }
        /* First we try to match the title */
        if(title.match(__matchInsert))
        {
          titleMap = new mapObject({
            local_id: id,
            node_id: nodeId,
            mapIndex: maps.length,
            mapTextIndex: 0,
            text: title,
            maps: maps,
            mapText: [title],
            type: 'style',
            isInsert: true,
            property: 'style',
            node: node,
            local: node.style,
            isFullProp: !(value),
            isInlineStyle: true,
            isPointer: isComponent,
            isProperty: true
          })
          maps.push(titleMap)
          titleMap.mapText = [maps[(maps.length - 1)]];
        }
        else if(title.match(__matchText))
        {
          titleMap = new mapObject({
            local_id: id,
            node_id: nodeId,
            mapIndex: maps.length,
            mapTextIndex: 0,
            text: title,
            maps: maps,
            mapText: [title],
            type: 'style',
            property: 'style',
            node: node,
            local: node.style,
            isFullProp: !(value),
            isInlineStyle: true,
            isPointer: isComponent,
            isProperty: true
          })
          maps.push(titleMap)
          titleMap.mapText = [maps[(maps.length - 1)]];
        }
        else
        {
          titleMap = undefined;
        }
        /* Then we try to match the value */
        mapText = splitText(value);
        mapValues = (titleMap ? titleMap.mapValues : maps);
        lenn = mapText.length;
        i = 0;

        for(i;i<lenn;i++)
        {
          item = mapText[i];
          if(item.match(__matchInsert))
          {
            localMap = new mapObject({
              local_id: id,
              node_id: nodeId,
              mapIndex: mapValues.length,
              mapTextIndex: i,
              text: item,
              mapText: mapText,
              maps: mapValues,
              node: node,
              type: 'style',
              isInsert: true,
              property: title,
              local: node.style,
              localAttr: title,
              isInlineStyle: true,
              isPointer: isComponent,
              isPropertyValue: true
            })
            if(!titleMap)
            {
              maps.push(localMap);
              localMap.mapText = [maps[(maps.length - 1)]];
            }
            else
            {
              titleMap.mapValues.push(localMap)
            }
          }
          else if(item.match(__matchText))
          {
            localMap = new mapObject({
              local_id: id,
              node_id: nodeId,
              mapIndex: mapValues.length,
              mapTextIndex: i,
              text: item,
              mapText: mapText,
              maps: mapValues,
              node: node,
              type: 'style',
              property: title,
              listener: title,
              local: node.style,
              localAttr: title,
              isInlineStyle: true,
              isPointer: isComponent,
              isPropertyValue: true
            })
            if(!titleMap)
            {
              maps.push(localMap);
              localMap.mapText = [maps[(maps.length - 1)]];
            }
            else
            {
              titleMap.mapValues.push(localMap)
            }
          }
          else
          {
            localMap = item;
          }
          mapText[i] = localMap;
        }
        if(titleMap) titleMap.values = mapText;
      }
    }
  }
361604
function (selectorText, css) {
            var sheet = this.sheet;
            var rulesName = this.rulesName;
            var cssRules = this.cssRules;
            var rule = cssRules[selectorText];
            var multiSelector = selectorText.split(/\s*,\s*/);
            var i;
            if (multiSelector.length > 1) {
                for (i = 0; i < multiSelector.length - 1; i++) {
                    this.set(multiSelector[i], css);
                }
                return this;
            }
            if (rule) {
                css = toCssText(css, rule.style.cssText);
                if (css) {
                    rule.style.cssText = css;
                } else {
                    // unset remove this rule
                    delete cssRules[selectorText];
                    for (i = sheet[rulesName].length - 1; i >= 0; i--) {
                        if (sheet[rulesName][i] === rule) {
                            deleteRule(sheet, i);
                            break;
                        }
                    }
                }
            } else {
                var len = sheet[rulesName].length;
                css = toCssText(css);
                if (css) {
                    insertRule(sheet, selectorText, css, len);
                    cssRules[selectorText] = sheet[rulesName][len];
                }
            }
            return this;
        }
1029260
function plugin(cb) {
	return function(css) {
		if (lodash.isFunction(cb)) {
			var token = cb(css.source.input.file);

			if (!lodash.isNull(token)) {
				css.eachRule(function(rule) {
					if (!areSelectorsValid(rule.selectors, token)) {
						throw rule.error('Wrong selector');
					}
				});
			}
		}
	}
}
704997
function createPrefixedRule(rule, prefix) {
  const prefixLength = prefix.length;
  const selectorStart = rule.selector.slice(1, prefixLength + 1);
  const isAlreadyPrefixed = selectorStart === prefix;
  if (isAlreadyPrefixed) return false;

  return rule.clone({
    selector: `.${prefix + rule.selector.substring(1)}`,
  });
}
956927
def all_selectors(Class, fn):
        """"""
        selectors = []
        cssparser = cssutils.CSSParser(validate=False)
        css = cssparser.parseFile(fn)
        for rule in [r for r in css.cssRules if type(r)==cssutils.css.CSSStyleRule]:
            selectors += [sel.selectorText for sel in rule.selectorList]
        selectors = sorted(list(set(selectors)))
        return selectors
919543
function map(fn, m) {
  if(!isFunction(fn)) {
    throw new TypeError('map: Function required for first argument')
  }

  if(isFunction(m)) {
    return compose(fn, m)
  }

  if(isArray(m)) {
    return array.map(fn, m)
  }

  if(m && isFunctor(m)) {
    return (m[fl.map] || m.map).call(m, fn)
  }

  if(isObject(m)) {
    return object.map(fn, m)
  }

  throw new TypeError('map: Object, Function or Functor of the same type required for second argument')
}
435892
def css_to_func(css, flags, css_namespaces, lang):
    """"""
    from cssselect import parse, HTMLTranslator
    from cssselect.parser import FunctionalPseudoElement
    #  FIXME HACK need lessc to support functional-pseudo-selectors instead
    #  of marking as strings and stripping " here.
    if not (css):
        return None

    sel = parse(css.strip('" '))[0]
    xpath = HTMLTranslator().selector_to_xpath(sel)

    first_letter = False
    if sel.pseudo_element is not None:
        if type(sel.pseudo_element) == FunctionalPseudoElement:
            if sel.pseudo_element.name in ('attr', 'first-letter'):
                xpath += '/@' + sel.pseudo_element.arguments[0].value
                if sel.pseudo_element.name == 'first-letter':
                    first_letter = True
        elif isinstance(sel.pseudo_element, type(u'')):
            if sel.pseudo_element == 'first-letter':
                first_letter = True

    xp = etree.XPath(xpath, namespaces=css_namespaces)

    def toupper(u):
        """Use icu library for locale sensitive uppercasing (python2)."""
        loc = Locale(lang) if lang else Locale()
        return UnicodeString(u).toUpper(loc).encode('utf-8').decode('utf-8')

    def func(elem):
        res = xp(elem)
        if res:
            if etree.iselement(res[0]):
                res_str = etree.tostring(res[0], encoding='unicode',
                                         method="text")
            else:
                res_str = res[0]
            if first_letter:
                if res_str:
                    if flags and 'nocase' in flags:
                        return toupper(res_str[0])
                    else:
                        return res_str[0]
                else:
                    return res_str
            else:
                if flags and 'nocase' in flags:
                    return toupper(res_str)
                else:
                    return res_str

    return func
964516
function createStylefromCode(styles, abspath) {
    //may import other file
    const arr = queryImport(styles)
    const baseRes = handleImportStyle(styles, abspath)
    const obj = {}
    const ast = csstree.parse(baseRes);
    csstree.walk(ast, {
        enter: function (node) {
            if (node.type === 'Rule' && node.prelude && node.prelude.type === 'SelectorList') {
                const clzName = []
                node.prelude.children.forEach(e => {
                    //we may handle each class selector here
                    let ans = selectorBlockHandler(e)
                    if (ans) {
                        //to save before value
                        obj[ans] = obj[ans] || {}
                        //save ans to log which to give value
                        clzName.push(ans)
                    }
                })
                const styleArray = []
                node.block.children.forEach(e => {
                    //handle with unit or function case
                    const styleItem = styleBlockHandler(e)
                    styleItem.length > 0 && styleArray.push(styleItem)
                })
                clzName.forEach(e => {
                    try {
                        const styleObject = transform(styleArray)
                        if (styleObject.fontWeight) {
                            //fontWeight must be string
                            styleObject.fontWeight = styleObject.fontWeight + ""
                        }
                        Object.assign(obj[e], styleObject)
                    } catch (e) {
                        console.error("convert ", abspath, " error:", e.message)
                    }

                })
            }
        },
    })
    return {styles: obj, imports: arr}
}
308176
function _makeCSSTarget(targets, rule) {
        if (rule.sourceURL) {
            var url = rule.sourceURL;
            url += ":" + rule.style.range.start;
            var name = rule.selectorList.text;
            var file = _fileFromURL(url);
            targets.push({"type": "css", "url": url, "name": name, "file": file});
        }
    }
1103159
function createMarkupOnPseudoClass(pseudoClasses, id, disabled) {
  return mapObject(pseudoClasses, (style, pseudoClass) => {
    if (style && Object.keys(style).length > 0) {
      const styleString = CSSPropertyOperations.createMarkupForStyles(style);
      const styleWithImportant = styleString.replace(/;/g, ' !important;');

      return disabled ?
        `.${id}[disabled]:${pseudoClass} {${styleWithImportant}}` :
        `.${id}:${pseudoClass} {${styleWithImportant}}`;
    }

    return undefined;
  });
}