All files / public/admin media-domain.js

97.7% Statements 85/87
90.35% Branches 103/114
100% Functions 23/23
98.73% Lines 78/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 19627x     27x 27x     12x 12x       6x 6x 6x   6x 1x 1x   5x 1x   5x 1x   5x 1x   5x 1x   5x       5x 5x       5x 5x 4x 2x 2x 2x   2x     1x 1x 6x   2x   1x       2x 2x 2x 1x 1x             14x 14x     12x         12x 4x           8x 8x 6x 4x 2x                                         14x 14x 14x                       7x 7x 7x   1x         2x 2x 3x 3x         5x 15x 10x         3x 3x 3x 6x   3x               2x 2x 4x 2x   2x       19x 60x 60x           27x                     1x      
(function () {
  "use strict";
 
  var RASTER = /\.(jpe?g|png|webp)$/i;
  var RETAINED = /\.(gif|svg|mp4)$/i;
 
  function extension(name) {
    var match = String(name || "").toLowerCase().match(/\.[^.]+$/);
    return match ? match[0] : "";
  }
 
  function validateFile(file, cover) {
    var errors = [];
    var ext = extension(file && file.name);
    var size = Number(file && file.size) || 0;
 
    if (!RASTER.test(ext) && !RETAINED.test(ext)) {
      errors.push("仅支持 JPEG、PNG、WebP、GIF、SVG 或 MP4");
      return errors;
    }
    if (cover && !RASTER.test(ext)) {
      errors.push("封面仅支持 JPEG、PNG 或 WebP 静态图片");
    }
    if (ext === ".svg" && size > 1024 * 1024) {
      errors.push("SVG 不能超过 1MB");
    }
    if (ext === ".gif" && size > 5 * 1024 * 1024) {
      errors.push("GIF 不能超过 5MB");
    }
    if (ext === ".mp4" && size > 10 * 1024 * 1024) {
      errors.push("MP4 不能超过 10MB");
    }
    return errors;
  }
 
  function targetExtension(file) {
    var ext = extension(file && file.name);
    return RASTER.test(ext) ? ".webp" : ext;
  }
 
  function nextFileName(existing, cover, ext) {
    var names = Array.isArray(existing) ? existing : [];
    if (cover) {
      if (names.indexOf("cover" + ext) === -1) return "cover" + ext;
      var coverIndex = 2;
      while (names.indexOf("cover-" + String(coverIndex).padStart(2, "0") + ext) !== -1) {
        coverIndex += 1;
      }
      return "cover-" + String(coverIndex).padStart(2, "0") + ext;
    }
 
    var index = 1;
    while (names.some(function (name) {
      return new RegExp("^image-" + String(index).padStart(2, "0") + "\\.", "i").test(name);
    })) {
      index += 1;
    }
    return "image-" + String(index).padStart(2, "0") + ext;
  }
 
  function fitDimensions(width, height, maxEdge) {
    var limit = maxEdge || 1600;
    var longest = Math.max(width, height);
    if (!longest || longest <= limit) return { width: width, height: height };
    var ratio = limit / longest;
    return {
      width: Math.max(1, Math.round(width * ratio)),
      height: Math.max(1, Math.round(height * ratio)),
    };
  }
 
  function decodeHtmlEntities(value) {
    var text = String(value || "");
    return text.replace(
      /&(?:#x([0-9a-f]+)|#([0-9]+)|(amp|lt|gt|quot|apos));/gi,
      function (match, hex, decimal, named) {
        var codePoint = hex
          ? parseInt(hex, 16)
          : decimal
            ? parseInt(decimal, 10)
            : null;
        if (codePoint !== null) {
          return codePoint > 0 &&
            codePoint <= 0x10ffff &&
            !(codePoint >= 0xd800 && codePoint <= 0xdfff)
            ? String.fromCodePoint(codePoint)
            : "\uFFFD";
        }
        Iif (named === "amp") return "&";
        if (named === "lt") return "<";
        if (named === "gt") return ">";
        if (named === "quot") return '"';
        Eif (named === "apos") return "'";
        return match;
      },
    );
  }
 
  /**
   * Blacklist-style SVG safety check for the CMS upload path.
   *
   * The check runs before an SVG enters the repository, so it rejects
   * executable content instead of sanitizing it in place. To close the
   * common encoding bypasses it first decodes HTML entities and removes
   * whitespace, then scans for script/foreignObject elements, event
   * handler attributes, javascript: URLs and inline data: payloads.
   *
   * This is deliberately conservative: legitimate SVGs containing these
   * literal strings are rejected. A full allowlist parser would be more
   * precise and is the recommended upgrade if SVG uploads ever become
   * multi-user.
   */
  function isSafeSvg(source) {
    var decoded = decodeHtmlEntities(String(source || ""));
    var compact = decoded.replace(/\s+/g, "");
    return !(
      /<script\b/i.test(compact) ||
      /<foreignobject\b/i.test(compact) ||
      /on[a-z]+\s*=/i.test(compact) ||
      /javascript:/i.test(compact) ||
      /(?:href|xlink:href|src)\s*=\s*["']?data:|url\(\s*["']?data:|@import\s*["']?data:/i.test(
        compact,
      )
    );
  }
 
  function normalizeMediaReference(value) {
    var path = String(value || "").split(/[?#]/, 1)[0];
    try {
      return decodeURIComponent(path);
    } catch (_error) {
      return path;
    }
  }
 
  function classifyMedia(files, references) {
    var known = new Set((Array.isArray(references) ? references : []).map(normalizeMediaReference));
    return (Array.isArray(files) ? files : []).map(function (file) {
      var publicPath = "/" + String(file.path || "").replace(/^public\//, "");
      return { path: file.path, referenced: known.has(normalizeMediaReference(publicPath)) };
    });
  }
 
  function deletionPaths(files) {
    return (Array.isArray(files) ? files : [])
      .filter(function (file) { return file && file.referenced === false; })
      .map(function (file) { return String(file.path || ""); })
      .filter(Boolean);
  }
 
  function deletionSelectionState(files, selectedPaths) {
    var paths = deletionPaths(files);
    var selected = new Set(Array.isArray(selectedPaths) ? selectedPaths : []);
    var selectedCount = paths.reduce(function (count, path) {
      return count + (selected.has(path) ? 1 : 0);
    }, 0);
    return {
      paths: paths,
      checked: paths.length > 0 && selectedCount === paths.length,
      indeterminate: selectedCount > 0 && selectedCount < paths.length,
    };
  }
 
  function toggleDeletionSelection(selectedPaths, files, checked) {
    var selected = new Set(Array.isArray(selectedPaths) ? selectedPaths : []);
    deletionPaths(files).forEach(function (path) {
      if (checked) selected.add(path);
      else selected.delete(path);
    });
    return Array.from(selected);
  }
 
  function urlTitleSegment(title) {
    return Array.from(String(title || "").trim()).map(function (character) {
      var codePoint = character.codePointAt(0) || 0;
      return codePoint > 127 || /^[A-Za-z0-9._~-]$/.test(character)
        ? character
        : "%" + codePoint.toString(16).toUpperCase().padStart(2, "0");
    }).join("");
  }
 
  window.DecapMediaDomain = {
    validateFile: validateFile,
    targetExtension: targetExtension,
    nextFileName: nextFileName,
    fitDimensions: fitDimensions,
    isSafeSvg: isSafeSvg,
    classifyMedia: classifyMedia,
    normalizeMediaReference: normalizeMediaReference,
    deletionSelectionState: deletionSelectionState,
    toggleDeletionSelection: toggleDeletionSelection,
    urlTitleSegment: urlTitleSegment,
    isRaster: function (file) { return RASTER.test(extension(file && file.name)); },
  };
})();