function written after some investigation here: https://github.com/facebook/react/issues/10135#issuecomment-401496776
178560
function setNativeValue(element, value) {
  const {set: valueSetter} =
    Object.getOwnPropertyDescriptor(element, 'value') || {}
  const prototype = Object.getPrototypeOf(element)
  const {set: prototypeValueSetter} =
    Object.getOwnPropertyDescriptor(prototype, 'value') || {}
  if (prototypeValueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value)
  } /* istanbul ignore next (I don't want to bother) */ else if (valueSetter) {
    valueSetter.call(element, value)
  } else {
    throw new Error('The given element does not have a value setter')
  }
}
34589
function getComments(path) {
  var source = fs.readFileSync(path, 'utf8');
  var comments = parseComments(source, true);
  var values = comments.map(function (comment) {
    return comment.value;
  });
  return parseJSDocs(values.join('\n'), { unwrap: true });
}
1285691
function whitage() {
        let closer = "(end)";
        let free = false;
        let left = global;
        let margin = 0;
        let nr_comments_skipped = 0;
        let open = true;
        let qmark = "";
        let result;
        let right;

        function expected_at(at) {
            warn(
                "expected_a_at_b_c",
                right,
                artifact(right),
                fudge + at,
                artifact_column(right)
            );
        }

        function at_margin(fit) {
            const at = margin + fit;
            if (right.from !== at) {
                return expected_at(at);
            }
        }

        function no_space_only() {
            if (
                left.id !== "(global)"
                && left.nr + 1 === right.nr
                && (
                    left.line !== right.line
                    || left.thru !== right.from
                )
            ) {
                warn(
                    "unexpected_space_a_b",
                    right,
                    artifact(left),
                    artifact(right)
                );
            }
        }

        function no_space() {
            if (left.line === right.line) {
                if (left.thru !== right.from && nr_comments_skipped === 0) {
                    warn(
                        "unexpected_space_a_b",
                        right,
                        artifact(left),
                        artifact(right)
                    );
                }
            } else {
                if (open) {
                    const at = (free)
                        ? margin
                        : margin + 8;
                    if (right.from < at) {
                        expected_at(at);
                    }
                } else {
                    if (right.from !== margin + 8) {
                        expected_at(margin + 8);
                    }
                }
            }
        }

        function one_space_only() {
            if (left.line !== right.line || left.thru + 1 !== right.from) {
                warn(
                    "expected_space_a_b",
                    right,
                    artifact(left),
                    artifact(right)
                );
            }
        }

        function one_space() {
            if (left.line === right.line) {
                if (left.thru + 1 !== right.from && nr_comments_skipped === 0) {
                    warn(
                        "expected_space_a_b",
                        right,
                        artifact(left),
                        artifact(right)
                    );
                }
            } else {
                if (free) {
                    if (right.from < margin) {
                        expected_at(margin);
                    }
                } else {
                    const mislaid = (stack.length) > 0
                        ? stack[stack.length - 1].right
                        : undefined;
                    if (!open && mislaid !== undefined) {
                        warn(
                            "expected_a_next_at_b",
                            mislaid,
                            artifact(mislaid.id),
                            margin + 4 + fudge
                        );
                    } else if (right.from !== margin + 8) {
                        expected_at(margin + 8);
                    }
                }
            }
        }

        function unqmark() {

// Undo the effects of dangling nested ternary operators.

            const level = qmark.length;
            if (level > 0) {
                margin -= level * 4;
            }
            qmark = "";
        }

        stack = [];
        tokens.forEach(function (the_token) {
            right = the_token;
            if (right.id === "(comment)" || right.id === "(end)") {
                nr_comments_skipped += 1;
            } else {

// If left is an opener and right is not the closer, then push the previous
// state. If the token following the opener is on the next line, then this is
// an open form. If the tokens are on the same line, then it is a closed form.
// Open form is more readable, with each item (statement, argument, parameter,
// etc) starting on its own line. Closed form is more compact. Statement blocks
// are always in open form.

                const new_closer = opener[left.id];
                if (typeof new_closer === "string") {
                    if (new_closer !== right.id) {
                        stack.push({
                            closer: closer,
                            free: free,
                            margin: margin,
                            open: open,
                            qmark: qmark,
                            right: right
                        });
                        qmark = "";
                        closer = new_closer;
                        if (left.line !== right.line) {
                            free = closer === ")" && left.free;
                            open = true;
                            margin += 4;
                            if (right.role === "label") {
                                if (right.from !== 0) {
                                    expected_at(0);
                                }
                            } else if (right.switch) {
                                unqmark();
                                at_margin(-4);
                            } else {
                                at_margin(0);
                            }
                        } else {
                            if (right.statement || right.role === "label") {
                                warn(
                                    "expected_line_break_a_b",
                                    right,
                                    artifact(left),
                                    artifact(right)
                                );
                            }
                            free = false;
                            open = false;
                            no_space_only();
                        }
                    } else {

// If left and right are opener and closer, then the placement of right depends
// on the openness. Illegal pairs (like {]) have already been detected.

                        if (left.line === right.line) {
                            no_space();
                        } else {
                            at_margin(0);
                        }
                    }
                } else {

// If right is a closer, then pop the previous state.

                    if (right.id === closer) {
                        const previous = stack.pop();
                        margin = previous.margin;
                        if (open && right.id !== ";") {
                            at_margin(0);
                        } else {
                            no_space_only();
                        }
                        closer = previous.closer;
                        free = previous.free;
                        open = previous.open;
                        qmark = previous.qmark;
                    } else {

// Left is not an opener, and right is not a closer. The nature of left and
// right will determine the space between them.

// If left is , or ; or right is a statement then if open, right must go at the
// margin, or if closed, a space between.


                        if (right.switch) {
                            unqmark();
                            at_margin(-4);
                        } else if (right.role === "label") {
                            if (right.from !== 0) {
                                expected_at(0);
                            }
                        } else if (left.id === ",") {
                            unqmark();
                            if (!open || (
                                (free || closer === "]")
                                && left.line === right.line
                            )) {
                                one_space();
                            } else {
                                at_margin(0);
                            }

// If right is a ternary operator, line it up on the margin. Use qmark to
// deal with nested ternary operators.

                        } else if (right.arity === "ternary") {
                            if (right.id === "?") {
                                margin += 4;
                                qmark += "?";
                            } else {
                                result = qmark.match(rx_colons);
                                qmark = result[1] + ":";
                                margin -= 4 * result[2].length;
                            }
                            at_margin(0);
                        } else if (
                            right.arity === "binary"
                            && right.id === "("
                            && free
                        ) {
                            no_space();
                        } else if (
                            left.id === "."
                            || left.id === "..."
                            || right.id === ","
                            || right.id === ";"
                            || right.id === ":"
                            || (
                                right.arity === "binary"
                                && (right.id === "(" || right.id === "[")
                            )
                            || (
                                right.arity === "function"
                                && left.id !== "function"
                            )
                        ) {
                            no_space_only();
                        } else if (right.id === ".") {
                            if (left.line === right.line) {
                                no_space();
                            } else {
                                if (!rx_dot.test(qmark)) {
                                    qmark += ".";
                                    margin += 4;
                                }
                                at_margin(0);
                            }
                        } else if (left.id === ";") {
                            unqmark();
                            if (open) {
                                at_margin(0);
                            } else {
                                one_space();
                            }
                        } else if (
                            left.arity === "ternary"
                            || left.id === "case"
                            || left.id === "catch"
                            || left.id === "else"
                            || left.id === "finally"
                            || left.id === "while"
                            || right.id === "catch"
                            || right.id === "else"
                            || right.id === "finally"
                            || (right.id === "while" && !right.statement)
                            || (left.id === ")" && right.id === "{")
                        ) {
                            one_space_only();
                        } else if (right.statement === true) {
                            if (open) {
                                at_margin(0);
                            } else {
                                one_space();
                            }
                        } else if (
                            left.id === "var"
                            || left.id === "const"
                            || left.id === "let"
                        ) {
                            stack.push({
                                closer: closer,
                                free: free,
                                margin: margin,
                                open: open,
                                qmark: qmark
                            });
                            closer = ";";
                            free = false;
                            open = left.open;
                            qmark = "";
                            if (open) {
                                margin = margin + 4;
                                at_margin(0);
                            } else {
                                one_space_only();
                            }
                        } else if (

// There is a space between left and right.

                            spaceop[left.id] === true
                            || spaceop[right.id] === true
                            || (
                                left.arity === "binary"
                                && (left.id === "+" || left.id === "-")
                            )
                            || (
                                right.arity === "binary"
                                && (right.id === "+" || right.id === "-")
                            )
                            || left.id === "function"
                            || left.id === ":"
                            || (
                                (
                                    left.identifier
                                    || left.id === "(string)"
                                    || left.id === "(number)"
                                )
                                && (
                                    right.identifier
                                    || right.id === "(string)"
                                    || right.id === "(number)"
                                )
                            )
                            || (left.arity === "statement" && right.id !== ";")
                        ) {
                            one_space();
                        } else if (left.arity === "unary" && left.id !== "`") {
                            no_space_only();
                        }
                    }
                }
                nr_comments_skipped = 0;
                delete left.calls;
                delete left.dead;
                delete left.free;
                delete left.init;
                delete left.open;
                delete left.used;
                left = right;
            }
        });
    }
788345
function (token) {
            var inline = false;
            if (token) {
                if (token.type === 'LineComment') {
                    inline = true;
                } else if (token.type === 'BlockComment') {
                    inline = (token.value.indexOf('\n') === -1);
                }
            }
            return inline;
        }
928087
function removeComments(obj) {
    const keys = Object.keys(obj);
    const newObj = {};

    for (let i = 0, len = keys.length; i < len; i++) {
      if (!COMMENT_KEY.test(keys[i])) {
        newObj[keys[i]] = obj[keys[i]];
      }
    }

    return newObj;
  }
332033
function codeAroundComment(token) {
            let currentToken = token;

            do {
                currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true });
            } while (currentToken && astUtils.isCommentToken(currentToken));

            if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) {
                return true;
            }

            currentToken = token;
            do {
                currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
            } while (currentToken && astUtils.isCommentToken(currentToken));

            if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) {
                return true;
            }

            return false;
        }
591846
function checkComment(node) {
            if (astUtils.isDirectiveComment(node) && selfConfigRegEx.test(node.value)) {
                return;
            }

            const matches = commentContainsWarningTerm(node.value);

            matches.forEach(matchedTerm => {
                context.report({
                    node,
                    message: "Unexpected '{{matchedTerm}}' comment.",
                    data: {
                        matchedTerm
                    }
                });
            });
        }
1184682
function actPolyfill(cb) {
  ReactDOM.unstable_batchedUpdates(cb)
  ReactDOM.render(<div />, document.createElement('div'))
}
908322
function uncomment(editor, range, modelType) {
	const commentParts = modelComments[modelType];
	const stream = new BufferStreamReader(editor.getBuffer(), range.start, range);

	// narrow down comment range till meanful content
	stream.pos = range.start.translate([0, commentParts.before.length]);
	stream.eatWhile(isSpace);
	stream.start = stream.pos;

	// Make sure comment ends with proper token
	stream.pos = range.end.translate([0, -commentParts.after.length]);
	if (editor.getTextInBufferRange([stream.pos, range.end]) === commentParts.after) {
		while (!stream.sof()) {
			if (!isSpace(stream.backUp(1))) {
				stream.next();
				break;
			}
		}
	} else {
		stream.pos = range.end;
	}

	const start = new Range(range.start, stream.start);
	const end = new Range(stream.pos, range.end);
	const delta = {
		start: editor.getTextInBufferRange(start).length,
		end: editor.getTextInBufferRange(end).length
	};

	editor.setTextInBufferRange(end, '');
	editor.setTextInBufferRange(start, '');

	return delta;
}
368964
function getCommentsList(comments) {
  if (!comments.body || !comments.headers) return;

  let pageInfo = getPage(comments.headers.link);
  let pageList = [];

  comments.body.forEach((item) => {
    pageList.push(getComments(item));
  });

  return {
    page: pageInfo,
    list: pageList
  }
}
171130
function addComment(form) {
    var node_id = form.find('input[name="node"]').val();
    var parent_id = form.find('input[name="parent"]').val();
    var text = form.find('textarea[name="comment"]').val();
    var proposal = form.find('textarea[name="proposal"]').val();

    if (text == '') {
      showError('Please enter a comment.');
      return;
    }

    // Disable the form that is being submitted.
    form.find('textarea,input').attr('disabled', 'disabled');

    // Send the comment to the server.
    $.ajax({
      type: "POST",
      url: opts.addCommentURL,
      dataType: 'json',
      data: {
        node: node_id,
        parent: parent_id,
        text: text,
        proposal: proposal
      },
      success: function(data, textStatus, error) {
        // Reset the form.
        if (node_id) {
          hideProposeChange(node_id);
        }
        form.find('textarea')
          .val('')
          .add(form.find('input'))
          .removeAttr('disabled');
	var ul = $('#cl' + (node_id || parent_id));
        if (ul.data('empty')) {
          $(ul).empty();
          ul.data('empty', false);
        }
        insertComment(data.comment);
        var ao = $('#ao' + node_id);
        ao.find('img').attr({'src': opts.commentBrightImage});
        if (node_id) {
          // if this was a "root" comment, remove the commenting box
          // (the user can get it back by reopening the comment popup)
          $('#ca' + node_id).slideUp();
        }
      },
      error: function(request, textStatus, error) {
        form.find('textarea,input').removeAttr('disabled');
        showError('Oops, there was a problem adding the comment.');
      }
    });
  }
1191845
private void checkJsDocInBlockComments(String fileName) {
    if (!compiler.getOptions().preservesDetailedSourceInfo()) {
      // Comments only available if preservesDetailedSourceInfo is true.
      return;
    }

    for (Comment comment : compiler.getComments(fileName)) {
      if (comment.type == Comment.Type.BLOCK) {
        if (COMMENT_PATTERN.matcher(comment.value).find()) {
          compiler.report(
              JSError.make(
                  fileName,
                  comment.location.start.line + 1,
                  comment.location.start.column,
                  JSDOC_IN_BLOCK_COMMENT));
        }
      }
    }
  }
233443
def addcomment(self, comment, private=False):
        
        # Note: fedora bodhi uses this function
        vals = self.bugzilla.build_update(comment=comment,
                                          comment_private=private)
        log.debug("addcomment: update=%s", vals)

        return self.bugzilla.update_bugs(self.bug_id, vals)
1003130
function toComments(text, level) {
  var indent = '';
  var i;
  for (i = 0; i < level; i++) {
    indent += '  ';
  }
  if (text == null || text.length === 0) {
    return indent;
  }
  const lines = text.trim().split('\n');
  var result = '\n' + indent + '/**\n';
  lines.forEach(line => {
    result += indent + ' *' + (line === '' ? '' : ' ' + line) + '\n';
  });
  result += indent + ' */\n' + indent;
  return result;
}
195178
function ErrorStackParser$$parseOpera11(error) {
	            var filtered = _filter(error.stack.split('\n'), function (line) {
	                return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) &&
	                    !line.match(/^Error created at/);
	            }, this);
	
	            return _map(filtered, function (line) {
	                var tokens = line.split('@');
	                var locationParts = this.extractLocation(tokens.pop());
	                var functionCall = (tokens.shift() || '');
	                var functionName = functionCall
	                        .replace(/<anonymous function(: (\w+))?>/, '$2')
	                        .replace(/\([^\)]*\)/g, '') || undefined;
	                var argsRaw;
	                if (functionCall.match(/\(([^\)]*)\)/)) {
	                    argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1');
	                }
	                var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(',');
	                return new StackFrame(functionName, args, locationParts[0], locationParts[1], locationParts[2], line);
	            }, this);
	        }
1015948
function onComment(block, text, start, stop, startLoc, endLoc) {
      var match;
      commentsByEndLine[endLoc.line] = {
        text: text,
        block: block
      };
      match = text.match(/@module (\w+)/);
      if (match) {
        moduleName = match[1];
        modules.push({
          name: moduleName,
          comment: '/*' + text + '*/\n'
        });
      }
      // Both @module and @namespace may be defined in the same comment block.
      match = text.match(/@(namespace|module) \w+/g);
      if (match) {
        if (text.match(/@method/)) {
          // Don't allow temporary namespace renamings
          // in method block.
          return;
        }
        var namespace = match[match.length - 1].match(/@(namespace|module) (\w+)/)[2];
        namespaceBoundary(namespace, endLoc.line);
      }
    }
988980
function processString(content = '', options = defaultOptions) {

    const comments = []
    const preservedTokens = []

    let pattern

    content = extractDataUrls(content, preservedTokens)
    content = convertRelativeUrls(content, options, preservedTokens)
    content = collectComments(content, comments)

    // preserve strings so their content doesn't get accidentally minified
    pattern = /("([^\\"]|\\.|\\)*")|('([^\\']|\\.|\\)*')/g
    content = content.replace(pattern, token => {
        const quote = token.substring(0, 1)
        token = token.slice(1, -1)
        // maybe the string contains a comment-like substring or more? put'em back then
        if (token.indexOf('___PRESERVE_CANDIDATE_COMMENT_') >= 0) {
            for (let i = 0, len = comments.length; i < len; i += 1) {
                token = token.replace('___PRESERVE_CANDIDATE_COMMENT_' + i + '___', comments[i])
            }
        }
        // minify alpha opacity in filter strings
        token = token.replace(/progid:DXImageTransform.Microsoft.Alpha\(Opacity=/gi, 'alpha(opacity=')
        preservedTokens.push(token)
        return quote + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___' + quote
    })

    // strings are safe, now wrestle the comments
    for (let i = 0, len = comments.length; i < len; i += 1) {

        let token = comments[i]
        let placeholder = '___PRESERVE_CANDIDATE_COMMENT_' + i + '___'

        // ! in the first position of the comment means preserve
        // so push to the preserved tokens keeping the !
        if (token.charAt(0) === '!') {
            if (options.cuteComments) {
                preservedTokens.push(token.substring(1).replace(/\r\n/g, '\n'))
            } else if (options.uglyComments) {
                preservedTokens.push(token.substring(1).replace(/[\r\n]/g, ''))
            } else {
                preservedTokens.push(token)
            }
            content = content.replace(placeholder, ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___')
            continue
        }

        // \ in the last position looks like hack for Mac/IE5
        // shorten that to /*\*/ and the next one to /**/
        if (token.charAt(token.length - 1) === '\\') {
            preservedTokens.push('\\')
            content = content.replace(placeholder, ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___')
            i = i + 1 // attn: advancing the loop
            preservedTokens.push('')
            content = content.replace(
                '___PRESERVE_CANDIDATE_COMMENT_' + i + '___',
                ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___'
            )
            continue
        }

        // keep empty comments after child selectors (IE7 hack)
        // e.g. html >/**/ body
        if (token.length === 0) {
            let startIndex = content.indexOf(placeholder)
            if (startIndex > 2) {
                if (content.charAt(startIndex - 3) === '>') {
                    preservedTokens.push('')
                    content = content.replace(placeholder, ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___')
                }
            }
        }

        // in all other cases kill the comment
        content = content.replace(`/*${placeholder}*/`, '')
    }

    // parse simple @variables blocks and remove them
    if (options.expandVars) {
        const vars = {}
        pattern = /@variables\s*\{\s*([^\}]+)\s*\}/g
        content = content.replace(pattern, (_, f1) => {
            pattern = /\s*([a-z0-9\-]+)\s*:\s*([^;\}]+)\s*/gi
            f1.replace(pattern, (_, f1, f2) => {
                if (f1 && f2) {
                    vars[f1] = f2
                }
                return ''
            })
            return ''
        })

        // replace var(x) with the value of x
        pattern = /var\s*\(\s*([^\)]+)\s*\)/g
        content = content.replace(pattern, (_, f1) => {
            return vars[f1] || 'none'
        })
    }

    // normalize all whitespace strings to single spaces. Easier to work with that way.
    content = content.replace(/\s+/g, ' ')

    // preserve formulas in calc() before removing spaces
    pattern = /calc\(([^;}]*)\)/g
    content = content.replace(pattern, (_, f1) => {
        preservedTokens.push(
            'calc(' +
            f1.replace(/(^\s*|\s*$)/g, '')
                .replace(/\( /g, '(')
                .replace(/ \)/g, ')') +
            ')'
        )
        return ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___'
    })

    // preserve matrix
    pattern = /\s*filter:\s*progid:DXImageTransform.Microsoft.Matrix\(([^\)]+)\);/g
    content = content.replace(pattern, (_, f1) => {
        preservedTokens.push(f1)
        return 'filter:progid:DXImageTransform.Microsoft.Matrix(' + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___);'
    })

    // remove the spaces before the things that should not have spaces before them.
    // but, be careful not to turn 'p :link {...}' into 'p:link{...}'
    // swap out any pseudo-class colons with the token, and then swap back.
    pattern = /(^|\})(([^\{:])+:)+([^\{]*\{)/g
    content = content.replace(pattern, token => token.replace(/:/g, '___PSEUDOCLASSCOLON___'))

    // remove spaces before the things that should not have spaces before them.
    content = content.replace(/\s+([!{};:>+\(\)\],])/g, '$1')

    // restore spaces for !important
    content = content.replace(/!important/g, ' !important')

    // bring back the colon
    content = content.replace(/___PSEUDOCLASSCOLON___/g, ':')

    // preserve 0 followed by a time unit for properties using time units
    pattern = /\s*(animation|animation-delay|animation-duration|transition|transition-delay|transition-duration):\s*([^;}]+)/gi
    content = content.replace(pattern, (_, f1, f2) => {

        f2 = f2.replace(/(^|\D)0?\.?0(m?s)/gi, (_, g1, g2) => {
            preservedTokens.push('0' + g2)
            return g1 + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___'
        })

        return f1 + ':' + f2
    })

    // preserve unit for flex-basis within flex and flex-basis (ie10 bug)
    pattern = /\s*(flex|flex-basis):\s*([^;}]+)/gi
    content = content.replace(pattern, (_, f1, f2) => {
        let f2b = f2.split(/\s+/)
        preservedTokens.push(f2b.pop())
        f2b.push(___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___')
        f2b = f2b.join(' ')
        return `${f1}:${f2b}`
    })

    // preserve 0% in hsl and hsla color definitions
    content = content.replace(/(hsla?)\(([^)]+)\)/g, (_, f1, f2) => {
        var f0 = []
        f2.split(',').forEach(part => {
            part = part.replace(/(^\s+|\s+$)/g, '')
            if (part === '0%') {
                preservedTokens.push('0%')
                f0.push(___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + '___')
            } else {
                f0.push(part)
            }
        })
        return f1 + '(' + f0.join(',') + ')'
    })

    // preserve 0 followed by unit in keyframes steps (WIP)
    content = keyframes(content, preservedTokens)

    // retain space for special IE6 cases
    content = content.replace(/:first-(line|letter)(\{|,)/gi, (_, f1, f2) => ':first-' + f1.toLowerCase() + ' ' + f2)

    // newlines before and after the end of a preserved comment
    if (options.cuteComments) {
        content = content.replace(/\s*\/\*/g, '___PRESERVED_NEWLINE___/*')
        content = content.replace(/\*\/\s*/g, '*/___PRESERVED_NEWLINE___')
        // no space after the end of a preserved comment
    } else {
        content = content.replace(/\*\/\s*/g, '*/')
    }

    // If there are multiple @charset directives, push them to the top of the file.
    pattern = /^(.*)(@charset)( "[^"]*";)/gi
    content = content.replace(pattern, (_, f1, f2, f3) => f2.toLowerCase() + f3 + f1)

    // When all @charset are at the top, remove the second and after (as they are completely ignored).
    pattern = /^((\s*)(@charset)( [^;]+;\s*))+/gi
    content = content.replace(pattern, (_, __, f2, f3, f4) => f2 + f3.toLowerCase() + f4)

    // lowercase some popular @directives (@charset is done right above)
    pattern = /@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)/gi
    content = content.replace(pattern, (_, f1) => '@' + f1.toLowerCase())

    // lowercase some more common pseudo-elements
    pattern = /:(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)/gi
    content = content.replace(pattern, (_, f1) => ':' + f1.toLowerCase())

    // if there is a @charset, then only allow one, and push to the top of the file.
    content = content.replace(/^(.*)(@charset \"[^\"]*\";)/g, '$2$1')
    content = content.replace(/^(\s*@charset [^;]+;\s*)+/g, '$1')

    // lowercase some more common functions
    pattern = /:(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?any)\(/gi
    content = content.replace(pattern, (_, f1) => ':' + f1.toLowerCase() + '(')

    // lower case some common function that can be values
    // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us right after this
    pattern = /([:,\( ]\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)/gi
    content = content.replace(pattern, (_, f1, f2) => f1 + f2.toLowerCase())

    // put the space back in some cases, to support stuff like
    // @media screen and (-webkit-min-device-pixel-ratio:0){
    content = content.replace(/\band\(/gi, 'and (')

    // remove the spaces after the things that should not have spaces after them.
    content = content.replace(/([!{}:;>+\(\[,])\s+/g, '$1')

    // remove unnecessary semicolons
    content = content.replace(/;+\}/g, '}')

    // replace 0(px,em,%) with 0.
    content = content.replace(/(^|[^.0-9\\])(?:0?\.)?0(?:ex|ch|r?em|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|g?rad|turn|m?s|k?Hz|dpi|dpcm|dppx|%)/gi, '$10')

    // Replace x.0(px,em,%) with x(px,em,%).
    content = content.replace(/([0-9])\.0(ex|ch|r?em|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|g?rad|turn|m?s|k?Hz|dpi|dpcm|dppx|%| |;)/gi, '$1$2')

    // replace 0 0 0 0; with 0.
    content = content.replace(/:0 0 0 0(;|\})/g, ':0$1')
    content = content.replace(/:0 0 0(;|\})/g, ':0$1')
    content = content.replace(/:0 0(;|\})/g, ':0$1')

    // replace background-position:0; with background-position:0 0;
    // same for transform-origin and box-shadow
    pattern = /(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin|box-shadow):0(;|\})/gi
    content = content.replace(pattern, (_, f1, f2) => f1.toLowerCase() + ':0 0' + f2)

    // replace 0.6 to .6, but only when preceded by : or a white-space
    content = content.replace(/(:|\s)0+\.(\d+)/g, '$1.$2')

    // shorten colors from rgb(51,102,153) to #336699
    // this makes it more likely that it'll get further compressed in the next step.
    pattern = /rgb\s*\(\s*([0-9,\s]+)\s*\)/gi
    content = content.replace(pattern, (_, f1) => {
        const rgbcolors = f1.split(',')
        let hexcolor = '#'
        for (let i = 0; i < rgbcolors.length; i += 1) {
            let val = parseInt(rgbcolors[i], 10)
            if (val < 16) {
                hexcolor += '0'
            }
            if (val > 255) {
                val = 255
            }
            hexcolor += val.toString(16)
        }
        return hexcolor
    })

    // Shorten colors from #AABBCC to #ABC.
    content = compressHexColors(content)

    // Replace #f00 -> red
    content = content.replace(/(:|\s)(#f00)(;|})/g, '$1red$3')

    // Replace other short color keywords
    content = content.replace(/(:|\s)(#000080)(;|})/g, '$1navy$3')
    content = content.replace(/(:|\s)(#808080)(;|})/g, '$1gray$3')
    content = content.replace(/(:|\s)(#808000)(;|})/g, '$1olive$3')
    content = content.replace(/(:|\s)(#800080)(;|})/g, '$1purple$3')
    content = content.replace(/(:|\s)(#c0c0c0)(;|})/g, '$1silver$3')
    content = content.replace(/(:|\s)(#008080)(;|})/g, '$1teal$3')
    content = content.replace(/(:|\s)(#ffa500)(;|})/g, '$1orange$3')
    content = content.replace(/(:|\s)(#800000)(;|})/g, '$1maroon$3')

    // border: none -> border:0
    pattern = /(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|\})/gi
    content = content.replace(pattern, (_, f1, f2) => f1.toLowerCase() + ':0' + f2)

    // shorter opacity IE filter
    content = content.replace(/progid:DXImageTransform\.Microsoft\.Alpha\(Opacity=/gi, 'alpha(opacity=')

    // Find a fraction that is used for Opera's -o-device-pixel-ratio query
    // Add token to add the '\' back in later
    content = content.replace(/\(([\-A-Za-z]+):([0-9]+)\/([0-9]+)\)/g, '($1:$2___QUERY_FRACTION___$3)')

    // remove empty rules.
    content = content.replace(/[^\};\{\/]+\{\}/g, '')

    // Add '\' back to fix Opera -o-device-pixel-ratio query
    content = content.replace(/___QUERY_FRACTION___/g, '/')

    // some source control tools don't like it when files containing lines longer
    // than, say 8000 characters, are checked in. The linebreak option is used in
    // that case to split long lines after a specific column.
    if (options.maxLineLen > 0) {
        const lines = []
        let line = []
        for (let i = 0, len = content.length; i < len; i += 1) {
            let ch = content.charAt(i)
            line.push(ch)
            if (ch === '}' && line.length > options.maxLineLen) {
                lines.push(line.join(''))
                line = []
            }
        }
        if (line.length) {
            lines.push(line.join(''))
        }

        content = lines.join('\n')
    }

    // replace multiple semi-colons in a row by a single one
    // see SF bug #1980989
    content = content.replace(/;;+/g, ';')

    // trim the final string (for any leading or trailing white spaces)
    content = content.replace(/(^\s*|\s*$)/g, '')

    // restore preserved tokens
    for (let i = preservedTokens.length - 1; i >= 0; i--) {
        content = content.replace(___PRESERVED_TOKEN_ + i + '___', preservedTokens[i], 'g')
    }

    // restore preserved newlines
    content = content.replace(/___PRESERVED_NEWLINE___/g, '\n')

    // return
    return content
}