tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

isMinified.js (1565B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
      4 
      5 import { isFulfilled } from "./async-value";
      6 
      7 // Used to detect minification for automatic pretty printing
      8 const SAMPLE_SIZE = 50;
      9 const INDENT_COUNT_THRESHOLD = 5;
     10 const CHARACTER_LIMIT = 250;
     11 const _minifiedCache = new Map();
     12 
     13 export function isMinified(source, sourceTextContent) {
     14  if (_minifiedCache.has(source.id)) {
     15    return _minifiedCache.get(source.id);
     16  }
     17 
     18  if (
     19    !sourceTextContent ||
     20    !isFulfilled(sourceTextContent) ||
     21    sourceTextContent.value.type !== "text"
     22  ) {
     23    return false;
     24  }
     25 
     26  let text = sourceTextContent.value.value;
     27 
     28  let lineEndIndex = 0;
     29  let lineStartIndex = 0;
     30  let lines = 0;
     31  let indentCount = 0;
     32  let overCharLimit = false;
     33 
     34  // Strip comments.
     35  text = text.replace(/\/\*[\S\s]*?\*\/|\/\/(.+|\n)/g, "");
     36 
     37  while (lines++ < SAMPLE_SIZE) {
     38    lineEndIndex = text.indexOf("\n", lineStartIndex);
     39    if (lineEndIndex == -1) {
     40      break;
     41    }
     42    if (/^\s+/.test(text.slice(lineStartIndex, lineEndIndex))) {
     43      indentCount++;
     44    }
     45    // For files with no indents but are not minified.
     46    if (lineEndIndex - lineStartIndex > CHARACTER_LIMIT) {
     47      overCharLimit = true;
     48      break;
     49    }
     50    lineStartIndex = lineEndIndex + 1;
     51  }
     52 
     53  const minified =
     54    (indentCount / lines) * 100 < INDENT_COUNT_THRESHOLD || overCharLimit;
     55 
     56  _minifiedCache.set(source.id, minified);
     57  return minified;
     58 }